像Thrift框架那样编写一个描述文件就生成了代码是如何做到的?

我也想开发一种类似thrift那样的协议,可以满足移动开发,想通过一种协议描述文件生成各端sdk,但不知如何更方便地解析文件,不知有什么好方法没。

阅读 5k
2 个回答

你可以看看 Thrift IDL编译器的实现。

The Thrift compiler isimplemented in C++ using standard lex/yacc
lexing and parsing
.....
Code generation is done using two passes. The first pass looks
only for include files and type definitions. Type definitions are not
checked during this phase, since they may depend upon include
files. All included files are sequentially scanned in a first pass. Once
the include tree has been resolved, a second pass over all files is
taken that inserts type definitions into the parse tree and raises an
error on any undefined types. The program isthen generated against
the parse tree.

Thrift编译器使用lex/yacc在C ++中实现词法分析和解析
....
代码生成是通过两部完成的。第一部扫描引用文件和类型定义。因为类型定义可能依赖头文件,所以下一部才检查类型定义。所有引用文件都是在第一部中顺序扫描的。一旦引用文件树构建完成,则开始第二部,遍历所有文件将类型定义插入到树中,并在检查到为定义的错误时报错。最后程序根据树解析生成。

更多设计细节可参考
thrift技术白皮书

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进