Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2022-01

Case statement for class introspection

31 messages · 4 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Ryan Joseph

I saw a new syntax in Swift which I thought was clever and fits a pattern I've seen before. Basically it's a case statement for class types which lets you branch depending on which class type the class instance is at run time.

I wonder if this could be implemented in FPC? The syntax would be kind of clumsy though since you can't declare scoped variables in Pascal so you would need to do lots of casts but it's still cleaner than the equivalent code as if statements.

=====================

  case monster of
    TZenChan:
      TZenChan(monster).DoThis;
    TPulPul:
      TPulPul(monster).DoThat;
    otherwise
      monster.DoSomething;
  end;

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Ryan Joseph
Ryan Joseph wrote
I saw a new syntax in Swift which I thought was clever and fits a pattern I've seen before. Basically it's a case statement for class types which lets you branch depending on which class type the class instance is at run time.

I think Scala did it before Swift.

I wonder if this could be implemented in FPC? The syntax would be kind of clumsy though since you can't declare scoped variables in Pascal so you would need to do lots of casts but it's still cleaner than the equivalent code as if statements.

This idea has been proposed before by Izak Maciej. I'm all for it.

Michael.

Reply by email

Ryan Joseph
to Michael Van Canneyt
Show quoted text 8 lines
On Jan 15, 2022, at 8:30 AM, Michael Van Canneyt via fpc-pascal wrote: > I saw a new syntax in Swift which I thought was clever and fits a pattern > I've seen before. Basically it's a case statement for class types which > lets you branch depending on which class type the class instance is at run > time. I think Scala did it before Swift.

What did it look like? Seems like an obvious feature any OOP language should have.

Swift has a compound switch statement which does lots of things. It's a little messy but it accomplishes this well. For example here they have a "case is" and "case let _ as" which tests for class type or casts to a local variable using "as".

switch object {
case is Message:
break
case let content as MessageContent:
break
case let attachment as Attachment:
break
default: break
}

Problem for Pascal is how to handle the casting mess. C languages (and Delphi now I guess) can do inline variable declarations to avoid the casting.

Come to think of it this a similar problem with for-loops where you want to loop over a collection of only certain types. For example:

for monster in monsters do
    if monster is TZenChan then
      TZenChan(monster).Dothis;

Swift does something similar as the switch which would look kind of like this:

for case monster as TZenChan in monsters do
      TZenChan(monster).Dothis;

That syntax is not so nice but I like they're trying to help us manage class introspection using existing language constructs.

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Ryan Joseph
Ryan Joseph wrote 12 lines
> On Jan 15, 2022, at 8:30 AM, Michael Van Canneyt via fpc-pascal wrote: > >> I saw a new syntax in Swift which I thought was clever and fits a pattern >> I've seen before. Basically it's a case statement for class types which >> lets you branch depending on which class type the class instance is at run >> time. > > I think Scala did it before Swift. What did it look like? Seems like an obvious feature any OOP language should have.
myInstance match {
   case TComponent => dosomething;
   case TPersistent => dosomethingelse;
}
Show quoted text 14 lines
Swift has a compound switch statement which does lots of things. It's a little messy but it accomplishes this well. For example here they have a "case is" and "case let _ as" which tests for class type or casts to a local variable using "as". switch object { case is Message: break case let content as MessageContent: break case let attachment as Attachment: break default: break } Problem for Pascal is how to handle the casting mess. C languages (and Delphi now I guess) can do inline variable declarations to avoid the casting.

I don't see how an inline variable helps with the casting mess. You'll always need a cast.

What I do is
Var
   MyInstance : TObject;
   MyNeededClass : TMyNeededClass absolute myInstance:
Show quoted text 6 lines
Come to think of it this a similar problem with for-loops where you want to loop over a collection of only certain types. For example: for monster in monsters do if monster is TZenChan then TZenChan(monster).Dothis;

See above for the solution.

Michael.

Reply by email

