From e6583045f0a2a8fa50b77c7d442bb336615bab96 Mon Sep 17 00:00:00 2001 From: Glasses-Neo Date: Tue, 5 Mar 2024 02:27:07 +0900 Subject: [PATCH 1/2] :sparkles: Add `isInstanceOf` macro --- src/oolib.nim | 12 ++++++++++++ tests/is_instanceof.nim | 28 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 tests/is_instanceof.nim diff --git a/src/oolib.nim b/src/oolib.nim index 823519e..dfe563f 100644 --- a/src/oolib.nim +++ b/src/oolib.nim @@ -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` diff --git a/tests/is_instanceof.nim b/tests/is_instanceof.nim new file mode 100644 index 0000000..b526d8c --- /dev/null +++ b/tests/is_instanceof.nim @@ -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) From 7c7f1033147bdd44349c8f5ddcad067314302df7 Mon Sep 17 00:00:00 2001 From: Glasses-Neo Date: Tue, 5 Mar 2024 02:29:34 +0900 Subject: [PATCH 2/2] :books: Edit CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3801169..71ce317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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