Grammar Examples Document
This document provides code examples strictly based on the grammar specification, demonstrating how to correctly use this language to write business code.
1. Basic Contract Examples
1.1 Simple Identity Verification Contract
python
Contract IdentityContract:
Struct UserInfo:
name: string
pubkey: hex
age: int
def __init__(admin_key: hex):
self.admin = admin_key
def verify_user(user: UserInfo, signature: string) -> bool:
result: bool = CheckSig(user.pubkey, signature)
return resultExplanation:
- Defines a struct
UserInfocontaining basic user information - Constructor initializes the admin public key
- Verification function receives user information and signature, returns verification result
1.2 Digital Asset Transfer Contract
python
Contract TransferContract:
def __init__(owner_pubkey: hex):
self.owner = owner_pubkey
def transfer(from_key: hex, to_key: hex, amount: int, signature: string) -> bool:
from_key_clone: hex = from_key.Clone()
signature_clone: string = signature.Clone()
# self.owner is a contract member variable, can be used multiple times without Clone
is_owner: bool = (from_key_clone == self.owner)
is_valid_sig: bool = CheckSig(from_key, signature_clone)
is_positive_amount: bool = (amount > 0)
if is_owner:
if is_valid_sig:
if is_positive_amount:
return true
else:
return false
else:
return false
else:
return falseExplanation:
- Transfer contract verifies owner identity
- Uses
Clone()to avoid variable consumption, ensuring multiple uses - Demonstrates correct variable usage in the ownership system
2. Struct and Field Access Examples
2.1 Nested Struct Example
python
Contract UserManagement:
Struct Address:
street: string
city: string
zipcode: string
Struct User:
name: string
age: int
address: Address
balance: int
def __init__(admin_name: string):
self.admin_name = admin_name
def process_user(user: User) -> bool:
user_clone: User = user.Clone()
user_name: string = user.name
user_city: string = user_clone.address.city
# Need to clone again to access balance field
user_clone2: User = user_clone.Clone()
current_balance: int = user_clone2.balance
user_clone.balance = current_balance + 100
if user_clone.age >= 18:
return true
else:
return false
def update_user_address(user: User, new_street: string):
user.address.street = new_streetExplanation:
- Nested struct definition (Address nested in User)
- Multi-layer field access (
user.address.city) - Field assignment operation
- Conditional judgment and return value
3. Expression and Operation Examples
3.1 Mathematical Operations Contract
python
Contract MathOperations:
def calculate(a: int, b: int, c: int) -> int:
sum_result: int = a + b + c
product: int = a * b
difference: int = a - b
quotient: int = a / b
is_greater: bool = (a > b)
is_equal: bool = (a == b)
is_not_equal: bool = (a != c)
complex_result: int = (a + b) * c - (a / b)
return complex_result
def validate_Range(value: int, min_val: int, max_val: int) -> bool:
min_check: bool = (value >= min_val)
max_check: bool = (value <= max_val)
if min_check:
if max_check:
return true
else:
return false
else:
return falseExplanation:
- Various arithmetic operators (+, -, *, /)
- Comparison operators (>, ==, !=, >=, <=)
- Compound expressions and parentheses usage
- Since there are no logical operators (and, or) in the grammar specification, nested if is used to implement logical judgment
4. Function Call and Method Call Examples
4.1 Chained Field Access Example
python
Contract ChainedAccess:
Struct Config:
value: int
name: string
Struct System:
config: Config
active: bool
def __init__(initial_value: int):
self.default_value = initial_value
def process_system(sys: System) -> int:
sys_clone: System = sys.Clone()
config_value: int = sys.config.value
config_name: string = sys_clone.config.name
if sys_clone.active:
# self.default_value is a contract member variable, can be used multiple times without Clone
result: int = config_value + self.default_value
return result
else:
return 0
def update_system_config(sys: System, new_value: int, new_name: string):
sys_clone: System = sys.Clone()
sys.config.value = new_value
sys_clone.config.name = new_name
sys_clone.active = trueExplanation:
- Chained field access (
sys.config.value) - Struct passed as parameter
- Field assignment and reading
- Field access in conditional judgment
5. Complete Practical Application Examples
5.1 Simple Voting Contract
python
Contract VotingContract:
Struct Voter:
pubkey: hex
has_voted: bool
vote_choice: int
Struct Proposal:
id: int
title: string
yes_votes: int
no_votes: int
def __init__(admin_key: hex):
self.admin = admin_key
self.total_voters = 0
def register_voter(voter_key: hex) -> bool:
# self.total_voters is a contract member variable, can be used multiple times without Clone
self.total_voters = self.total_voters + 1
return true
def cast_vote(voter: Voter, proposal: Proposal, choice: int, signature: string) -> bool:
voter_clone: Voter = voter.Clone()
proposal_clone: Proposal = proposal.Clone()
is_valid_sig: bool = CheckSig(voter.pubkey, signature)
has_not_voted: bool = (voter_clone.has_voted == false)
valid_choice: bool = (choice == 0)
if is_valid_sig:
if has_not_voted:
if valid_choice:
proposal_clone2: Proposal = proposal_clone.Clone()
current_no_votes: int = proposal_clone2.no_votes
proposal_clone.no_votes = current_no_votes + 1
voter_clone.has_voted = true
return true
else:
choice_is_one: bool = (choice == 1)
if choice_is_one:
proposal_clone3: Proposal = proposal_clone.Clone()
current_yes_votes: int = proposal_clone3.yes_votes
proposal_clone.yes_votes = current_yes_votes + 1
voter_clone.has_voted = true
return true
else:
return false
else:
return false
else:
return false
def get_result(proposal: Proposal) -> int:
proposal_clone: Proposal = proposal.Clone()
yes_votes: int = proposal.yes_votes
no_votes: int = proposal_clone.no_votes
yes_wins: bool = (yes_votes > no_votes)
if yes_wins:
return 1
else:
return 0Explanation:
- Actual voting business logic
- Usage of multiple structs
- Complex conditional judgment logic
- Reading and modification of fields
- Function calls and return values
6. Ownership System and Special Built-in Function Examples
6.1 Ownership System Example
python
Contract OwnershipExample:
Struct UserInfo:
name: string
age: int
def demonstrate_ownership(value1: int, value2: int) -> int:
cloned_value1: int = value1.Clone()
result1: int = value1 + value2
result2: int = cloned_value1 * 2
return result1 + result2
def demonstrate_field_access(user: UserInfo) -> string:
user_clone: UserInfo = user.Clone()
name1: string = user.name
name2: string = user_clone.name
return name1
def incorrect_field_access(user: UserInfo) -> string:
name1: string = user.name
# name2: string = user.name # Error! user.name has been consumed
return name1Explanation:
- Use
Clone()to create variable copies, avoid ownership transfer - Field access consumes the ownership of that field, need to clone struct to access the same field multiple times
- Demonstrates correct and incorrect field access methods
6.2 Special Built-in Function Examples
python
Contract StackOperations:
def stack_management(data1: hex, data2: hex, data3: hex):
SetAlt(data1)
SetAlt(data2)
SetMain(data1)
SetMain(data2)
result: hex = data1 + data2 + data3
def complex_stack_operations(value: int) -> int:
cloned_value: int = value.Clone()
SetAlt(value)
SetMain(cloned_value)
final_result: int = value + cloned_value
return final_resultExplanation:
SetAlt()andSetMain()do not consume variable ownership- These functions can be called multiple times without affecting variable availability
- Demonstrates correct usage of stack operations
7. Grammar Features Summary
The above examples demonstrate the core features of the language:
7.1 Supported Grammar Features
- Strong Type System: All variables, parameters, and return values must declare types
- Struct Definition: Supports custom data structures and nested structs
- Field Access: Supports multi-layer field access (
obj.field1.field2), but consumes field ownership - Function Definition: Supports functions with parameters and return values
- Constructor: Uses
__init__to define constructor - Conditional Control: if-else branch control
- Expression Operations: Arithmetic operations, comparison operations
- Variable Declaration: Supports type-annotated variable declarations
- Assignment Operations: Supports assignment to variables and fields
- Ownership System: Variables have consumption property, support clone operations and special built-in functions
7.2 Grammar Limitations
- No Logical Operators: No
and,or,notoperators, need to use nested if to implement - No Loop Structures: No
for,whileloops - No Arrays/Lists: No array or list data structures
- No Comment Syntax: Comments not defined in grammar specification
- No Exception Handling: No try-catch exception handling mechanism
- Single Contract System: Each file can only contain one contract
- Field Access Consumption: Accessing struct fields consumes the ownership of that field, need to use clone operations carefully
7.3 Important Reminders for Ownership System
- Contract Member Variables Exception: Contract member variables (like
self.field) are not subject to ownership constraints, can be used multiple times without Clone - Local Variables and Parameters: Local variables and function parameters follow ownership rules, are consumed after use
- Struct Field Access: Accessing fields of a struct instance consumes the ownership of that field, cannot access again
- Need Clone for Multiple Access: If need to access the same local variable or struct field multiple times, must clone first
- Special Functions Don't Consume: Only
SetAlt()andSetMain()do not consume variable ownership - Clone is Deep Copy:
Clone()creates a complete copy, including nested structs
7.4 Contract Member Variables vs Local Variables Example
python
Contract OwnershipComparison:
def __init__(initial_value: int):
self.member_value = initial_value
def demonstrate_difference(local_value: int) -> int:
# Contract member variables can be used multiple times
result1: int = self.member_value + 10
result2: int = self.member_value * 2
result3: int = self.member_value - 5
# Local variables need clone to be used multiple times
local_clone1: int = local_value.Clone()
local_clone2: int = local_value.Clone()
local_result1: int = local_value + 10
local_result2: int = local_clone1 * 2
local_result3: int = local_clone2 - 5
return result1 + result2 + result3 + local_result1 + local_result2 + local_result3These examples strictly follow the grammar specification and ownership system, and can serve as references for writing actual business code.