Hi,
Thank you for your detailed explanation. My knowledge of the C language
is limited and I missed a bit the distinction between the various types.
I was trying to port the 'strlen' function from newlib and looked
into the examples in the testsuite for inspiration as suggested
and came up with:
(* Adapted from GNU NewLib *)
(* gm2 -g -fcpp -Wall String.mod *)
MODULE String ;
FROM SYSTEM IMPORT ADR, BITSET32, WORD, TSIZE ;
FROM ASCII IMPORT nul;
TYPE
(* defined(__x86_64) || (defined(__alpha__) && defined(__arch64__)) || defined(__LP64__) *)
#if defined(HAS_BITSET64)
BITS = BITSET64 ;
WRD = LONGCARD ;
#else
BITS = BITSET32 ;
WRD = CARDINAL ;
#endif
CONST
BLOCK_SIZE = TSIZE(WRD) ;
(* defined(__x86_64) || (defined(__alpha__) && defined(__arch64__)) || defined(__LP64__) *)
#if defined(HAS_BITSET64)
NULLMASK1 = 0101010101010101H ;
NULLMASK2 = 8080808080808080H ;
#else
NULLMASK1 = 01010101H ;
NULLMASK2 = 80808080H ;
#endif
#define DETECTNULL(X) (BITSET(VAL(WRD,X^) - VAL(WRD,NULLMASK1)) * (-VAL(BITSET,X^)) * VAL(BITSET,NULLMASK2))
(* Find length of string *)
PROCEDURE Length (VAR a: ARRAY OF CHAR) : CARDINAL ;
VAR
Len, High: CARDINAL ;
PWord: POINTER TO WRD ;
BEGIN
Len := 0;
High := HIGH(a) ;
#if !(defined LIBRARY_OPTIMIZE_SIZE)
(* Check block by block *)
(* https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord *)
PWord := ADR(a[Len]);
LOOP
IF DETECTNULL(PWord) # 0 THEN
EXIT;
END;
INC(PWord, BLOCK_SIZE);
INC(Len, BLOCK_SIZE);
IF (Len > (High - BLOCK_SIZE)) THEN
EXIT;
END;
END;
(* Find position in last block *)
#endif
WHILE (Len <= High) AND (a[Len] # nul) DO
INC(Len);
END;
RETURN(Len);
END Length ;
VAR
str : ARRAY[0..256] OF CHAR;
i, len : CARDINAL;
BEGIN
str := '123';
len := Length(str);
END String.
This works fine and look readable still.
Except for when I use the flag -fsoft-check-all.
It then failed with a segmentation fault.
For now this is a fun exercise in porting Newlib
functions in order to learn/evaluate the language.
I think this could work perfectly for bare-metal embedded
development and potential much safer than C/C++.
It is for a reason the IEC 61131-3 PLC structured text
language is based on Modula-2 and not C/C++.
Best regards
Runar Tenfjord