Ryan Joseph
to Michael Van Canneyt
Show quoted text 8 lines
On Jan 15, 2022, at 3:24 PM, Michael Van Canneyt via fpc-pascal wrote: I don't see how an inline variable helps with the casting mess. You'll always need a cast. What I do is Var MyInstance : TObject; MyNeededClass : TMyNeededClass absolute myInstance:

Yes that's the best option.

Anyways, the case statement in FPC allows for strings which basically fold down into an if-else statement for comparing strings and this same logic could be expanded for class types. Seems like a smart extension to add but does the compiler team support this?

Something like this:

  case o.ClassType of
    TObject: writeln('TObject');
    TInterfacedObject: writeln('TInterfacedObject');
  end;

Converts to:

  if o.ClassType = TObject then
    writeln('TObject')
  else if o.ClassType = TInterfacedObject then
    writeln('TInterfacedObject');

There is a possibility for using "as" operator also though....

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph
On Jan 16, 2022, at 9:21 AM, Ryan Joseph wrote: There is a possibility for using "as" operator also though....

oops I mean "is" operator. Not sure if these are technically different from ClassType = ClassType though...

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Ryan Joseph
Ryan Joseph wrote 7 lines
> On Jan 16, 2022, at 9:21 AM, Ryan Joseph wrote: > > There is a possibility for using "as" operator also though.... oops I mean "is" operator. Not sure if these are technically different from ClassType = ClassType though...

They are.

No "is", because then the order of the label will start to matter, and that runs contrary to the case statement's intent.

if you use 'is' then
case A of
   TPersistent: Writeln('TPersistent');
   TComponent : Writeln('TComponent');
end;

would always stop at TPersistent for every TComponent descendent, and that is not what you want.

So to preserve the semantics of 'case' (order of labels does not matter), it must be an exact match.

Michael.

Reply by email

Ryan Joseph
to Michael Van Canneyt
Show quoted text 7 lines
On Jan 16, 2022, at 2:35 PM, Michael Van Canneyt via fpc-pascal wrote: They are. No "is", because then the order of the label will start to matter, and that runs contrary to the case statement's intent.

oh of course they are, I don't know why I forgot that. :P

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph

I had some fun today on my day off and managed to actually implement this based on the if-statement based string case labels. Is the compiler team interested in this feature? I think it's a clearly useful addition to OOP and an appropriate new use of the case statement.

https://gitlab.com/genericptr/free-pascal/-/commits/case_label_classref

Here's an example of what I did. To keep it simple you use "ClassType" to branch off of possible class types.

========================

  o := TInterfacedObject.Create;
  case o.ClassType of
    TObject: writeln('TObject');
    TInterfacedObject: writeln('TInterfacedObject');
    TAggregatedObject: writeln('TAggregatedObject');
    otherwise
      writeln('OTHER: ',o.ClassName);
  end;

Regards,
Ryan Joseph

Reply by email

Marco van de Voort
to Ryan Joseph
Ryan Joseph wrote 17 lines
I had some fun today on my day off and managed to actually implement this based on the if-statement based string case labels. Is the compiler team interested in this feature? I think it's a clearly useful addition to OOP and an appropriate new use of the case statement. https://gitlab.com/genericptr/free-pascal/-/commits/case_label_classref Here's an example of what I did. To keep it simple you use "ClassType" to branch off of possible class types. ======================== o := TInterfacedObject.Create; case o.ClassType of TObject: writeln('TObject'); TInterfacedObject: writeln('TInterfacedObject'); TAggregatedObject: writeln('TAggregatedObject'); otherwise writeln('OTHER: ',o.ClassName); end;

What does it print in this case? I mean tobject matches, and tinterfacedobject too.

The most logic solution would be to only run the most specialized case?

Reply by email

Ryan Joseph
to Marco van de Voort
Show quoted text 5 lines
On Jan 16, 2022, at 8:38 PM, Marco van de Voort via fpc-pascal wrote: What does it print in this case? I mean tobject matches, and tinterfacedobject too. The most logic solution would be to only run the most specialized case?

It would print the name of the class if it didn't exist in the list. It's an incomplete code snippet but if the class was another type it would be captured there of course.

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph: I had some fun today on my day off and managed to actually implement this based on the…
On Jan 16, 2022, at 8:18 PM, Ryan Joseph wrote: https://gitlab.com/genericptr/free-pascal/-/commits/case_label_classref

