Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/id 128 #129

Merged
merged 2 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading