Skip to content

Commit

Permalink
Merge pull request #129 from Glasses-Neo/feature/id_128
Browse files Browse the repository at this point in the history
Feature/id 128
  • Loading branch information
glassesneo committed Mar 4, 2024
2 parents e22241a + 7c7f103 commit c426dac
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]
### Added
- `isInstanceOf` to check whether a variable can be converted to a certain protocol

## [v0.7.1] -2023-10-21
### Fixed
Expand Down
12 changes: 12 additions & 0 deletions src/oolib.nim
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,15 @@ macro protocoled*(typeDef: untyped): untyped =
result = typeDef

ProtocolTable[protocolName.basename.strVal] = typeDef[2]

macro isInstanceOf*(v, T: untyped): untyped =
return block:
if ProtocolTable.hasKey(T.strVal):
quote do:
when compiles(`v`.toProtocol()):
`v`.toProtocol().type is `T`
else:
false
else:
quote do:
`v`.type is `T`
28 changes: 28 additions & 0 deletions tests/is_instanceof.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
discard """
action: "compile"
"""

import
std/unittest,
../src/oolib

protocol Readable:
var text: string

class Book impl Readable:
var title: string
var text: string = ""

class Human:
var name: string

let
book = Book.new(title = "Autobiography")
me = Human.new("Me")

check book.isInstanceOf(Readable)
check book.isInstanceOf(Book)
check me.isInstanceOf(Human)

check not me.isInstanceOf(Readable)
check not book.isInstanceOf(Human)

0 comments on commit c426dac

Please sign in to comment.