Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add vm/qdoc with function comments #3459

Merged
merged 28 commits into from
Feb 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
12af64d
feat: In doc, add newPkgDataFromMemPkg
jefft0 Jan 8, 2025
337d3e2
chore: In doc, remove the Documentable interface, and instead export …
jefft0 Jan 21, 2025
7b15624
feat: Add NewDocumentableFromMemPkg and WriteJSONDocumentation
jefft0 Jan 24, 2025
cc96681
feat: Add support for vm/qdoc
jefft0 Jan 13, 2025
0be5f1c
chore: In querying-a-network.md, add a section for vm/qdoc
jefft0 Jan 27, 2025
2d151c1
Merge branch 'master' into feat/wm-qdoc-with-comments
jefft0 Jan 29, 2025
5104328
chore: In querying-a-network.md, add a section for vm/qdoc (fix grammar)
jefft0 Jan 30, 2025
52d79f4
Merge branch 'master' into feat/wm-qdoc-with-comments
jefft0 Jan 31, 2025
f154d82
chore: In vmHandler, fix comment for method queryDoc
jefft0 Feb 4, 2025
1c0c3c9
chore: In newPkgDataFromMemPkg, fullPath is only used for the error m…
jefft0 Feb 4, 2025
a99223d
chore: VMKeeper: In QueryDoc, expect the input to be pkgPath
jefft0 Feb 5, 2025
7833b92
feat: improve values (const, var) and functions extractions
D4ryl00 Feb 18, 2025
94434ff
chore: update tests
D4ryl00 Feb 18, 2025
0e1c040
Merge remote-tracking branch 'upstream/master' into feat/wm-qdoc-with…
D4ryl00 Feb 19, 2025
841c000
chore: fix lint
D4ryl00 Feb 19, 2025
510431b
chore: In JSONDocumentation json name, use the variable name
jefft0 Feb 19, 2025
bbd9af6
chore: In JSONValueDecl, use array of pointer to JSONValue
jefft0 Feb 19, 2025
41ce2f4
chore: In TestVmHandlerQuery_Doc, change the expected result to a JSO…
jefft0 Feb 19, 2025
fdb8add
fix: In WriteJSONDocumentation, include type constructors
jefft0 Feb 20, 2025
655682c
chore: TestVmHandlerQuery_Doc: also test named returns, var doc
jefft0 Feb 22, 2025
62db837
chore: In TestVmHandlerQuery_Doc, simplify the test. Put the full tes…
jefft0 Feb 24, 2025
3bbb6f5
chore: Add helper mustFormatNode, use it to simplify WriteJSONDocumen…
jefft0 Feb 25, 2025
df8663b
Merge branch 'master' into feat/wm-qdoc-with-comments
jefft0 Feb 25, 2025
2405bff
Merge branch 'master' into feat/wm-qdoc-with-comments
jefft0 Feb 26, 2025
88afcee
fix comment typo in gnovm/pkg/doc/json_doc.go
jefft0 Feb 27, 2025
18e925b
chore: docs: Update the vm/qdoc example
jefft0 Feb 28, 2025
cd29609
chore: Documentable: Merge extractFuncParams and extractFuncResults i…
jefft0 Feb 28, 2025
17c749d
Merge branch 'master' into feat/wm-qdoc-with-comments
thehowl Feb 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions docs/gno-tooling/cli/gnokey/querying-a-network.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Below is a list of queries a user can make with `gnokey`:
- `bank/balances/{ADDRESS}` - returns balances of an account
- `vm/qfuncs` - returns the exported functions for a given pkgpath
- `vm/qfile` - returns package contents for a given pkgpath
- `vm/qdoc` - Returns the JSON of the doc for a given pkgpath, suitable for printing
- `vm/qeval` - evaluates an expression in read-only mode on and returns the results
- `vm/qrender` - shorthand for evaluating `vm/qeval Render("")` for a given pkgpath

