向 C++ 源代码添加注解语法 [英] Adding Annotation Syntax to C++ Source

查看:18
本文介绍了向 C++ 源代码添加注解语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 C++ 源代码中创建我自己的自定义注释(就像 Java 风格的注释)标签.由于标准 C++ 语法不允许注释,我想根据自己的需要修改/增强编译器.

I want to create my own custom annotation (just like the Java style annotation) tags in my C++ source. Since standard C++ syntax doesn't allow annotation, I'd like to modify/enhance the compiler for my own needs.

但是 Visual Studio 是否公开其编译器内部结构供用户修改(例如,其词法分析器的输出、抽象语法树等)?如果没有,是否有任何第三方工具可以解析 C++ 语法并允许我根据自己的注释发出自己定制的 C++ 源代码?

But does Visual Studio expose its compiler internals for users to modify (e.g. output of its lexer, abstract syntax tree, etc)? If not, are there any third party tools for parsing c++ syntax and allow me to emit my own customized c++ source base on my own annotation?

推荐答案

对于此类问题的标准解决方案,如果它是在非 C++ 的编程语言中遇到的,则是编写一个自定义预处理器来理解有问题的语言和您的注释,会在删除注释的情况下重写代码,然后将其传递给实际的语言编译器.

The standard solution to a problem like this, if it's faced in a programming language that is not C++, is to write a custom preprocessor that understands some subset of the language in question and your annotation, rewrites the code with annotations removed, which is then passed to the actual language compiler.

这是扩展语言的标准方法:在编译器之前添加预处理步骤.

This is the standard method when it comes to extending languages: Adding an preprocessing step before the compiler.

不幸的是,仅仅解析功能完整的 C++ 几乎是不可能的;处理 C++ 源代码几乎总是以创建完整的 AST 生成器而告终,因为其中的一些分析语言特性很乏味.

Unfortunately it's next to impossible to just parse feature complete C++; processing C++ source code almost always ends up in creating a full AST generator, due to some of it's tedious to analyze language features.

看看这些声明:

template<bool b, class T> void foo(T &t){if(b) T.do_this(); else T.do_that();}
class foobar { public: virtual void do_this(); virtual void do_that(); };
class barfoo : public foobar { public: virtual void do_this(); virtual void do_that(); };

现在这个功能

void bar(float l){ barfoo t; foo<fsqrt(l) > 1, foobar>(t); }

这里的问题是,括号具有双重含义,对于模板和模板参数的比较.决定每个括号属于哪个的唯一方法需要一个完整的语法树.

The problem here is, that the brackets have double meaning, for the template and the comparision for a template parameter. The only way to decide to which each bracket belongs requires a complete syntax tree.

我知道只有一个像您描述的这样的工具:Qt 工具包的 MOC,按照您的建议执行:使用关键字 signalslot 注释的 C++ 代码.Qt 是开源的,因此查看 MOC 的源代码可能是个好主意.

I know of only one such tool like you describe: The MOC of the Qt toolkit, does what you suggest: C++ code annotated with keywords signal and slot. Qt is open source so it may be a good idea to look into MOC's sources.

编写和阅读 C++ 确实非常难.

Writing and reading C++ is very hard indeed.

这篇关于向 C++ 源代码添加注解语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