I just realized too late that the way I implemented this may be not the best idea. If the class type had an ordinal representation then you could use a normal case statement instead of making a big if-else block and doing equality comparisons for each type. That would be faster right?

Assuming the memory address of the type worked you could do something like this behind the scenes:

  case PtrUInt(o.ClassType) of
    4500656856: writeln('TObject');
  end;

If so, I would have to rethink this then and come back to it later.

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph
Show quoted text 5 lines
On Jan 16, 2022, at 9:01 PM, Ryan Joseph wrote: case PtrUInt(o.ClassType) of 4500656856: writeln('TObject'); end;

I may have spoken too soon and without thinking the through clearly (it's getting late here!). For this to work we would need a unique ID in the RTTI, right? I don't think that exists so unless it does we need to do equality comparisons for each case.

Regards,
Ryan Joseph

Reply by email

Sven Barth
to Ryan Joseph
Ryan Joseph wrote 7 lines
> On Jan 16, 2022, at 9:01 PM, Ryan Joseph wrote: > > case PtrUInt(o.ClassType) of > 4500656856: writeln('TObject'); > end; I may have spoken too soon and without thinking the through clearly (it's getting late here!). For this to work we would need a unique ID in the RTTI, right? I don't think that exists so unless it does we need to do equality comparisons for each case.

The class type already is a unique "ID" for each class type when doing an equal comparison. You can essentially take the address of the VMT as the constant values that the loaded value is compared against.

Regards,
Sven

Reply by email

Ryan Joseph
to Sven Barth
On Jan 16, 2022, at 11:15 PM, Sven Barth wrote: The class type already is a unique "ID" for each class type when doing an equal comparison. You can essentially take the address of the VMT as the constant values that the loaded value is compared against.

Does that look something like this then? and if so, this is better then doing the if-statement block, like string case statements?

  case PtrUInt(o.ClassType.ClassInfo) of
    PtrUInt(TObject.ClassInfo): writeln('TObject');
  end;

Question then is how you get the VMT address as a constant at compile time.

Regards,
Ryan Joseph

Reply by email

Sven Barth
to Ryan Joseph

Ryan Joseph via fpc-pascal schrieb am
Mo., 17. Jan. 2022, 02:38:

Show quoted text 12 lines
> On Jan 16, 2022, at 11:15 PM, Sven Barth wrote: > > The class type already is a unique "ID" for each class type when doing an equal comparison. You can essentially take the address of the VMT as the constant values that the loaded value is compared against. Does that look something like this then? and if so, this is better then doing the if-statement block, like string case statements?

At least the compiler would be able to optimize it better.

case PtrUInt(o.ClassType.ClassInfo) of PtrUInt(TObject.ClassInfo): writeln('TObject'); end;

No, that is the RTTI. While that would work as well that is an additional indirection. So it would be more like:

case PtrUInt(o.ClassType) of
    PtrUInt(TObject): writeln('TObject');
  end;
Question then is how you get the VMT address as a constant at compile time.

I'll need to get back to you with that.

Regards,
Sven

Reply by email

Ryan Joseph
to Sven Barth
Show quoted text 6 lines
On Jan 17, 2022, at 1:55 PM, Sven Barth wrote: Question then is how you get the VMT address as a constant at compile time. I'll need to get back to you with that.

I didn't test yet but I think what you're saying is that VMT writer would need to have generated this address in advance of doing tcasenode.pass_1, which could presumably get this address in some integer form. Is that basically what you're thinking is possible?

If it's a big problem I guess the question is if the if blocks are really that bad compared to alternative ( I would need to basically redo the entire thing also).

Regards,
Ryan Joseph

Reply by email

Sven Barth
to Ryan Joseph

Ryan Joseph via fpc-pascal schrieb am
Mo., 17. Jan. 2022, 08:53:

Show quoted text 16 lines
> On Jan 17, 2022, at 1:55 PM, Sven Barth wrote: > > Question then is how you get the VMT address as a constant at compile time. > > I'll need to get back to you with that. > I didn't test yet but I think what you're saying is that VMT writer would need to have generated this address in advance of doing tcasenode.pass_1, which could presumably get this address in some integer form. Is that basically what you're thinking is possible?

The VMT writer already does that, cause the VMT pointer is required for each constructor call.

If it's a big problem I guess the question is if the if blocks are really that bad compared to alternative ( I would need to basically redo the entire thing also).

That is of course the question.

Regards,
Sven

Reply by email

Ryan Joseph
to Sven Barth
On Jan 17, 2022, at 5:09 PM, Sven Barth wrote: The VMT writer already does that, cause the VMT pointer is required for each constructor call.

The pointer to the VMT table is just PVmt(self) right? If I make a program and do:

writeln(PtrUInt(TObject.ClassType));

the address changes every time the program reloads (as expected) so how do you use a constant memory address which would map to this?

Regards,
Ryan Joseph

Reply by email

Sven Barth
to Ryan Joseph
Ryan Joseph wrote 10 lines
> On Jan 17, 2022, at 5:09 PM, Sven Barth wrote: > > The VMT writer already does that, cause the VMT pointer is required for each constructor call. > The pointer to the VMT table is just PVmt(self) right? If I make a program and do: writeln(PtrUInt(TObject.ClassType)); the address changes every time the program reloads (as expected) so how do you use a constant memory address which would map to this?

The values will have the same differences between each other upon each start so ideally this would work anyway, but if one also throws dynamic packages into the mix things would get messed up. So better stay with the if-clauses.

Regards,
Sven

Reply by email

Ryan Joseph
to Sven Barth
On Jan 18, 2022, at 5:28 AM, Sven Barth wrote: The values will have the same differences between each other upon each start so ideally this would work anyway, but if one also throws dynamic packages into the mix things would get messed up. So better stay with the if-clauses.

Here's my issue and feature branch linked + tests. Please leave any comments since I wasn't 100% sure in a few places.

https://gitlab.com/freepascal.org/fpc/source/-/issues/39535

Now that the compiler is moved to GitLab do you prefer merge requests? I assumed no and that it would clutter up the system but I'll make a merge request if you want.

Regards,
Ryan Joseph

Reply by email

Sven Barth
to Ryan Joseph
Ryan Joseph wrote 9 lines
> On Jan 18, 2022, at 5:28 AM, Sven Barth wrote: > > The values will have the same differences between each other upon each start so ideally this would work anyway, but if one also throws dynamic packages into the mix things would get messed up. So better stay with the if-clauses. Here's my issue and feature branch linked + tests. Please leave any comments since I wasn't 100% sure in a few places. https://gitlab.com/freepascal.org/fpc/source/-/issues/39535 Now that the compiler is moved to GitLab do you prefer merge requests? I assumed no and that it would clutter up the system but I'll make a merge request if you want.

We also take merge requests. If you have a fork anyway, then a merge request is probably easier. Though you need to have your repository set up to use rebasing instead of merging, see here:
https://wiki.freepascal.org/FPC_git#Update

Regards,
Sven

Reply by email

Ryan Joseph
to Sven Barth
On Jan 19, 2022, at 1:26 PM, Sven Barth wrote: We also take merge requests. If you have a fork anyway, then a merge request is probably easier. Though you need to have your repository set up to use rebasing instead of merging, see here: https://wiki.freepascal.org/FPC_git#Update

Sorry I'm not following. Before starting this branch I did a pull from the main branch so I'm up to date.

What other steps do I need to do? If I do a "git pull --rebase" on the feature branch does that even do anything?

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Ryan Joseph
Ryan Joseph wrote 9 lines
> On Jan 19, 2022, at 1:26 PM, Sven Barth wrote: > > We also take merge requests. If you have a fork anyway, then a merge request is probably easier. Though you need to have your repository set up to use rebasing instead of merging, see here: https://wiki.freepascal.org/FPC_git#Update Sorry I'm not following. Before starting this branch I did a pull from the main branch so I'm up to date. What other steps do I need to do? If I do a "git pull --rebase" on the feature branch does that even do anything?

It's explained in the page that Sven referred to ?

It's only when you merge into your feature branch from the main branch that you will see an effect.

Michael.

Reply by email

Ryan Joseph
to Michael Van Canneyt
Show quoted text 5 lines
On Jan 19, 2022, at 4:15 PM, Michael Van Canneyt wrote: It's explained in the page that Sven referred to ? It's only when you merge into your feature branch from the main branch that you will see an effect.

Still not following this. Do you need me to do a pull-rebase from main and then make my pull request?

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Ryan Joseph
Ryan Joseph wrote 8 lines
> On Jan 19, 2022, at 4:19 PM, Ryan Joseph wrote: > > Still not following this. Do you need me to do a pull-rebase from main and then make my pull request? I used git at work everyday but I'm still a newbie in many ways. Reading this now but I'm confused because it seems too late. Please provide exact steps. :)

Make sure your fork gets all changes from upstream by mirroring it regularly:

https://docs.gitlab.com/ee/user/project/repository/mirror/index.html or
https://about.gitlab.com/blog/2016/12/01/how-to-keep-your-fork-up-to-date-with-its-origin/

In your local copy, execute:

git config pull.rebase true

Update your main branch:

git switch main
git pull

Now rebase your feature branch:

git switch yourfeaturebranch
git rebase main

That should be it (if there are no conflicts, which unfortunately can happen)

Michael.

Reply by email

Ryan Joseph
to Michael Van Canneyt

Ok I got this almost done (mirroring is great I didn't know I could do that) and did the rebase which shows the linear history now.

First a question, do I need to do the "rebase main" again before I push to remote or does it stay this way now?

Problem is I go to push the changes to the my remote feature branch and I get this error:

error: failed to push some refs to 'https://gitlab.com/genericptr/free-pascal.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

A pull didn't help but I think I basically broke that branch and maybe I need to delete it and start over?

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph
Show quoted text 15 lines
On Jan 19, 2022, at 8:14 PM, Ryan Joseph wrote: Ok I got this almost done (mirroring is great I didn't know I could do that) and did the rebase which shows the linear history now. First a question, do I need to do the "rebase main" again before I push to remote or does it stay this way now? Problem is I go to push the changes to the my remote feature branch and I get this error: error: failed to push some refs to 'https://gitlab.com/genericptr/free-pascal.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. A pull didn't help but I think I basically broke that branch and maybe I need to delete it and start over?

The problem was my remote for the branch got lost after rebasing but I think I fixed it by re-pulling.

It looks like some unrelated commits are included in my merge request but maybe that happened because I rebased the repo after I started working on it? Let me know if that's ok like it is.

https://gitlab.com/genericptr/free-pascal/-/merge_requests/1

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph
Show quoted text 8 lines
On Jan 20, 2022, at 9:11 AM, Ryan Joseph wrote: The problem was my remote for the branch got lost after rebasing but I think I fixed it by re-pulling. It looks like some unrelated commits are included in my merge request but maybe that happened because I rebased the repo after I started working on it? Let me know if that's ok like it is. https://gitlab.com/genericptr/free-pascal/-/merge_requests/1

I just check at https://gitlab.com/freepascal.org/fpc/source/-/merge_requests and I don't see my merge request appeared. If it were GitHub I would expect to see it there. What did I do wrong?

Regards,
Ryan Joseph

Reply by email

Ryan Joseph
to Ryan Joseph
On Jan 20, 2022, at 8:10 PM, Ryan Joseph wrote: I just check at https://gitlab.com/freepascal.org/fpc/source/-/merge_requests and I don't see my merge request appeared. If it were GitHub I would expect to see it there. What did I do wrong?

So what I did was created a merge request on my own fork. Totally not what I expected when I pressed "create merge request" Oh well here is the correct merge request.

https://gitlab.com/freepascal.org/fpc/source/-/merge_requests/147

However, now it says I need to rebase anyways so my original attempt must have not been right.

Regards,
Ryan Joseph

Reply by email