类型脚本
用 TypeScript 编写的 Thrift 解析器 。 由此产生的AST可用于从Thrift文件中编码JavaScript,或者仅仅用于检查Thrift结构.
使用量
一个成功的解析返回了 ThriftDocument 对象 。 不成功的剖析返回 ThriftErrors 对象 .
import { parse, ThriftDocument } from '@creditkarma/thrift-parser'
const rawThrift: string =`
struct MyStruct {
1: required i32 id
}
`;
const thriftAST: ThriftDocument | ThriftErrors = parse(rawThrift);
switch(thriftAST.type) {
case 'ThriftDocument':
// Do something with valid AST
case 'ThriftErrors':
// Report or recover from errors
}
您也可以使用命令行或 npm 脚本中的 Thrift Parser 。 当从命令行使用生成的 AST 时被保存为 JSON .
$ thrift-parser --rootDir thrift --outDir thrift-json --fastFail false some_file.thrift
在这种使用中,有三种选择:
- --rootDir: 在哪里启动文件搜索并保存
- --outDir: 相对于 rootDir 保存输出文件的位置
- -- fastFail: 如果遇到第一个错误时出现真实失败
构建
$ npm install
$ npm run build
测试
$ npm test
AST 结构
返回的 AST 的根是 Thrift Document( 成功剖析) 或 ThriftErrors( 未成功剖析) .
调色文件
{
type: "ThriftDocument",
body: Array<ThriftStatement>
}
扰动错误
{
type: "ThriftErrors",
errors: Array<ThriftError>
}
扭曲
在解析指定 Thrift 源时描述出出错的描述符 .
{
type: "ParseError" | "ScanError",
message: string,
loc: TextLocation
}
倾斜语句
Thrift Systems代表了在 Thrift source中可以定义的每个主构造.
名称空间定义
namespace <identifier> <identifier>
{
type: "NamespaceDefinition",
scope: Identifier,
name: Identifier
}
包含定义
include '<path>'"
{
type: "IncludeDefinition",
path: StringLiteral
}
类型定义
typedef <field-type> <identifier>
{
type: "TypedefDefinition",
name: Identifier,
definitionType: FieldType
}
定义
const <field-type> <identifier> = <initializer>
{
type: "ConstDefinition",
name: Identifier,
fieldType: FieldType,
initializer: ConstValue,
}
定义
enum <identifier> { <members> }
{
type: "EnumDefinition",
name: Identifier,
members: Array<EnumMember>
}
定义
struct <identifier> { <fields> }
{
type: "StructDefinition",
name: Identifier,
fields: Array<FieldDefinition>
}
联盟定义
union <identifier> { <fields> }
{
type: "UnionDefinition",
name: Identifier,
fields: Array<FieldDefinition>
}
例外定义
exception <identifier> { <fields> }
{
type: "ExceptionDefinition",
name: Identifier,
fields: Array<FieldDefinition>
}
服务定义
service <identifier> (extends <identifier>)? { <functions> }
{
type: "ServiceDefinition",
name: Identifier,
extends: Identifier | null,
functions: Array<FunctionDefinition>
}
使用 AST 爆炸器查看
ASTExplorer是可视化AST的网络应用. 您输入源。 它显示基于您所选择的解析器生成的语法树. 我已经包括了这个解析器的整合。 为了把那个弄好,你需要克隆ASTExplorer.
$ git clone https://github.com/fkling/astexplorer.git
$ cd astexplorer/website
$ npm install
您现在需要为 AST Explorer 安装节俭 Parser
$ npm install @creditkarma/thrift-parser
酷,现在我们需要复制一些东西 在ASTExplorer项目.
如果ASTExplorer项目和@creditkarma/thrift-parser项目是兄弟姐妹,您可以输入到temrinal(从astexplorer/website)中.
$ cp -r ../../thrift-parser/astexplorer/thrift ./src/parsers/thrift
您现在需要建立 AST 探索器并启动服务器
$ npm run build
$ npm start
默认情况下, 这将在本地主机: 8080 启动 AST Explorer
要选择要使用的语言, 请选择“ Thrift IDL ”
注意:我有些困难 npm run build 工作的时候。 然而,手表的建造要可靠得多.
$ npm run watch
然后在另一个终端窗口运行 start。 。 。 .
$ npm start
捐款
欲了解更多关于贡献新功能和错误修正的信息,请参见我们 贡献准则。 。 。 . 外部捐助者必须签署捐助者许可证协定
许可证
这个项目的许可证根据 Apache 许可证版本 2.0