Skip to content

Commit

Permalink
feat: KCL Go AST definition and parser API
Browse files Browse the repository at this point in the history
Signed-off-by: peefy <[email protected]>
  • Loading branch information
Peefy committed Nov 18, 2024
1 parent 26d6fe5 commit 35670ba
Show file tree
Hide file tree
Showing 9 changed files with 3,336 additions and 12 deletions.
9 changes: 9 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

kcl "kcl-lang.io/kcl-go"
"kcl-lang.io/kcl-go/pkg/native"
"kcl-lang.io/kcl-go/pkg/parser"
"kcl-lang.io/kcl-go/pkg/spec/gpyrpc"
)

Expand Down Expand Up @@ -213,6 +214,14 @@ age = option("age")
// name: kcl
}

func ExampleParseFile() {
result, err := parser.ParseFile("testdata/main.k", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}

func ExampleParseProgram() {
result, err := kcl.ParseProgram(&kcl.ParseProgramArgs{
Paths: []string{"testdata/main.k"},
Expand Down
42 changes: 30 additions & 12 deletions pkg/ast/ast.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,43 @@
package ast

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

// Pos denotes the struct tuple (filename, line, column, end_line, end_column).
type Pos struct {
Filename string `json:"filename"`
Line uint64 `json:"line"`
Column uint64 `json:"column"`
EndLine uint64 `json:"end_line"`
EndColumn uint64 `json:"end_column"`
// NewModule creates a new Module instance
func NewModule() *Module {
return &Module{
Body: make([]*Node[Stmt], 0),
Comments: make([]*Node[Comment], 0),
}
}

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

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

// Pos denotes the struct tuple (filename, line, column, end_line, end_column).
type Pos struct {
Filename string `json:"filename,omitempty"`
Line int64 `json:"line,omitempty"`
Column int64 `json:"column,omitempty"`
EndLine int64 `json:"end_line,omitempty"`
EndColumn int64 `json:"end_column,omitempty"`
}

// Comment node.
type Comment struct {
Text string
Expand Down
Loading

0 comments on commit 35670ba

Please sign in to comment.