Skip to content

Commit

Permalink
Support the documentation of global variables
Browse files Browse the repository at this point in the history
Following [this feature-request](OpenZeppelin#43), extending the `solidity-docgen` package to support the documentation of global variables, which are implicitly added by the compiler as getter functions in the contract.

This should allow users to get the natspec-documentation of their global variables added into the `solidity-docgen` output by extending the input template (hbs) file.

For example:
```
{{#if ownVariables}}
# Variables:
{{#ownVariables}}
- [`{{type}} {{name}}`](#{{anchor}})
{{/ownVariables}}
{{/if}}

{{#ownVariables}}
# Variable `{{type}} {{name}}` {#{{anchor~}} }
{{#if natspec.devdoc}}{{natspec.devdoc}}{{else}}No description{{/if}}
{{/ownVariables}}
```
Note that this PR is incomplete, since the `devdoc` of a global variable is always `undefined`.

For this reason, I also had to override function `SolidityContractItem.natspec()` in class `SolidityVariable` with a slightly different implementation (since `this.astNode.documentation === undefined`).
  • Loading branch information
barakman authored Sep 1, 2019
1 parent 4f9aa2d commit 4e53870
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/solidity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,20 @@ export class SolidityContract implements Linkable {
);
}

get variables(): SolidityVariable[] {
return uniqBy(
flatten(this.inheritance.map(c => c.ownVariables)),
v => v.signature,
);
}

get ownVariables(): SolidityVariable[] {
return this.astNode.nodes
.filter(isVariableDeclaration)
.filter(n => n.visibility === 'public')
.map(n => new SolidityVariable(this, n));
}

get functions(): SolidityFunction[] {
return uniqBy(
flatten(this.inheritance.map(c => c.ownFunctions)),
Expand Down Expand Up @@ -191,6 +205,30 @@ abstract class SolidityContractItem implements Linkable {
}
}

class SolidityVariable extends SolidityContractItem {
constructor(
contract: SolidityContract,
protected readonly astNode: solc.ast.VariableDeclaration,
) {
super(contract, astNode);
}

get type(): string {
return this.astNode.typeName.name;
}

get signature(): string {
return `${this.type} ${this.name}`;
}

get natspec(): NatSpec {
if (this.astNode.documentation) {
return parseNatSpec(this.astNode.documentation);
}
return {};
}
}

class SolidityFunction extends SolidityContractItem {
constructor(
contract: SolidityContract,
Expand Down Expand Up @@ -359,6 +397,10 @@ interface ToString {
toString(): string;
}

function isVariableDeclaration(node: solc.ast.ContractItem): node is solc.ast.VariableDeclaration {
return node.nodeType === 'VariableDeclaration';
}

function isFunctionDefinition(node: solc.ast.ContractItem): node is solc.ast.FunctionDefinition {
return node.nodeType === 'FunctionDefinition';
}
Expand Down

0 comments on commit 4e53870

Please sign in to comment.