Lazarus

Free Pascal => General => Topic started by: PeterHu on August 08, 2022, 01:48:05 pm

Title: Does Freepascal has everything "must have" functional features as C does
Post by: PeterHu on August 08, 2022, 01:48:05 pm
Greetings!

Speaking to FPC3.0,just want to know whether freepascal has everything "must have" as those features in C?And how about pointers in fpc,it has the same strong ability as C,let's say in a system programming environment.

I am not tending to leading a language war,rather,just expecting everything C can do freepascal can do as well and nothing "must have" features is missing in Freepascal.

Best Regards,
Peter
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 08, 2022, 02:19:33 pm

No parameterized macros and no ? operator. But those are not really must haves, and (Object) Pascal provides so much more.....
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 02:58:44 pm

No parameterized macros and no ? operator. But those are not really must haves...

Arguable.

Different semantics of the case/switch statement, but equivalence can be fudged. Different build system, i.e. no in-depth support for make.

Very strong support for string and dynamic array handling, at the cost of having compiler-generated finalisation blocks to do housekeeping.

Implementation- and platform-specific: limited (at present) attribute support, making it difficult to e.g. specify which section a variable or routine goes into.

Comparing it with other systems languages: no support for coroutine switching at the language level.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 08, 2022, 03:41:56 pm

No parameterized macros and no ? operator. But those are not really must haves...

Arguable.

Anything opinion based is arguable.

Quote
Different semantics of the case/switch statement, but equivalence can be fudged.

