Skip to content

Commit cc0c536

Browse files
committed
add the check subroutine
1 parent 5d1e091 commit cc0c536

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

src/Makefile.manual

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ clean:
3737

3838
# Fortran module dependencies
3939
f18estop.o: stdlib_experimental_error.o
40+
stdlib_experimental_error.o: stdlib_experimental_optval.o
4041
stdlib_experimental_io.o: \
4142
stdlib_experimental_error.o \
4243
stdlib_experimental_optval.o \

src/stdlib_experimental_error.f90

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module stdlib_experimental_error
2-
use, intrinsic :: iso_fortran_env, only: stderr=>error_unit
2+
use, intrinsic :: iso_fortran_env, only: stderr => error_unit
3+
use stdlib_experimental_optval, only: optval
34
implicit none
45
private
56

@@ -10,7 +11,7 @@ module subroutine error_stop(msg, code)
1011
end subroutine error_stop
1112
end interface
1213

13-
public :: assert, error_stop
14+
public :: assert, check, error_stop
1415

1516
contains
1617

@@ -31,4 +32,49 @@ subroutine assert(condition, code)
3132
if (.not. condition) call error_stop("Assert failed.", code)
3233
end subroutine
3334

34-
end module
35+
subroutine check(condition, msg, code, warn)
36+
37+
! Checks the value of a logical condition. If condition == .false. and:
38+
!
39+
! * No other arguments are provided, it stops the program with the default
40+
! message and exit code 1;
41+
! * msg is provided, it prints the value of msg;
42+
! * code is provided, it stops the program with the given exit code;
43+
! * warn is provided and .true., it doesn't stop the program and prints
44+
! * the message.
45+
!
46+
! Arguments
47+
! ---------
48+
49+
logical, intent(in) :: condition
50+
character(*), intent(in), optional :: msg
51+
integer, intent(in), optional :: code
52+
logical, intent(in), optional :: warn
53+
character(*), parameter :: msg_default = 'Test failed.'
54+
55+
! Examples
56+
! --------
57+
!
58+
! ! Stops the program with exit code 1 and prints 'Test failed.'
59+
! call check(a == 5)
60+
!
61+
! ! As above, but prints 'a == 5 failed.'
62+
! call check(a == 5, msg='a == 5 failed.')
63+
!
64+
! ! As above, but doesn't stop the program.
65+
! call check(a == 5, msg='a == 5 failed.', warn=.true.)
66+
!
67+
! ! As example #2, but stops the program with exit code 77
68+
! call check(a == 5, msg='a == 5 failed.', code=77)
69+
70+
if (.not. condition) then
71+
if (optval(warn, .false.)) then
72+
write(stderr,*) optval(msg, msg_default)
73+
else
74+
call error_stop(optval(msg, msg_default), optval(code, 1))
75+
end if
76+
end if
77+
78+
end subroutine check
79+
80+
end module stdlib_experimental_error

0 commit comments

Comments
 (0)