Fun with Code Diagnostic Analyzers

A few days ago I posted an article detailing how to construct a code diagnostic analyzer and code fix provider to detect if..else statements that simply assign a variable or return a value and replace the statements with a conditional operator. You know, the kind of things that code diagnostic analyzers and code fix providers are intended for. As I was developing those components I got to thinking about what kind of fun I could have while abusing the feature. More specifically, I wondered whether could I construct a code diagnostic analyzer such that it would highlight every line of C# code as a warning and recommend using F# instead.

It turns out, it’s actually really easy. The trick is to register a syntax tree action rather than a syntax node action and always report the diagnostic rule at the tree’s root location. For an extra bit of fun, I also set the diagnostic rule’s help link to fsharp.org so that clicking the link in the error list directs the user to that site.

Here’s the analyzer’s code listing in its entirety:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

namespace UseFSharpAnalyzer
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class UseFSharpAnalyzerAnalyzer : DiagnosticAnalyzer
    {
        internal static DiagnosticDescriptor Rule =
            new DiagnosticDescriptor(
                "UseFSharpAnalyzer",
                "Use F#",
                "You're using C#; Try F# instead!",
                "Language Choice",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                helpLink: "http://fsharp.org");

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterSyntaxTreeAction(AnalyzeTree);
        }

        private static void AnalyzeTree(SyntaxTreeAnalysisContext context)
        {
            var rootLocation = context.Tree.GetRoot().GetLocation();
            var diag = Diagnostic.Create(Rule, rootLocation);

            context.ReportDiagnostic(diag);
        }
    }
}

When applied to a C# file, the result is as follows:

Use F# Analyzer

This is clearly an example of what not to do with code analyzers but it was fun to put together and see the result nonetheless. If you’ve thought of any other entertaining uses for code analyzers, I’d love to hear about them!

IndyF#

Indianapolis F# Developers Coding Dojo

There’s a new developer group in town! The inaugural meeting of the Indianapolis F# Developers group is upon us. On Tuesday, November 18th I’ll be leading the group through the Digit Recognizer dojo from Community for F#!

Since I suspect we’ll have some people new to the language, we’ll spend some time talking about some language concepts that are critical to successfully completing the exercise. Make sure you bring a laptop because after the introduction we’ll then split into a few groups (pairs, probably) and work through the problem together. After some time we’ll come back together as a group to talk about the problem and discuss some of the ways that F# lets you focus on the task at hand.

If F#, functional programming, and/or machine learning are of interest to you, please register for the event on our meetup page. We’ll be meeting in the 20 person meeting room at Launch Fishers. The meetup starts at 7:00 PM. We’d love for you to join us!

I Can Analyze Code, And So Can You

Over the past several years, Microsoft has been hard at work on the .NET Compiler Platform (formerly Roslyn). Shipping with Visual Studio 2015 the .NET Compiler Platform includes a complete rewrite of the C# and Visual Basic compilers intended to bring features that developers have come to expect from modern compilers. In addition to the shiny new compilers the .NET Compiler Platform introduces a rich set of APIs that we can harness to build custom code diagnostic analyzers and code fix providers thus allowing us to detect and correct issues in our code.

When trying to decide on a useful demonstration for these features I thought of one of my coding pet peeves: using an if..else statement to conditionally set a variable or return a value. I prefer treating these scenarios as an expression via the conditional (ternary) operator and I often find myself refactoring these patterns in legacy code. It certainly would be nice to automate that process. It turns out that this is exactly the type of task at which diagnostic analyzers and code fix providers excel and we’ll walk through the process of creating such components in this post. (more…)

Recursive AngularJS Directives

It has been a long time since I’ve done any greenfield UI development. Most of my projects over the past several years have involved extending existing Web Forms or ASP.NET MVC apps with some new controls here or there. You can imagine my delight in being able to work on a brand new system with AngularJS as the front-end technology.

I’ve heard a number of good things about AngularJS over the past year or so and have familiarized myself with enough of its core concepts to hold (hopefully) an intelligent conversation about it but this is my first time actually using it on a real project. Given that I still have plenty to learn it didn’t surprise me too much when I encountered my first real roadblock – a recursive directive. (more…)