I never considered the broken C switch that defaults to fall-through a "feature".  Even if you consider fall-through itself a feature (I don't, at least not with a modern perspective), it should never have been default nor mixed with normal switch/case usage, too error prone.

Quote
Different build system, i.e. no in-depth support for make.

Having an actually functioning build-in build system rather than having none in the standard and relying on external tools calling platform dependent tools. Keep in mind that even if you step over make not being standard, even then the oft fabled parallelization of make often only gains back some of the time spent on header reparsing.

Quote
Comparing it with other systems languages: no support for coroutine switching at the language level.

Standard or language? What is the language level in M2 ?
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 03:57:27 pm
Standard or language? What is the language level in M2 ?

M2 had coroutines and TRANSFER() etc. from day one as I understand it.

It must also have had some way of getting at the I/O address space (although I forget the detail, and I don't think C- as standard- has that) but no form of attributes etc. which could be used to select between an arbitrary number of segments (term used loosely) or address spaces.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 08, 2022, 04:20:35 pm
Standard or language? What is the language level in M2 ?

M2 had coroutines and TRANSFER() etc. from day one as I understand it.

As part of the standard, but could be implemented as pure library solution?

Quote
It must also have had some way of getting at the I/O address space (although I forget the detail, and I don't think C- as standard- has that) but no form of attributes etc. which could be used to select between an arbitrary number of segments (term used loosely) or address spaces.

Aside from the fact that such implementation details don't belong in a standard, the code and datasegments of a cooperative tasks is roughly the same. So the only hardware bit is the stack. Changing the stack to a different segment might upset security software, so that must be done in an OS specific way.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: Thaddy on August 08, 2022, 04:25:57 pm

No parameterized macros
True. Although macro's are not strictly part of the language.
Quote
and no ? operator.
FPC has a generic ifthen<> (I wrote that) which is more or less the same, although it is not an operator, but a library function.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 08, 2022, 04:29:02 pm

No parameterized macros
True. Although macro's are not strictly part of the language.

In C to my best knowledge they are, which was the point.

Quote
Quote
and no ? operator.
FPC has a generic ifthen<> (I wrote that) which is more or less the same, although it is not an operator, but a library function.
I was not aware that that lazily evaluated?
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 04:41:12 pm
As part of the standard, but could be implemented as pure library solution?

As part of the language. I'm not sure whether than can be implemented as a standard library routine, since a stack (etc.) context switch is involved.

Similarly, access to addressspaces other than standard memory is a compiler issue since at some point specialist assembler has to be emitted. (I can't remember how e.g. SPARC handled this in C).

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 04:43:30 pm
In C to my best knowledge they are, which was the point.

I think you're right, although I also think that it's defined that the preprocessor is (or at least behaves as) a separate pass.

Quote
I was not aware that that lazily evaluated?

Agreed, was discussed a few weeks ago the PascalDragon's involvement.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: Thaddy on August 08, 2022, 04:49:50 pm
I was not aware that that lazily evaluated?
At least I designed it like that with Boolean evaluation settings in mind.
Suppose two TFunc parameters: then if TFunc1 evaluates to true TFunc2 is never executed because of Boolean shortcut evaluation.
So TFunc2 is Lazy. I believe Michael added an example for it that I added later.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: Thaddy on August 08, 2022, 04:51:30 pm
Agreed, was discussed a few weeks ago the PascalDragon's involvement.
Can you point me to that? AFAIK the code that I wrote does what I answered to Marco.
If not, the compiler does not do what I expected.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 05:19:27 pm
Can you point me to that? AFAIK the code that I wrote does what I answered to Marco.
If not, the compiler does not do what I expected.

I was thinking of https://forum.lazarus.freepascal.org/index.php/topic,59197.msg441906.html#msg441906 where it's unclear whether laziness is guaranteed.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: Thaddy on August 08, 2022, 06:42:31 pm
@mark  indeed that depends on shortcut evaluation. I can sort that with push/pop.
@Marco variatic macro's were only introduced in C99, it does not belong to Ansi C or certainly not K&R. It also requires (and still does) a separate lexer and parser and as such multiple passes. That is like FPC does it too, albeit that variatic ( which are untyped ) macro's are indeed not supported by FPC, to my regret. I asked for it many times. But I understand that the single pass concept prevailed for Pascal, since it was designed to be single pass. (Which FPC isn't anymore depending on settings)
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: bytebites on August 08, 2022, 07:14:46 pm
IfThen is regular function, nothing related to short-cut evaluation.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: winni on August 08, 2022, 07:21:34 pm
Greetings!

Speaking to FPC3.0,just want to know whether freepascal has everything "must have" as those features in C?And how about pointers in fpc,it has the same strong ability as C,let's say in a system programming environment.

I am not tending to leading a language war,rather,just expecting everything C can do freepascal can do as well and nothing "must have" features is missing in Freepascal.

Best Regards,
Peter

Hi!

To make it short:

fpc is a superset of C.

Take care: The current stable version is 3.2.2

To show you what is possible with fpc have a look at this site:

Operating Systems written in FPC

https://wiki.freepascal.org/Operating_Systems_written_in_FPC (https://wiki.freepascal.org/Operating_Systems_written_in_FPC)

Winni



Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 07:29:24 pm
fpc is a superset of C.

If that is even superficially true, please show me an FPC implementation of Duff's Device.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 08, 2022, 08:10:06 pm
fpc is a superset of C.

If that is even superficially true, please show me an FPC implementation of Duff's Device.

Sure. Just show me a real world application.

P.s. OP probably meant for "FPC is a superset of SANE C"
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: winni on August 08, 2022, 08:23:25 pm
Hi!

PeterHu asked for the main direction to decide between Pascal and C.

He did not asked for 2^1024 details for his decission.
I tried to get the discussion back to the nitty-gritty

Winni

PS.: On modern machines  the only advantage of Duff's Device is a bloated cache.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 08:27:36 pm
PeterHu asked for the main direction to decide between Pascal and C.

No he didn't: he asked if anything was missing which is a fair question.

I think we've got as far as the ternary ?, omission of parameterised macros, plus the difference in case/switch which- irrespective of the merits of either approach- favours C in versatility.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 08, 2022, 09:15:37 pm
PS.: On modern machines  the only advantage of Duff's Device is a bloated cache.

On modern machines, fast moving data,  is a compiler intrinsic translating in to a rep; movs or SIMD move.

And modern is everything after and including Pentium MMX.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: PascalDragon on August 08, 2022, 10:20:12 pm
As part of the standard, but could be implemented as pure library solution?

As part of the language. I'm not sure whether than can be implemented as a standard library routine, since a stack (etc.) context switch is involved.

Of course it can be implemented as a library routine, cause that's after all how the other languages do it behind the scenes as well (however they might call that “behind the scenes”). It's just a highly platform specific functionality, but that's in line with some other functionality of FPC (e.g. the Invoke functionality). And there do exist some x86 specific coroutine implementations for Delphi and FPC.

I was not aware that that lazily evaluated?
At least I designed it like that with Boolean evaluation settings in mind.
Suppose two TFunc parameters: then if TFunc1 evaluates to true TFunc2 is never executed because of Boolean shortcut evaluation.
So TFunc2 is Lazy. I believe Michael added an example for it that I added later.

The result type of the IfThen<> function is the same as its if-and else-parameters, thus the function itself will never call any of the parameters you pass in, so you'd have to manually call the returned function variable. Not to mention that the whole usage of anonymous functions would make the whole construct much more verbose than just using a good, old ifthenelse statement.
Other than that there is no lazy evaluation of the parameters of IfThen<> as from the compiler's point of view it's just an ordinary function.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 08, 2022, 10:59:45 pm
Of course it can be implemented as a library routine, cause that's after all how the other languages do it behind the scenes as well (however they might call that “behind the scenes”). It's just a highly platform specific functionality, but that's in line with some other functionality of FPC (e.g. the Invoke functionality). And there do exist some x86 specific coroutine implementations for Delphi and FPC.

It can definitely be /described/ as a library routine, in the same way that WriteLn() is.

Quote
The result type of the IfThen<> function is the same as its if-and else-parameters, thus the function itself will never call any of the parameters you pass in, so you'd have to manually call the returned function variable. Not to mention that the whole usage of anonymous functions would make the whole construct much more verbose than just using a good, old ifthenelse statement.
Other than that there is no lazy evaluation of the parameters of IfThen<> as from the compiler's point of view it's just an ordinary function.

(Boggle)

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: SymbolicFrank on August 10, 2022, 01:58:59 pm
C and C++ have a plethora of different functions to copy strings, while Pascal has just 1.
C and C++ have all kinds of unbounded arrays, even for parameter passing, that Pascal lacks.
Due to the rich macros, you can freely change the meaning of most things and completely change the syntax of C and C++. Pascal doesn't have that, either.

Actually, there are a lot of things you can do in C and C++ that you cannot in Pascal, if you strictly look at the effects. And both cannot do half the things you can accomplish with assembly code. Then again, if you look at the results instead, you see that most of the things that are left out aren't very useful to begin with.

So, is there a program you can write in C or C++, that you cannot in (Free) Pascal? Certainly. There are platforms that aren't supported. But then again, there are also platforms that run Free Pascal applications that have no C and/or C++ compiler. And there are platforms that have neither.

Otherwise, use what you like best, it doesn't matter.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: y.ivanov on August 10, 2022, 02:59:48 pm
fpc is a superset of C.

If that is even superficially true, please show me an FPC implementation of Duff's Device.

Sure. Just show me a real world application.

P.s. OP probably meant for "FPC is a superset of SANE C"
As long for an embedded, bare metal firmware, I'm using C with an approach similar to the protothreads (https://en.wikipedia.org/wiki/Protothread). It exploits the C switch/case behavior (like in the Duff's device) and parametrized macros to achieve stackless multi-threading.
The lack of similar preprocessor and the different case statement makes such a technique infeasible in FPC.

It is true that with the help of fibers a lightweight co-routines can be implemented, but they're in no way stackless. It's about microcontrollers with a tiny amount of resources, where the protothreads can be the only solution.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 10, 2022, 03:25:02 pm
As long for an embedded, bare metal firmware, I'm using C with an approach similar to the protothreads (https://en.wikipedia.org/wiki/Protothread). It exploits the C switch/case behavior (like in the Duff's device) and parametrized macros to achieve stackless multi-threading.
The lack of similar preprocessor and the different case statement makes such a technique infeasible in FPC.

It is true that with the help of fibers a lightweight co-routines can be implemented, but they're in no way stackless. It's about microcontrollers with a tiny amount of resources, where the protothreads can be the only solution.

I think you can do that sort of thing up to a point using SetJmp()/LongJmp(), but the number of issues that somebody highlighted earlier in the year relating to exceptions etc. makes that tenuous.

HOWEVER: somebody made the flat assertion that FPC was a superset of C. I provided an example of something that FPC couldn't do without- at the very least- pretty extreme contortion. End of that particular argument from my POV.

Sticking closely to consideration of the languages rather than the libraries etc., Classic Pascal and K&R C are both grandchildren of ALGOL-60: Pascal via ALGOL-W and C via BCPL. C is actually slightly closer to ALGOL-60 than is Pascal, since Pascal gained the (overwhelmingly important) concept of types.

Object Pascal and Modern C are children of Pascal and K&R C, where C has borrowed more ideas from Pascal than vice versa. As such they are cousins: neither is a descendant or superset of the other.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: SymbolicFrank on August 10, 2022, 03:39:14 pm
DIY: use a timer to push and pop a different set of registers from a list. Done.

If you don't want stacks, use a block of memory to store them.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 10, 2022, 03:45:45 pm
DIY: use a timer to push and pop a different set of registers from a list. Done.

If you don't want stacks, use a block of memory to store them.

You can't do that within the constraints of either the C or Pascal languages /as/ /defined/.

Sure, you can do it by tacking on assembler or by using non-standard pragmata: but that favours neither C no Pascal so is basically a null argument.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: y.ivanov on August 10, 2022, 04:02:56 pm
*snip*
I think you can do that sort of thing up to a point using SetJmp()/LongJmp(), but the number of issues that somebody highlighted earlier in the year relating to exceptions etc. makes that tenuous.
*snip
SetJmp preserves bunch of registers into jmp_buf (sort of context switching) and also some stack space is required. In protothreads (http://dunkels.com/adam/pt/) the context is reduced to a single state variable.

@SymbolicFrank
It can be given as an example a micro controller architecture/model where the general purpose registers block is comparable in size to the amount of RAM available, thus context switching impossible. AFAIK earlier PICs have a hardware stack with no SP, i.e. not swappable. The Duff's trick works even there.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: SymbolicFrank on August 10, 2022, 04:35:08 pm
Yes, like you can change the return address of your function by making a local string buffer and copying one in there that is longer. We call that a buffer overrun. This, too, can be used on micro-controllers to jump from one thread into another one.

Or, you could make a function pointer and insert the address you want, although you could do that in Pascal as well, so that's not an argument, either.

Like, on some micro-controllers, you can use the code as constants, to save on storage space. Or overlap code so you have two different functions, depending on the entry-point chosen. Re-use threads by saving and restoring only part of the registers. Compress and decompress things. Use bits in code words that aren't used for the opcode as flags. Etc. But if you want to do any of those things, you probably don't want the overhead of a runtime and use assembly.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 10, 2022, 05:04:41 pm
Discussion of assembler-level hacks is not relevant to OP's question. Neither language supports this sort of thing directly, implementations of both languages typically allow linkage to assembler routines.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: y.ivanov on August 10, 2022, 05:45:19 pm
Yes, like you can change the return address of your function by making a local string buffer and copying one in there that is longer. We call that a buffer overrun. This, too, can be used on micro-controllers to jump from one thread into another one.

Or, you could make a function pointer and insert the address you want, although you could do that in Pascal as well, so that's not an argument, either.

Like, on some micro-controllers, you can use the code as constants, to save on storage space. Or overlap code so you have two different functions, depending on the entry-point chosen. Re-use threads by saving and restoring only part of the registers. Compress and decompress things. Use bits in code words that aren't used for the opcode as flags. Etc. But if you want to do any of those things, you probably don't want the overhead of a runtime and use assembly.
My sole point was to give to marcov a case when the C switch/case behavior can be of real use.
The protothreads are Duff's device inspired, despite the device is actually a manual loop unrolling.
IMO discussing concurrent programming techniques is out of topic. 
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 10, 2022, 06:23:08 pm
IMO discussing concurrent programming techniques is out of topic.

Noting of course that FPC includes facilities for supporting threads, and even if TThread itself is part of the RTL rather than the language that is arguably something in its favour.

But coroutines and assembler-level hacks are definitely OT.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: marcov on August 10, 2022, 09:37:37 pm
My sole point was to give to marcov a case when the C switch/case behavior can be of real use.

Duff's device originally also was. You are missing the point of the argument, the fact that you can abuse it for hackish things (and hopefully not touch implementation defined behaviour along the way) doesn't excuse that it was not intended for such purposes.

As said, if fall-through was intended, rather than an attempt to save on syntax for the multiple clause case, then there would be two switch/case statements.

(

     
Code: [Select]
       case 1:
       case 2:
                   bla;
                   break;
   

vs

   
Code: [Select]
    case 1,2 :  bla;
   
)
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: PascalDragon on August 11, 2022, 08:51:05 am
As long for an embedded, bare metal firmware, I'm using C with an approach similar to the protothreads (https://en.wikipedia.org/wiki/Protothread). It exploits the C switch/case behavior (like in the Duff's device) and parametrized macros to achieve stackless multi-threading.
The lack of similar preprocessor and the different case statement makes such a technique infeasible in FPC.

It is true that with the help of fibers a lightweight co-routines can be implemented, but they're in no way stackless. It's about microcontrollers with a tiny amount of resources, where the protothreads can be the only solution.

I think you can do that sort of thing up to a point using SetJmp()/LongJmp(), but the number of issues that somebody highlighted earlier in the year relating to exceptions etc. makes that tenuous.

Considering the use case mentioned by y.ivanov this wouldn't be relevant anyway as you wouldn't use Object Pascal exception handling on such a target.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: y.ivanov on August 11, 2022, 10:10:29 am
*snip*
As said, if fall-through was intended, rather than an attempt to save on syntax for the multiple clause case, then there would be two switch/case statements.
*snip*
Without being an advocate of neither language, i should say that the C switch/case and Pascal case statements are significantly different in their meaning (although most of the time it doesn't look so) with the former being a form of parametrized goto and the latter being a true alternatives selection.
The C case labels can appear everywhere, incl. in the middle of a nested block:
Code: C  [Select][+][-]
  1. // taken from https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
  2. int function(void) {
  3.     static int i, state = 0;
  4.     switch (state) {
  5.         case 0: /* start of function */
  6.         for (i = 0; i < 10; i++) {
  7.             state = 1; /* so we will come back to "case 1" */
  8.             return i;
  9.             case 1:; /* resume control straight after the return */
  10.         }
  11.     }
  12. }
Which is absolutely unacceptable in Pascal (that feature is also exploited into the Duff's device, not only the fall-through).

Considering that (significant) difference, it is no wonder that something written with switch/case in C can't be achieved with the Pascal's case statement and vice versa.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: SymbolicFrank on August 16, 2022, 09:24:17 am
Here you go.

Code: Pascal  [Select][+][-]
  1. function Test: Boolean;
  2. var
  3.   i: Integer;
  4. label
  5.   Start, Loop, Stop;
  6. begin
  7. Start:
  8.   i := 0;
  9. Loop:
  10.   Inc(i);
  11.   if i >= 1000 then Goto Stop;
  12.   Goto Loop;
  13. Stop:
  14.   Result := i;
  15.   if Random(10) = 0 then Goto Start;
  16. end;
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 16, 2022, 09:49:37 am
Here you go.

Yes /but/: everybody agrees that C syntax is easily abused, and that Pascal can, by and large, achieve the same result using better program structure. However I introduced Duff's Device into this thread with the intention of refuting the unqualified "Pascal is a superset of C" assertion: there's lots of languages which /are/ supersets of C and which strive for backward compatibility but Pascal isn't one of them.

Leaving aside library differences, I think we collectively identified two features that C has where there is no direct Pascal equivalent: the ternary conditional and parameterised macros. Everything else is just noise.

At least nobody introduced Turing equivalence...

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: BobDog on August 16, 2022, 11:53:40 am
You can simulate a fall through, if you really must.
Code: Pascal  [Select][+][-]
  1.  
  2. {$macro on}
  3. {$define nobreak := end; case x of}
  4.    
  5. var
  6. x:integer=6;
  7.  
  8.  
  9. begin
  10. writeln('Number ',x);
  11.  
  12. case x of
  13.  
  14. 6:
  15.     writeln( 6);
  16.     nobreak
  17.    
  18.    
  19.  2 .. 7:
  20.     writeln( 2,' to ',7);
  21.     nobreak
  22.    
  23.  
  24. 9 .. 14:
  25.     writeln( 9,' to ',14);
  26.     nobreak
  27.    
  28.    
  29. 5 .. 7:
  30.     writeln( 5,' to ',7);
  31.     nobreak
  32.    
  33.    
  34. 12:
  35.     writeln( 12);
  36.  
  37. end;
  38. writeln('Press return to exit . . .');
  39. readln;
  40.  
  41. end.
  42.  
  43.  
  44.  
  45.  
  46.  
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: y.ivanov on August 16, 2022, 01:54:03 pm
@SymbolicFrank, @BobDog
Since perhaps no one bothered to look at the protothreads (http://dunkels.com/adam/pt/), I can show a simple example. Consider the slightly modified previous one (from reply #35) with some parametrized macros added:
Code: C  [Select][+][-]
  1. #include <stdio.h>
  2.  
  3. #define C_BEGIN(q)      switch( q ) { case 0:
  4. #define C_END(q)        } q = 0; return -1;
  5. #define C_YIELD(q, r) do { q = __LINE__; return (r); case __LINE__: ; } while( 0 )
  6.  
  7. int function()
  8. {
  9.     static int i, state = 0;
  10.  
  11.     C_BEGIN( state );  
  12.     while( 1 )
  13.         for( i = 0; i < 10; i++ )
  14.             C_YIELD( state, i);
  15.     C_END( state );
  16. }
  17.  
  18. int main()
  19. {
  20.     for( int i = 0; i < 15; i++ )
  21.         printf("%d ", function()); // prints: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
  22. }

You can test it here: https://godbolt.org/z/r8jjnhnc9

Using C_BEGIN/C_END, and when you put C_YIELD in between, the function will exit and on next invocation will continue right after the C_YIELD. All local variables will lose their values, of course, but that is the price for the stackless switching.
 
Further, consider the skeleton:
Code: C  [Select][+][-]
  1. #include <stdio.h>
  2.  
  3. #define C_BEGIN(q)      switch( q ) { case 0:
  4. #define C_END(q)        } q = 0; return -1;
  5. #define C_YIELD(q, r)   do { q = __LINE__; return (r); case __LINE__: ; } while( 0 )
  6.  
  7. int comm_fn()
  8. {
  9.     static int q = 0;
  10.  
  11.     C_BEGIN( q );
  12.     while(1)
  13.     {
  14.         while( tx_buffer_empty() )
  15.             C_YIELD(q, 0);
  16.  
  17.         send_buffer();
  18.  
  19.         while( rx_buffer_empty() && !rx_timeout() )
  20.             C_YIELD(q, 0);
  21.  
  22.         if( !rx_buffer_empty() )
  23.         {
  24.             // process the rx data
  25.         }
  26.     }
  27.     C_END( q );
  28. }
  29.  
  30. int ui_fn()
  31. {
  32.     static int q = 0;
  33.  
  34.     C_BEGIN( q );
  35.     while(1)
  36.     {
  37.         printf( "enter command ('q' for quit)\n" );
  38.  
  39.         while( !user_input() )
  40.             C_YIELD(q, 0);
  41.  
  42.         if( last_input() == 'q' )
  43.             exit(0);
  44.  
  45.         else
  46.             ; // process other choices
  47.    }
  48.     C_END( q );
  49. }
  50.  
  51. int main()
  52. {
  53.     for( ;; )
  54.     {
  55.         comm_fn();
  56.         ui_fn();
  57.         // other coroutines ...
  58.     }
  59. }

In which two unrelated functions are executed together simultaneously much like coroutines.

And it is not only about fall-through, it is also about goto-like switch/case behavior and parametrized macros.

This is something not achievable with the Pascal case statement. It's just different.

*snip*

At least nobody introduced Turing equivalence...

MarkMLl

 
I was tempted to do so...
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: SymbolicFrank on August 16, 2022, 04:06:12 pm
This is something not achievable with the Pascal case statement. It's just different.

Which is a good thing! Broken code shouldn't compile.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: BobDog on August 16, 2022, 04:39:24 pm

I just simulated fall through.
It would save many if/then's maybe.
macros with parameters would be nice.
So would proper variadic functions like c, and not just variadic from exported functions.
But pascal can use an array directly as a parameter, which is powerful.
dothis([2,6,7,2])
So strike that So would proper variadic functions like c
 Ternary operators (properly, passing over what could be an error or violation) are quite handy.
And the dreaded a+=1, which I know will upset many, should return probably.
All this is IMHO of course, I don't use pascal that much.
C has only 32 keywords, but it remains the most powerful high level language around, and like pascal is ancient.
Reminds me of:
"Old fiddles play the best tunes"







Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 16, 2022, 05:08:11 pm
macros with parameters would be nice.

I agree, although it would need a great deal of thought to do properly.

Quote
So would proper variadic functions like c, and not just variadic from exported functions.
But pascal can use an array directly as a parameter, which is powerful.
dothis([2,6,7,2])
So strike that So would proper variadic functions like c

TBH, I'd not object to seeing WriteLn() etc. insist on the variable number of parameters being bracketed, i.e. in the same way that Format() does.

Quote
Ternary operators (properly, passing over what could be an error or violation) are quite handy.

I'd like to see the concise if-the-else expression that was in ALGOL reintroduced. But apart from that I'm wary of other ternaries (or above).

Quote
And the dreaded a+=1, which I know will upset many, should return probably.

Sven has patiently explained to me why even in the context of C that's a complex issue. Frankly I'd not be that bothered with the subtleties provided that they were properly documented, and would be entirely happy to see this being a predefined macro with no specific compiler support.

At which point I'd like to add two things. The first is that parameterised macros don't necessarily have to look like functions: in principle they could also look like Smalltalk keyword expressions.

The second is that IMO both C and Pascal are excessively find of automatic type conversions. I'd be happier with this not being the case, with conversion only being permitted by a trait or by an explicit overload of the assignment operator... which isn't going to happen in FPC since AIUI the type of the lvalue isn't taken into account when an overloaded function is selected.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: PascalDragon on August 17, 2022, 09:22:35 am
And the dreaded a+=1, which I know will upset many, should return probably.

a += 1 is a statement. Statements do not have a result value. This is a basic concept of Pascal and absolutely not up for discussion.

Quote
Ternary operators (properly, passing over what could be an error or violation) are quite handy.

I'd like to see the concise if-the-else expression that was in ALGOL reintroduced. But apart from that I'm wary of other ternaries (or above).

Which is the only one I personally would support as well... (and I had implemented it already)

The second is that IMO both C and Pascal are excessively find of automatic type conversions. I'd be happier with this not being the case, with conversion only being permitted by a trait or by an explicit overload of the assignment operator... which isn't going to happen in FPC since AIUI the type of the lvalue isn't taken into account when an overloaded function is selected.

For the assignment operator (and maybe also other operator overloads returning a custom type) the compiler does take the left side into account, after all it wouldn't be able to pick the correct one otherwise:

Code: Pascal  [Select][+][-]
  1. program topovld;
  2.  
  3. {$mode objfpc}{$H+}
  4. {$modeswitch advancedrecords}
  5.  
  6. type
  7.   TTest = record
  8.     f: LongInt;
  9.     class operator := (const aArg: TTest): LongInt;
  10.     class operator := (const aArg: TTest): Boolean;
  11.   end;
  12.  
  13. class operator TTest.:= (const aArg: TTest): LongInt;
  14. begin
  15.   Result := aArg.f;
  16. end;
  17.  
  18. class operator TTest.:= (const aArg: TTest): Boolean;
  19. begin
  20.   Result := aArg.f <> 0;
  21. end;
  22.  
  23. var
  24.   t: TTest;
  25.   l: LongInt;
  26.   b: Boolean;
  27. begin
  28.   t.f := 42;
  29.   l := t;
  30.   b := t;
  31.  
  32.   Writeln(l, ' ', b); // prints "42 TRUE"
  33. end.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: MarkMLl on August 17, 2022, 09:52:05 am
For the assignment operator (and maybe also other operator overloads returning a custom type) the compiler does take the left side into account, after all it wouldn't be able to pick the correct one otherwise:

Thanks for that. Are you saying that, in effect, they have started taking more notice of the left side type comparatively recently?

I've always found that overloaded assignments needed to be approached with extreme caution, but perhaps it's time to have another play.

MarkMLl
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: y.ivanov on August 17, 2022, 12:04:04 pm
This is something not achievable with the Pascal case statement. It's just different.

Which is a good thing! Broken code shouldn't compile.
And why do you call it broken? Apart from the unpretty macro definitions, which can reside in a separate include file, the code looks very decent.

As a matter of fact, I'm using it on a daily basis in production code, it is simple, predictable, not clogged by synchronization primitives, etc. The big drawback is that the locals gets lost on each call and if you want to reuse a function, you must pass to it a frame pointer to the locals data (much like self).

But if you have a flat main loop with a few (co-)routines it just works.
Title: Re: Does Freepascal has everything "must have" functional features as C does
Post by: PascalDragon on August 17, 2022, 01:28:34 pm
For the assignment operator (and maybe also other operator overloads returning a custom type) the compiler does take the left side into account, after all it wouldn't be able to pick the correct one otherwise:

Thanks for that. Are you saying that, in effect, they have started taking more notice of the left side type comparatively recently?

That should be the case since forever (aka since assignment operator overloads exist), cause otherwise assignment operators overloads make no sense and are useless.
TinyPortal © 2005-2018