Skip to content

Commit

Permalink
TypeDecl.State
Browse files Browse the repository at this point in the history
  • Loading branch information
xushiwei committed May 5, 2022
1 parent 0f052b1 commit 164024d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
9 changes: 9 additions & 0 deletions package_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -608,8 +608,17 @@ func TestDeleteType(t *testing.T) {
pkg := newMainPackage()
typ := types.NewStruct(nil, nil)
decl := pkg.NewType("foo")
if decl.State() != gox.TyStateUninited {
t.Fatal("TypeDecl.State failed")
}
decl.InitType(pkg, typ)
if decl.State() != gox.TyStateInited {
t.Fatal("TypeDecl.State failed")
}
decl.Delete()
if decl.State() != gox.TyStateDeleted {
t.Fatal("TypeDecl.State failed")
}
domTest(t, pkg, `package main
Expand Down
25 changes: 24 additions & 1 deletion type_var_and_const.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ func (p *CodeBuilder) EndConst() *Element {

// ----------------------------------------------------------------------------

type TyState int

const (
TyStateUninited TyState = iota
TyStateInited
TyStateDeleted
)

// TypeDecl type
type TypeDecl struct {
typ *types.Named
Expand All @@ -56,13 +64,28 @@ func (p *TypeDecl) Type() *types.Named {
return p.typ
}

// State checkes state of this type.
// If Delete is called, it returns TyStateDeleted.
// If InitType is called (but not deleted), it returns TyStateInited.
// Otherwise it returns TyStateUninited.
func (p *TypeDecl) State() TyState {
if spec := p.decl.Specs; len(spec) > 0 {
if spec[0].(*ast.TypeSpec).Type != nil {
return TyStateInited
}
return TyStateUninited
}
return TyStateDeleted
}

// Delete deletes this type.
// NOTE: It panics if you call InitType after Delete.
func (p *TypeDecl) Delete() {
p.decl.Specs = p.decl.Specs[:0]
}

// Inited checkes if `InitType` is called or not.
// Inited checkes if InitType is called or not.
// Will panic if this type is deleted (please use State to check).
func (p *TypeDecl) Inited() bool {
return p.decl.Specs[0].(*ast.TypeSpec).Type != nil
}
Expand Down

0 comments on commit 164024d

Please sign in to comment.