Skip to content

Commit 35670ba

Browse files
committed
feat: KCL Go AST definition and parser API
Signed-off-by: peefy <[email protected]>
1 parent 26d6fe5 commit 35670ba

File tree

9 files changed

+3336
-12
lines changed

9 files changed

+3336
-12
lines changed

example_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111

1212
kcl "kcl-lang.io/kcl-go"
1313
"kcl-lang.io/kcl-go/pkg/native"
14+
"kcl-lang.io/kcl-go/pkg/parser"
1415
"kcl-lang.io/kcl-go/pkg/spec/gpyrpc"
1516
)
1617

@@ -213,6 +214,14 @@ age = option("age")
213214
// name: kcl
214215
}
215216

217+
func ExampleParseFile() {
218+
result, err := parser.ParseFile("testdata/main.k", nil)
219+
if err != nil {
220+
log.Fatal(err)
221+
}
222+
fmt.Println(result)
223+
}
224+
216225
func ExampleParseProgram() {
217226
result, err := kcl.ParseProgram(&kcl.ParseProgramArgs{
218227
Paths: []string{"testdata/main.k"},

pkg/ast/ast.go

+30-12
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,43 @@
11
package ast
22

3-
// TODO: add more nodes from https://github.com/kcl-lang/kcl/blob/main/kclvm/ast/src/ast.rs
3+
// Module is an abstract syntax tree for a single KCL file.
4+
type Module struct {
5+
Filename string `json:"filename"`
6+
Pkg string `json:"pkg"`
7+
Doc *Node[string] `json:"doc"`
8+
Body []*Node[Stmt] `json:"body"`
9+
Comments []*Node[Comment] `json:"comments"`
10+
}
411

5-
// Pos denotes the struct tuple (filename, line, column, end_line, end_column).
6-
type Pos struct {
7-
Filename string `json:"filename"`
8-
Line uint64 `json:"line"`
9-
Column uint64 `json:"column"`
10-
EndLine uint64 `json:"end_line"`
11-
EndColumn uint64 `json:"end_column"`
12+
// NewModule creates a new Module instance
13+
func NewModule() *Module {
14+
return &Module{
15+
Body: make([]*Node[Stmt], 0),
16+
Comments: make([]*Node[Comment], 0),
17+
}
1218
}
1319

14-
// Node is the file, line, and column number information that all AST nodes need to contain.
15-
type Node interface {
16-
Pos() Pos
17-
Index() string
20+
// Node is the file, line and column number information that all AST nodes need to contain.
21+
// In fact, column and end_column are the counts of character. For example, `\t` is counted as 1 character,
22+
// so it is recorded as 1 here, but generally col is 4.
23+
type Node[T any] struct {
24+
ID AstIndex `json:"id,omitempty"`
25+
Node T `json:"node,omitempty"`
26+
Pos
1827
}
1928

2029
// AstIndex represents a unique identifier for AST nodes.
2130
type AstIndex string
2231

32+
// Pos denotes the struct tuple (filename, line, column, end_line, end_column).
33+
type Pos struct {
34+
Filename string `json:"filename,omitempty"`
35+
Line int64 `json:"line,omitempty"`
36+
Column int64 `json:"column,omitempty"`
37+
EndLine int64 `json:"end_line,omitempty"`
38+
EndColumn int64 `json:"end_column,omitempty"`
39+
}
40+
2341
// Comment node.
2442
type Comment struct {
2543
Text string

0 commit comments

Comments
 (0)