Skip to content

Commit

Permalink
feat: enumof operator
Browse files Browse the repository at this point in the history
  • Loading branch information
pmqueiroz committed Dec 3, 2024
1 parent 8b68b28 commit f02f29c
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ast/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ func (p *Parser) unary() Expression {
func (p *Parser) multiplication() Expression {
expr := p.unary()

for p.match(tokens.SLASH, tokens.STAR, tokens.PERCENT) {
for p.match(tokens.SLASH, tokens.STAR, tokens.PERCENT, tokens.ENUMOF) {
expr = BinaryExpression{
Left: expr,
Operator: p.previous(),
Expand Down
3 changes: 3 additions & 0 deletions examples/enums.u
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ for mut i num = 0, ~events - 1 {
}
}

io::println(Event.Keyboard("a") enumof Event.Keyboard) # true
io::println(Event.Keyboard("a") == Event.Keyboard("a")) # true
io::println(Event.Keyboard("a") == Event.Keyboard("b")) # false

## Todo
# - [x] Declare enums
Expand Down
2 changes: 2 additions & 0 deletions exception/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ var Messages = map[string]string{
"RT034": "enum member '%s' does not exits in '%s'",
"RT035": "cannot use '%s' as a type",
"RT036": "enum member expects to be called with arguments",
"RT037": "left operand in enumof should be an enum member",
"RT038": "right operand in enumof should be an enum member",
"GN001": "cannot find module '%s'",
"GN002": "unable to load file '%s'. module does not exits. path: %s",
}
11 changes: 11 additions & 0 deletions interpreter/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,17 @@ func Evaluate(expression ast.Expression, env *environment.Environment) (interfac
}
case tokens.BANG_EQUAL:
return left != right, nil
case tokens.ENUMOF:
leftVal, ok := left.(ast.EnumMember)
if !ok {
return nil, exception.NewRuntimeError("RT037")
}
rightVal, ok := right.(ast.EnumMember)
if !ok {
return nil, exception.NewRuntimeError("RT038")
}

return leftVal.Signature == rightVal.Signature && leftVal.Name == rightVal.Name, nil
default:
return nil, exception.NewRuntimeError("RT010", expr.Operator.Lexeme)
}
Expand Down
2 changes: 2 additions & 0 deletions tokens/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ const (
ENUM TokenType = "ENUM"
MATCH TokenType = "MATCH"
PIPE TokenType = "PIPE"
ENUMOF TokenType = "ENUMOF"
)

var PRIMITIVE_TYPES = []TokenType{
Expand Down Expand Up @@ -128,6 +129,7 @@ var reservedKeywordsMap = map[string]TokenType{
"typeof": TYPE_OF,
"enum": ENUM,
"match": MATCH,
"enumof": ENUMOF,
}

func getKeyword(lexis string) TokenType {
Expand Down

0 comments on commit f02f29c

Please sign in to comment.