Talking TypeScript in Fort Wayne

I’ll be back in Fort Wayne on October 15 to talk about TypeScript. If writing JavaScript frustrates you or you just want to be more productive, join NUFW at the Cole Foundation Conference and Training Center to learn how leveraging TypeScript in your existing projects can lead to cleaner and more expressive code.

Please visit the NUFW site for logistics and registration details.

I hope to see you there!

Musings on C#’s Evolution

Since completing my series on likely C# 6.0 features and reviewing the draft spec for record classes and pattern matching in C#, I’ve had some time to reflect on how C# has evolved and think about where it’s going from a more holistic perspective.

I’ve been working with C# for approximately 12 years. It was the language of choice at the beginning of my career so, in a sense, C# and I have grown up together. During that time I’ve watched what was essentially a Java clone grow into the powerhouse it is today. It’s a bit cliché, but when I started working with C# it didn’t have many of the features I now take for granted. Things like generics, the null coalescing operator, lambda expressions, extension methods, anonymous types, dynamics, and async/await were in their infancy with some as much as a decade away. It seems that every major release has brought a slew of compelling new features that have dramatically improved the language.

As I look at the code I write today I often wonder how C# developers managed without generics. I remember the headaches of dealing with ArrayList and its early kin and having to trust that the objects in the collections were actually the types we thought they were. Today I often look at blocks of imperative code (typically loops) that see that they’re doing nothing more than explicitly filtering, mapping, and reducing sequences. I immediately think how much cleaner the code would be with LINQ. And in today’s world of connected mobile devices where application responsiveness is of primary importance, async/await make asynchronous development accessible to the masses. These are all incredible tools we have at our disposal and are all among the reasons I’ve stuck with .NET development for so long.

C# 6 is different. With C# 6, the language enhancement is the Roslyn compiler. Roslyn promises to bring modern compilation strategies to C#. This is a huge undertaking and heavily impacts how we’ll interact with code through Visual Studio and other tools. I haven’t looked at Roslyn nearly as much as I’d like but I do believe the new compiler is long overdue and will pay dividends in the long run for developers and Microsoft alike. That said, the actual changes to the C# language itself seem to range from lackluster to pointless.

I’m not saying that the language features are all bad; several of them will likely be welcome additions to the language. Enhancements such as primary constructors, auto-implemented property initializers, and using static are each things that can have an immediate impact on developer productivity and are by far my favorites of the lot. Other features, such as index initializers, params IEnumerable<T>, and expression-bodied members don’t really seem to add much to the language due to either existing syntactic constructs or other limitations of the language.

Is initializing dictionary elements with [7] = "seven" really any better than with { 7, "seven" }? All the index initializer achieves is trading a pair of curly braces and a comma for a pair of square brackets and an assignment operator, respectively. How is params IEnumerable<int> better than params int[] if the argument list is still converted to an array at the call site and no other usage requires defining the parameter with the params modifier? Finally, expression-bodied members could be a great feature if C# was an expression-based language but it’s not – it’s statement-based. The proposed semicolon operator could greatly increase the usefulness of expression-bodied members but at the time of this writing, it’s still listed as “Maybe” on the Language Feature Implementation Status page. Even then, the semicolon operator feels like an attempt to coerce C# into being expression-based when it was never intended to be treated as such. In the meantime, there’s already a perfectly viable alternative – write a function!

Looking further into the future brings us to the draft spec for record classes and pattern matching. (Please note that since this spec is a draft, everything here is subject to change; whatever does get implemented, if anything, may or may not look like this proposal.) If you haven’t read the draft (and I highly recommend that you do), it proposes a new record modifier for class definitions. This modifier would instruct the compiler to generate an immutable class with built-in structural equality and an is operator (if not provided). The is operator can then be used in if and switch statements for type checking and value extractions.

For example, we could define a class like this (example taken from the proposal):

public record class Cartesian(double x: X, double y: Y);

…then use pattern matching constructs like this (adapted from the proposal):

if (expr is Cartesian c)
{
  // code using c
}

