Skip to content

Commit

Permalink
grammar,astgen: support unsafe block
Browse files Browse the repository at this point in the history
StunxFS committed Jun 11, 2024

Verified

This commit was signed with the committer’s verified signature.
1 parent 67922ff commit 2385ba6
Showing 4 changed files with 16 additions and 5 deletions.
7 changes: 5 additions & 2 deletions bsc/AST.py
Original file line number Diff line number Diff line change
@@ -160,13 +160,16 @@ def __str__(self):
return res

class BlockStmt:
def __init__(self, stmts, pos):
def __init__(self, is_unsafe, stmts, pos):
self.is_unsafe = is_unsafe
self.stmts = stmts
self.pos = pos

def __str__(self):
stmts = '\n'.join([str(stmt) for stmt in self.stmts])
return f"{{ {stmts} }}"
res = "unsafe " if self.is_unsafe else ""
res += f"{{ {stmts} }}"
return res

# Expressions

8 changes: 6 additions & 2 deletions bsc/astgen.py
Original file line number Diff line number Diff line change
@@ -186,8 +186,12 @@ def block(self, *nodes):
return list(nodes[1:-1])

def block_stmt(self, *nodes):
stmts = list(nodes[1:-1])
return BlockStmt(stmts, self.mkpos(nodes[0]) + self.mkpos(nodes[-1]))
is_unsafe = nodes[0] != None
stmts = list(nodes[2:-1])
return BlockStmt(
is_unsafe, stmts,
self.mkpos(nodes[0]) + self.mkpos(nodes[-1])
)

def while_stmt(self, *nodes):
return WhileStmt(nodes[1], nodes[2], self.mkpos(nodes[0]))
3 changes: 2 additions & 1 deletion bsc/grammar.lark
Original file line number Diff line number Diff line change
@@ -75,7 +75,7 @@ primitive_type: "any"
| KW_WHILE expr block -> while_stmt

block: LBRACE stmt* RBRACE // returns array of stmts in AstGen
block_stmt: LBRACE stmt* RBRACE // returns BlockStmt in AstGen
block_stmt: [KW_UNSAFE] LBRACE stmt* RBRACE // returns BlockStmt in AstGen

assignment: expr (COMMA expr)* op_assign expr
op_assign: OP_ASSIGN
@@ -214,6 +214,7 @@ KW_PUB.1: "pub"
KW_SELF.1: "self"
KW_TRUE.1: "true"
KW_USE.1: "use"
KW_UNSAFE.1: "unsafe"
KW_VAR.1: "var"
KW_WHILE.1: "while"

3 changes: 3 additions & 0 deletions tests/syntax.bs
Original file line number Diff line number Diff line change
@@ -37,6 +37,9 @@ enum WorldLevel {
undefined = 0xFF

fn from_string(s: string) Self {
unsafe {
"unsafe!"
}
return match s {
"overworld" => .overworld,
"midgard" => .midgard,

0 comments on commit 2385ba6

Please sign in to comment.