如何创建在 VisualStudio 中使用的新语言

我想编写一种新的模板语言,我希望 VisualStudio 能够“支持”它。我需要知道的是:

  1. 如何解析我的新语言?
    给定我的新模板语言中的一些代码,我如何将其翻译成 HTML?现在我使用正则表达式来逐个标记地解析它,但是我不认为这样可以很好地伸缩,因为语言变得更加复杂,而且没有错误检查。我听说过 ANTLR,但从没用过。这是这项工作的正确工具,还是有更简单的方法?理想情况下,我希望向错误窗口发送任何语法错误,并像其他语言那样提供尽可能多的信息(行 # ,错误类型)。
  2. 如何为 VisualStudio 创建新的文件类型?
  3. 我怎样才能得到语法突显?
    我是否可以使用在步骤1中创建的解析器,或者这是完全不同的东西?
  4. 我怎样才能获得智能感知?

我更喜欢用 C # 编写解析器。

26666 次浏览

I would take a look at another language that has already done the legwork of integrating with Visual Studio. A great example is Boo. The language and Visual Studio integration are open source. So you can take a look at exactly what they had to do.

The Boo Syntax Highlighting for VS2010 includes some recommended links on its homepage, which I'll copy for easy reference:

Regarding the Visual Studio aspects, what you need is a "language service", which is the entity that handles colorizing, intellisense, etc. for a given file extension/type.

For an intro, see this article
And for a code sample see here

Regarding parsing, there are lots of technologies, and I won't offer an opinion/advice.

Beware, there is a fair amount of work involved, although in my opinion it is much more straightforward in VS2010 than in previous versions of Visual Studio to provide this kind of extension.

See also

Visual Studio 2010 Extensibility, MPF and language services

There is a sample in the VS SDK that shows most of the features you are looking for.

I wrote a VS Language Service using this article as my basis: http://www.codeproject.com/KB/recipes/VSLanguageService.aspx

It wasn't too bad if you have a basic handle on Grammars.

I found this very useful collection of recent samples for Visual Studio 2013 SDK: http://blogs.msdn.com/b/vsx/archive/2014/05/30/vs-2013-sdk-samples-released.aspx

It also contains the recent version of the OokLanguage which sounds promising.

We used ANTLR 4 to parse our language which works like a charm and allows direct interaction with C# code. Can totally recommend it.

I was using VS with own language and desperately needed a syntax highlight. I built mine based on this tutorial: https://mattduffield.wordpress.com/2012/07/31/writing-a-brightscript-syntax-highlight-extension-for-visual-studio-2010/

I know the tutorial is in VS2010. I made mine in VS2012 with no or very small hiccups. (also worked in VS2013) Recently I changed to VS2015 and the solution can be edited, built with no problem.

As mentioned in other answers, the most interesting code sample is the Ook language extension for the latest version of Visual Studio (2017 at the time of writing).

For VS 2015 see the sample in the VS2015 branch.

In order to install the SDK for 2015 or later, you need to rerun the VS setup. In 2015 it's called "Visual Studio Extensibility Tools Update 3".