Expand Down Expand Up @@ -176,6 +177,77 @@ const (
...
```


## `vm/qdoc`

Using the `vm/qdoc` query, we can fetch the docs, for functions, types and variables from a specific
package path. To specify the path we want to query, we can use the `-data` flag:

```bash
gnokey query vm/qdoc --data "gno.land/r/gnoland/valopers/v2" -remote https://rpc.gno.land:443
```

The output is a JSON string containing doc strings of the package, functions, etc., including comments for `valopers` realm:

```json
height: 0
data: {
"package_path": "gno.land/r/gnoland/valopers/v2",
"package_line": "package valopers // import \"valopers\"",
"package_doc": "Package valopers is designed around the permissionless lifecycle of valoper profiles. It also includes parts designed for govdao to propose valset changes based on registered valopers.\n",
"values": [
{
"name": "valopers",
"doc": "// Address -> Valoper\n",
"type": "*avl.Tree"
}
// other values
],
"funcs": [
{
"type": "",
"name": "GetByAddr",
"signature": "func GetByAddr(address std.Address) Valoper",
"doc": "GetByAddr fetches the valoper using the address, if present\n",
"params": [
{
"Name": "address",
"Type": "std.Address"
}
],
"results": [
{
"Name": "",
"Type": "Valoper"
}
]
}
// other funcs
{
"type": "Valoper",
"name": "Render",
"signature": "func (v Valoper) Render() string",
"doc": "Render renders a single valoper with their information\n",
"params": [],
"results": [
{
"Name": "",
"Type": "string"
}
]
}
// other methods (in this case of the Valoper type)
],
"types": [
{
"name": "Valoper",
"signature": "type Valoper struct {\n\tName string // the display name of the valoper\n\tMoniker string // the moniker of the valoper\n\tDescription string // the description of the valoper\n\n\tAddress std.Address // The bech32 gno address of the validator\n\tPubKey string // the bech32 public key of the validator\n\tP2PAddresses []string // the publicly reachable P2P addresses of the validator\n\tActive bool // flag indicating if the valoper is active\n}",
"doc": "Valoper represents a validator operator profile\n"
}
]
}
```

## `vm/qeval`

`vm/qeval` allows us to evaluate a call to an exported function without using gas,
Expand Down
1 change: 1 addition & 0 deletions docs/reference/rpc-endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,7 @@ Call with the `/abci_query` to get information via the ABCI Query.
| `bank/balances/{ADDRESS}` | Returns the balance information about the account. |
| `vm/qfuncs` | Returns public facing function signatures as JSON. |
| `vm/qfile` | Returns the file bytes, or list of files if directory. |
| `vm/qdoc` | Returns JSON of the package doc, suitable for printing. |
| `vm/qrender` | Calls `.Render(<path>)` in readonly mode. |
| `vm/qeval` | Evaluates any expression in readonly mode and returns the results. |
| `vm/store` | (not yet supported) Fetches items from the store. |
Expand Down
15 changes: 15 additions & 0 deletions gno.land/pkg/sdk/vm/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const (
QueryFuncs = "qfuncs"
QueryEval = "qeval"
QueryFile = "qfile"
QueryDoc = "qdoc"
)

func (vh vmHandler) Query(ctx sdk.Context, req abci.RequestQuery) abci.ResponseQuery {
Expand All @@ -89,6 +90,8 @@ func (vh vmHandler) Query(ctx sdk.Context, req abci.RequestQuery) abci.ResponseQ
res = vh.queryEval(ctx, req)
case QueryFile:
res = vh.queryFile(ctx, req)
case QueryDoc:
res = vh.queryDoc(ctx, req)
default:
return sdk.ABCIResponseQueryFromError(
std.ErrUnknownRequest(fmt.Sprintf(
Expand Down Expand Up @@ -183,6 +186,18 @@ func (vh vmHandler) queryFile(ctx sdk.Context, req abci.RequestQuery) (res abci.
return
}

// queryDoc returns the JSON of the doc for a given pkgpath, suitable for printing
func (vh vmHandler) queryDoc(ctx sdk.Context, req abci.RequestQuery) (res abci.ResponseQuery) {
filepath := string(req.Data)
jsonDoc, err := vh.vm.QueryDoc(ctx, filepath)
if err != nil {
res = sdk.ABCIResponseQueryFromError(err)
return
}
res.Data = []byte(jsonDoc.JSON())
return
}

// ----------------------------------------
// misc

Expand Down
116 changes: 116 additions & 0 deletions gno.land/pkg/sdk/vm/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/gnolang/gno/gnovm"
"github.com/gnolang/gno/gnovm/pkg/doc"
abci "github.com/gnolang/gno/tm2/pkg/bft/abci/types"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/std"
Expand Down Expand Up @@ -327,3 +328,118 @@ func TestVmHandlerQuery_File(t *testing.T) {
})
}
}

func TestVmHandlerQuery_Doc(t *testing.T) {
expected := &doc.JSONDocumentation{
PackagePath: "gno.land/r/hello",
PackageLine: "package hello // import \"hello\"",
PackageDoc: "hello is a package for testing\n",
Values: []*doc.JSONValueDecl{
{
Signature: "const prefix = \"Hello\"",
Const: true,
Doc: "The prefix for the hello message\n",
Values: []*doc.JSONValue{
{
Name: "prefix",
Doc: "",
Type: "",
},
},
},
},
Funcs: []*doc.JSONFunc{
{
Type: "",
Name: "Hello",
Signature: "func Hello(msg string) (res string)",
Doc: "",
Params: []*doc.JSONField{
{Name: "msg", Type: "string"},
},
Results: []*doc.JSONField{
{Name: "res", Type: "string"},
},
},
{
Type: "myStruct",
Name: "Foo",
Signature: "func (ms myStruct) Foo() string",
Doc: "",
Params: []*doc.JSONField{},
Results: []*doc.JSONField{
{Name: "", Type: "string"},
},
},
},
Types: []*doc.JSONType{
{
Name: "myStruct",
Signature: "type myStruct struct{ a int }",
Doc: "myStruct is a struct for testing\n",
},
},
}

tt := []struct {
input []byte
expectedResult string
expectedErrorMatch string
}{
// valid queries
{input: []byte(`gno.land/r/hello`), expectedResult: expected.JSON()},
{input: []byte(`gno.land/r/doesnotexist`), expectedErrorMatch: `invalid package path`},
}

for _, tc := range tt {
name := string(tc.input)
t.Run(name, func(t *testing.T) {
env := setupTestEnv()
ctx := env.vmk.MakeGnoTransactionStore(env.ctx)
vmHandler := env.vmh

// Give "addr1" some gnots.
addr := crypto.AddressFromPreimage([]byte("addr1"))
acc := env.acck.NewAccountWithAddress(ctx, addr)
env.acck.SetAccount(ctx, acc)
env.bank.SetCoins(ctx, addr, std.MustParseCoins("10000000ugnot"))
assert.True(t, env.bank.GetCoins(ctx, addr).IsEqual(std.MustParseCoins("10000000ugnot")))

// Create test package.
files := []*gnovm.MemFile{
{Name: "hello.gno", Body: `
// hello is a package for testing
package hello

// myStruct is a struct for testing
type myStruct struct{a int}
func (ms myStruct) Foo() string { return "myStruct.Foo" }
// The prefix for the hello message
const prefix = "Hello"
func Hello(msg string) (res string) { res = prefix+" "+msg; return }
`},
}
pkgPath := "gno.land/r/hello"
msg1 := NewMsgAddPackage(addr, pkgPath, files)
err := env.vmk.AddPackage(ctx, msg1)
assert.NoError(t, err)

req := abci.RequestQuery{
Path: "vm/qdoc",
Data: tc.input,
}

res := vmHandler.Query(env.ctx, req)
if tc.expectedErrorMatch == "" {
assert.True(t, res.IsOK(), "should not have error")
if tc.expectedResult != "" {
assert.Equal(t, tc.expectedResult, string(res.Data))
}
} else {
assert.False(t, res.IsOK(), "should have an error")
errmsg := res.Error.Error()
assert.Regexp(t, tc.expectedErrorMatch, errmsg)
}
})
}
}
17 changes: 17 additions & 0 deletions gno.land/pkg/sdk/vm/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"time"

"github.com/gnolang/gno/gnovm"
"github.com/gnolang/gno/gnovm/pkg/doc"
gno "github.com/gnolang/gno/gnovm/pkg/gnolang"
"github.com/gnolang/gno/gnovm/stdlibs"
"github.com/gnolang/gno/tm2/pkg/crypto"
Expand Down Expand Up @@ -827,6 +828,22 @@
}
}

func (vm *VMKeeper) QueryDoc(ctx sdk.Context, pkgPath string) (*doc.JSONDocumentation, error) {
store := vm.newGnoTransactionStore(ctx) // throwaway (never committed)

memPkg := store.GetMemPackage(pkgPath)
if memPkg == nil {
err := ErrInvalidPkgPath(fmt.Sprintf(
"package not found: %s", pkgPath))
return nil, err
}
d, err := doc.NewDocumentableFromMemPkg(memPkg, true, "", "")
if err != nil {
return nil, err
}

Check warning on line 843 in gno.land/pkg/sdk/vm/keeper.go

View check run for this annotation

Codecov / codecov/patch

gno.land/pkg/sdk/vm/keeper.go#L842-L843

Added lines #L842 - L843 were not covered by tests
return d.WriteJSONDocumentation()
}

// logTelemetry logs the VM processing telemetry
func logTelemetry(
gasUsed int64,
Expand Down
23 changes: 8 additions & 15 deletions gnovm/pkg/doc/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,14 @@ type WriteDocumentationOptions struct {
}

// Documentable is a package, symbol, or accessible which can be documented.
type Documentable interface {
WriteDocumentation(w io.Writer, opts *WriteDocumentationOptions) error
}

// static implementation check
var _ Documentable = (*documentable)(nil)

type documentable struct {
type Documentable struct {
bfsDir
symbol string
accessible string
pkgData *pkgData
}

func (d *documentable) WriteDocumentation(w io.Writer, o *WriteDocumentationOptions) error {
func (d *Documentable) WriteDocumentation(w io.Writer, o *WriteDocumentationOptions) error {
if o == nil {
o = &WriteDocumentationOptions{}
}
Expand Down Expand Up @@ -110,7 +103,7 @@ func (d *documentable) WriteDocumentation(w io.Writer, o *WriteDocumentationOpti
return d.output(pp)
}

func (d *documentable) output(pp *pkgPrinter) (err error) {
func (d *Documentable) output(pp *pkgPrinter) (err error) {
defer func() {
// handle the case of errFatal.
// this will have been generated by pkg.Fatalf, so get the error
Expand Down Expand Up @@ -163,7 +156,7 @@ var fpAbs = filepath.Abs
// dirs specifies the gno system directories to scan which specify full import paths
// in their directories, such as @/examples and @/gnovm/stdlibs; modDirs specifies
// directories which contain a gno.mod file.
func ResolveDocumentable(dirs, modDirs, args []string, unexported bool) (Documentable, error) {
func ResolveDocumentable(dirs, modDirs, args []string, unexported bool) (*Documentable, error) {
d := newDirs(dirs, modDirs)

parsed, ok := parseArgs(args)
Expand All @@ -173,7 +166,7 @@ func ResolveDocumentable(dirs, modDirs, args []string, unexported bool) (Documen
return resolveDocumentable(d, parsed, unexported)
}

func resolveDocumentable(dirs *bfsDirs, parsed docArgs, unexported bool) (Documentable, error) {
func resolveDocumentable(dirs *bfsDirs, parsed docArgs, unexported bool) (*Documentable, error) {
var candidates []bfsDir

// if we have a candidate package name, search dirs for a dir that matches it.
Expand Down Expand Up @@ -208,13 +201,13 @@ func resolveDocumentable(dirs *bfsDirs, parsed docArgs, unexported bool) (Docume
}
// we wanted documentation about a package, and we found one!
if parsed.sym == "" {
return &documentable{bfsDir: candidates[0]}, nil
return &Documentable{bfsDir: candidates[0]}, nil
}

// we also have a symbol, and maybe accessible.
// search for the symbol through the candidates

doc := &documentable{
doc := &Documentable{
symbol: parsed.sym,
accessible: parsed.acc,
}
Expand Down Expand Up @@ -246,7 +239,7 @@ func resolveDocumentable(dirs *bfsDirs, parsed docArgs, unexported bool) (Docume
}
doc.bfsDir = candidate
doc.pkgData = pd
// match found. return this as documentable.
// match found. return this as Documentable.
return doc, multierr.Combine(errs...)
}
}
Expand Down
Loading
Loading