My initial reaction when I heard about these features was excitement but the more I read and the more I think about it, the less I like them, pattern matching in particular. I’ll be the last person to argue against immutability and pattern matching, especially when looking at them from a functional programming mindset. I do like the simplicity of the immutable record classes and I don’t mind that pattern matching is essentially an extension of the is operator.

The reason I don’t like these features as proposed is that they don’t feel like they belong in C#. I feel like this for a few reasons. First, pattern matching can improve code’s expressiveness but merely adding it to a language that wasn’t constructed with pattern matching in mind severely limits its usefulness. Second, the overall expressiveness is again limited by the fact that C# isn’t an expression-based language; pattern matching might make if statements and switch statements more concise, it doesn’t change the fact that they’re still statements!

Let’s contrast the proposal with an expression-based language where pattern matching is already a central concept: F#. As an expression-based language, virtually everything in F# is an expression. This includes familiar constructs like ifs and matches. By definition, as expressions these constructs return values – there’s no need to rely on mutability or wrap the behavior within a separate function, returning from each branch as we must in a statement-based language. For example, this is valid F#:

let x = if System.Random().Next(10) % 2 = 0 then "even" else "odd"

You could correctly argue that C# provides the conditional operator for this scenario but that doesn’t change the fact that in C#, if is a statement whereas in F# it’s an expression. Furthermore, what’s probably not apparent here if you’re not familiar with F# is that binding x is a pattern match. You can see this in action by replacing x with an underscore (F#’s wildcard pattern matches everything and tosses out the result) as follows:

let _ = if System.Random().Next(10) % 2 = 0 then "even" else "odd"

If you evaluate the expression in F# Interactive (FSI) you’ll see that it executes successfully but no value is bound as we’d expect due to the wildcard. For further proof, this is also how tuple binding works as evidenced here:

let value, category =
  let r = System.Random().Next(10)
  r, if r % 2 = 0 then "even" else "odd"

The expression following the assignment in the above snippet returns a tuple containing a random value and whether that value is even or odd. The tupled items are then bound to value and category respectively by using pattern matching.

Pattern matching completely permeates F#. It’s not restricted to match expressions or inline bindings; it even works in function signatures and as a filter in looping constructs! The C# proposal doesn’t talk about pattern matching outside the context of if statements and switches so discussing whether C# will embrace pattern matching as fully as F# is pure speculation but it certainly doesn’t sound particularly promising at this point. Even if pattern matching is supported outside of if and switch statements, it’s still the same underlying statement-based language.

My point in writing all of this is that for years C# has been becoming increasingly functional, with the strongest push coming in version 3 and subsequent releases building upon that foundation. Many of the features in C# 6.0 continue even further down that path by elevating expressions an even more important concept within the language. Finally, a future incarnation of the language will likely include some form of immutable class syntax and pattern matching. If this is the direction that C# is going, my question is this: Why wait for it? Why not learn a functional language to at least supplement the object-oriented language you already know?

The C# of the future is already here and it’s called F#. F# already has a modern compiler; it already supports many of the things slowly making their way into C# and much, much more. In other words, there’s no reason to wait for these things to make it into C# because F# already does them! Incorporating F# into your existing solutions isn’t a mutually exclusive proposition. As a CLR language, F# compiles to the same IL, targets the same runtimes (with few exceptions), and uses the same libraries with which you’re already familiar. In many cases it’s a perfect complement to or replacement for existing C# code.

I challenge you to try F#. Experiment with the features; see how many things you can spot that are “recent” additions to C#, making their way to C#, or not possible at all. I think you’ll be pleasantly surprised at how adopting an expression-based, functional-first language can change the way you think, improve the quality of your code, and make you more productive. If you accept this challenge, I recommend checking out my book or any of the great resources listed on my Learning F# page to get you started.

Community Calendar – IndySA – September 18

IndySA is on a roll with great speakers. This month, Phil Japikse will lead the group in an interactive workshop covering user story mapping. If you want to improve your user story organization and prioritization skills, you won’t want to miss this one as Phil will guide the group through creating a user map, clearly defining order, minimal marketing features, and release plans.

I’ve been fortunate to attend a number of Phil’s previous talks and had have always learned something. You can register and find full logistics information by following the link below.

Register Here

I hope to see you there!