making types totally incompatible lazarus / 21-General ---------------------------------------------------------------------- MarkMLl · 2025-04-12 18:14 How can one declare two types- for example doubles- so that they are never under any circumstances directly compatible? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TMetres: double;  TKilometres: double; const  altitudeLimit: TMetres= 1500.0;  rangeLime: TKilometres= 20.0;  They should not be assignment compatible, they should not be compatible as parameters (i.e. one is promoted to the other if a function taking it as parameter is undefined), and neither should be compatible with the base type (here, double, but the same might apply to integers). MarkMLl ---------------------------------------------------------------------- jamie · 2025-04-12 18:29 Make a proxy type of double? ---------------------------------------------------------------------- cdbc · 2025-04-12 18:30 Hi Mark I believe this is the way to do that:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type TMetres: double;type TKilometres: double;It's got something to do with defining them in different 'type-blocks'  ...I think. Seen it somewhere, long ago. Regards Benny ---------------------------------------------------------------------- 440bx · 2025-04-12 19:08 Quote from: MarkMLl on April 12, 2025, 08:14:03 pmHow can one declare two types- for example doubles- so that they are never under any circumstances directly compatible? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TMetres: double;  TKilometres: double; const  altitudeLimit: TMetres= 1500.0;  rangeLime: TKilometres= 20.0;  They should not be assignment compatible, they should not be compatible as parameters (i.e. one is promoted to the other if a function taking it as parameter is undefined), and neither should be compatible with the base type (here, double, but the same might apply to integers). MarkMLl I asked that question long ago.  I've been wanting to do that for ages.  There is no way to do it in a _convenient_ manner. If you don't mind some inconvenience then it can be done like this:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  ATrulyNewType = record    v               : double;  end; Unfortunately that means the value can only be accessed using which gets old quickly.  Since I tried this years ago, I remember that by typecasting ATrulyNewType to double you can sometimes dispense of having to qualify the variable name with the field. What I also remember is that it was still quite inconvenient.  I abandoned every idea because none were simple and straightforward enough. Supposedly but, it doesn't work, something like this is supposed(?) to work: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  type  TNew = type integer;  but, TNew is still assignment compatible with integer which means it  is not really a new/different type. Hopefully someone can provide a solution because I'd love to have it too. I think it would be a really great feature if FPC gave some way of making the type definitions you showed _truly_ new and different types.  However, that means that assigning a value to it would require typecasting the value which is a small price to pay for a truly new type. ---------------------------------------------------------------------- Thaddy · 2025-04-12 19:13 Quote from: 440bx on April 12, 2025, 09:08:21 pmSupposedly but, it doesn't work, something like this is supposed(?) to work: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  type  TNew = type integer;  but, TNew is still assignment compatible with integer which means it  is not really a new/different type. That is indeed supposed to work, except.....for assignment ..(size) It is a distinct type, though. A possible way out: global properties, a feature not many people use or even know about: https://www.freepascal.org/docs-html/3.2.0/ref/refse27.html#:~:text=A% 20global%20block%20can%20declare%20properties%2C%20just%20as,a%20globa l%20property%20behaves%20like%20a%20class%20property. ---------------------------------------------------------------------- MarkMLl · 2025-04-12 19:25 Quote from: cdbc on April 12, 2025, 08:30:18 pmI believe this is the way to do that:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type TMetres: double;type TKilometres: double;It's got something to do with defining them in different 'type-blocks'  ...I think. Seen it somewhere, long ago. Ah- that's interesting, since it ties in with the special handling of records and pointers-to-records which again- AIUI and IIRC- have to be in the same block. I think that will leave double compatible, but I'll check and report back tomorrow or Monday. MarkMLl ---------------------------------------------------------------------- cdbc · 2025-04-12 20:41 Sorry Mate, I checked...  They're assignment compatible even with:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type TMetres = type double;type TKilometres = type double;Alas, could have been nice... Regards Benny ---------------------------------------------------------------------- Zoran · 2025-04-12 21:35 Quote from: Thaddy on April 12, 2025, 09:13:57 pmA possible way out: global properties, a feature not many people use or even know about: https://www.freepascal.org/docs-html/3.2.0/ref/refse27.html#:~:text=A% 20global%20block%20can%20declare%20properties%2C%20just%20as,a%20globa l%20property%20behaves%20like%20a%20class%20property. How do global properties help with unwanted assignment compatibility between distinct types? ---------------------------------------------------------------------- LV · 2025-04-12 21:54 maybe something like that Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$Mode Delphi}       // Enable strict type checking{$ModeSwitch AdvancedRecords} program project1; type  // "Meters" type with controlled operations  TMetres = record  private    Value: Double; // Internal representation  public    // Allowed operations:    class operator Add(const A, B: TMetres): TMetres; // Addition of meters    class operator Implicit(const A: Double): TMetres; // Explicit conversion Double -> Metres  end;   // "Kilometers" type with similar control  TKilometres = record  private    Value: Double;  public    class operator Add(const A, B: TKilometres): TKilometres;    class operator Implicit(const A: Double): TKilometres;  end; { Implementation of operators for TMetres } class operator TMetres.Add(const A, B: TMetres): TMetres;begin  Result.Value := A.Value + B.Value;end; class operator TMetres.Implicit(const A: Double): TMetres;begin  Result.Value := A;end; { Implementation of operators for TKilometres } class operator TKilometres.Add(const A, B: TKilometres): TKilometres;begin  Result.Value := A.Value + B.Value;end; class operator TKilometres.Implicit(const A: Double): TKilometres;begin  Result.Value := A;end; var  m1, m2: TMetres;  km1, km2: TKilometres;  d: Double; begin  // Examples of valid operations  m1 := 100.0;          // OK: implicit conversion via Implicit  m2 := 200.0;  m1 := m1 + m2;        // OK: addition of meters   km1 := 5.0;         // OK  km2 := 10.0;  km1 := km1 + km2;     // OK: addition of kilometers   // Examples of INVALID operations   m1 := m1 + km1;    // ERROR: Operator "+" not overloaded   km1 := km1 + m1;   // ERROR   d := m1;           // ERROR: Cannot assign "TMetres" to "Double"   // Explicit conversion (only if logically justified)  m1 := TMetres(km1.Value * 1000); // Explicit castingend. ---------------------------------------------------------------------- 440bx · 2025-04-12 23:37 Quote from: LV on April 12, 2025, 11:54:46 pmmaybe something like that Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$Mode Delphi}       // Enable strict type checking{$ModeSwitch AdvancedRecords} ... { etc } I have a question: why is the mode Delphi needed ?  what would be the difference with mode FPC or ObjFPC ? Thank you in advance. ---------------------------------------------------------------------- TRon · 2025-04-12 23:50 Quote from: 440bx on April 13, 2025, 01:37:26 amI have a question: why is the mode Delphi needed ? Because it isn't. Probably something the poster is used to. Note the differences in operator names between the modes in table 9.1 here. Quotewhat would be the difference with mode FPC or ObjFPC ? I do believe mode objfpc (or delphi) is required for advanced records (methods and such). ---------------------------------------------------------------------- 440bx · 2025-04-13 00:37 @TRon, If I understood what you said correctly, the only genuine difference resides in the different names used to identify operators unless mode Dellphi (which I never use) automatically enables advanced records too (don't really know if it does or not. ) ---------------------------------------------------------------------- TRon · 2025-04-13 00:44 Quote from: 440bx on April 13, 2025, 02:37:32 amIf I understood what you said correctly, the only genuine difference resides in the different names used to identify operators unless mode Dellphi (which I never use) automatically enables advanced records too (don't really know if it does or not. ) 100% Affirmative. Mode delphi does indeed support advanced records out of the box. ---------------------------------------------------------------------- 440bx · 2025-04-13 01:45 Quote from: TRon on April 13, 2025, 02:44:39 am100% Affirmative. Mode delphi does indeed support advanced records out of the box. Thank you.  That sets the record (pun!) straight ---------------------------------------------------------------------- LV · 2025-04-13 05:01 As an option for objfpc mode Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc} {$H+}{$ModeSwitch AdvancedRecords} program project1; type  // Type "Meters" with controlled operations  TMetres = record  private  Value: Double;  end;   // Type "Kilometers" with similar control  TKilometres = record  private    Value: Double;  end; // Operator overloads for TMetresoperator + (const A, B: TMetres): TMetres;begin  Result.Value := A.Value + B.Value;end; // Implicit conversion Double -> TMetresoperator := (const A: Double): TMetres;begin  Result.Value := A;end; // Operator overloads for TKilometresoperator + (const A, B: TKilometres): TKilometres;begin  Result.Value := A.Value + B.Value;end; // Implicit conversion Double -> TKilometresoperator := (const A: Double): TKilometres;begin  Result.Value := A;end; var  m1, m2: TMetres;  km1, km2: TKilometres; begin  // Examples of valid operations  m1 := 100.0;    // Implicit conversion via operator :=  m2 := 200.0;  m1 := m1 + m2;  // Addition using overloaded +   km1 := 5.0;  km2 := 10.0;  km1 := km1 + km2;   // Output values via direct access to Value field  writeln('m1 = ', m1.Value:0:2);  writeln('km1 = ', km1.Value:0:2);   // Examples of INVALID operations  // m1 := m1 + km1;  // Error: Incompatible types  // km1 := km1 + m1; // Error: Incompatible types   readln;end.  output: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i m1 = 300.00km1 = 15.00 ---------------------------------------------------------------------- 440bx · 2025-04-13 05:25 just for the record, the statements Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   writeln('m1 = ', m1.Value:0:2);  writeln('km1 = ', km1.Value:0:2); can be replaced with Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   writeln('m1 = ',  double(m1 ):0:2);  writeln('km1 = ', double(km1):0:2); which makes using the record's field name unnecessary BUT, it creates an undesirable type dependency because if the type is changed from double to something else the effect of typecasting may not yield expected behavior. One way or another there is always something that is less than ideal. ---------------------------------------------------------------------- Thaddy · 2025-04-13 06:25 Quote from: Zoran on April 12, 2025, 11:35:04 pmHow do global properties help with unwanted assignment compatibility between distinct types? RTTI: Although for both types the type kind is tkInteger, the type names differ. You can use that for e.g operators where you can test for type name to determine equivalence or you can write functions that do the same. Actually, it is not necessary to do that with global properties. It will work directly.Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}uses typinfo; type  TMy1 = type integer;  TMy2 = type integer; var  a:TMy1 = 100;  b:TMy2 = 5;     Info1, Info2:PTypeInfo;begin  Info1 := TypeInfo(a);  Info2 := TypeInfo(b);  writeln('Equal types?',Info1^.Name = Info2^.name);end. ---------------------------------------------------------------------- MarkMLl · 2025-04-13 07:36 Just to keep the pot boiling. Regrettably, all of the assignments etc. below work: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TMeters= type double;  TKilometers= type double;  TFeet= type integer;... procedure testTypeCompatibility; const  meters: TMeters= 1.0;  kilometers: TKilometers= 1.0; var  m: TMeters;  k: TKilometers;  d: double;    procedure pM(m: TMeters);   begin  end { pM } ;  begin  m := kilometers;                      (* Should fail                        *)  m := meters;                          (* Should be OK                       *)  k := meters;                          (* Should fail                          *)  k := kilometers;                    (* Should be OK                         *)  d := meters;                        (* Should fail                          *)  d := kilometers;                      (* Should fail                        *)  d := m;                               (* Should fail                        *)  m := d;                               (* Should fail                        *)  k := d;                               (* Should fail                          *)  pM(meters);                         (* Should be OK                         *)  pM(m);                              (* Should be OK                         *)  pM(kilometers);                       (* Should fail                        *)  pM(k);                                (* Should fail                        *)  pM(d)                                 (* Should fail                          *)end { testTypeCompatibility } ;  If TMetres etc. were actually defined as records with a single field, could that field be set to be the default (i.e. accessed implicitly if not specified)? ...OTOH that probably wouldn't help because implicit access to the value (i.e. a double whatever) would hide the distinct type of the record :-( I think I asked this elsewhere in the context of Delphi ten years or so ago, because I was musing about the capabilities of a C++ toolkit which could actually flag dimensionality errors (i.e. assigning seconds to meters etc.) as a compilation error. I was given a workaround, but it was subtle and might have relied on RTTI etc... not sure whether I can find it, and not sure whether it's worth the effort. I could possibly justify heavy modification of the code to encode distances as a record including both a value and a datum, but that's not going to happen immediately. Tightening up all functions etc. to use a TMetres or TFeet rather than just a double or integer would be a good start. I've not actually seen a screwed assignment, but this started when I realised that I was outputting something as feet when it was still actually in meters: which is of course a whole other can of worms. MarkMLl ---------------------------------------------------------------------- 440bx · 2025-04-13 08:59 Quote from: MarkMLl on April 13, 2025, 09:36:18 am this started when I realised that I was outputting something as feet when it was still actually in meters: which is of course a whole other can of worms. I seem to remember @Circular worked on a unit that created dimension types and protected against such mixups.  My recollection of it is very sketchy, I'll leave it to @Circular to provide more details if he happens to read this. ---------------------------------------------------------------------- paweld · 2025-04-13 09:37 @440bx : https://forum.lazarus.freepascal.org/index.php/topic,61958.0.html ---------------------------------------------------------------------- 440bx · 2025-04-13 09:51 @paweld, Thank you.  For some reason I couldn't find it. ---------------------------------------------------------------------- MarkMLl · 2025-04-13 10:46 Quote from: MarkMLl on April 13, 2025, 09:36:18 amI think I asked this elsewhere in the context of Delphi ten years or so ago, because I was musing about the capabilities of a C++ toolkit which could actually flag dimensionality errors (i.e. assigning seconds to meters etc.) as a compilation error. I was given a workaround, but it was subtle and might have relied on RTTI etc... not sure whether I can find it, and not sure whether it's worth the effort. I've been looking back through a private conferencing system's archive, and found this which I hope will amuse if nothing else: Quote> Will, do you remember the example you gave a few years ago of how (code written in) C++ could track the dimensions of quantities (i.e. mass-length-time dimensional analysis)? Yes indeed. The modern, de facto standard version of that library is Boost's Units library: http://www.boost.org/doc/libs/1_61_0/doc/html/boost_units.html > Can C-hash [must fix this damn keyboard] do anything similar? C++'s ability to do this is a consequence of its early, eccentric implementation of generics (small integer constants can be treated as types!), which can be [ab]used to perform meta-programming, ie application code that runs at compile time. This is how the library is implemented. Later implementers of generics in other languages (Java, Delf and, I believe, C#) used a less mad approach which is easier all round, but lacks C++'s facility for interesting perversion. Now that it has been shown that it can be put to useful purpose, C++ is gaining actually properly designed new features that should make it possible to do this thing using less bizarre mechanisms. Also, Walter Bright's D has support for this sort of thing by design. As for C#, I await Matthew's pronouncement in due course. When's he's watched the appropriate PluralSight course ;-) MarkMLl ---------------------------------------------------------------------- H₂SO₄ · 2025-04-14 06:14 Quote from: MarkMLl on April 13, 2025, 12:46:59 pmQuote[...] eccentric implementation of generics [...] This gives me an idea: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  generic TQuantity = record  private type    TSelf = specialize TQuantity;  private    Value: T;  public    class operator explicit(const Self: TSelf): T;    class operator explicit(const AValue: T): TSelf;    class operator +(const A, B: TSelf): TSelf;    // class operator - [...] etc.    function ToString(): String;  end; class operator TQuantity.explicit(const Self: TSelf): T;begin  Result := Self.Value;end; class operator TQuantity.explicit(const AValue: T): TSelf;begin  Result.Value := AValue;end; class operator TQuantity.+(const A, B: TSelf): TSelf;begin  Result.Value := A.Value + B.Value;end; function TQuantity.ToString(): String;begin  if TypeInfo(T) = TypeInfo(Double) then    Result := Format('%.2f %s', [PDouble(@Value)^, Symbol])  else if TypeInfo(T) = TypeInfo(Integer) then    Result := Format('%d %s', [PInteger(@Value)^, Symbol])  else    Result := '??? ' + Symbol;end; With these changes... Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TMeters= specialize TQuantity;  TKilometers= specialize TQuantity;  TFeet= specialize TQuantity;... procedure testTypeCompatibility; const  meters: TMeters= (Value: 1.0);  kilometers: TKilometers= (Value: 1.0); ...all the tests pass/fail as expected: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i test.pas(26,8) Error: Incompatible types: got "TQuantity" expected "TQuantity"test.pas(28,8) Error: Incompatible types: got "TQuantity" expected "TQuantity"test.pas(30,8) Error: Incompatible types: got "TQuantity" expected "Double"test.pas(31,8) Error: Incompatible types: got "TQuantity" expected "Double"test.pas(32,8) Error: Incompatible types: got "TQuantity" expected "Double"test.pas(33,8) Error: Incompatible types: got "Double" expected "TQuantity"test.pas(34,8) Error: Incompatible types: got "Double" expected "TQuantity"test.pas(37,16) Error: Incompatible type for arg no. 1: Got "TQuantity", expected "TQuantity"test.pas(38,7) Error: Incompatible type for arg no. 1: Got "TQuantity", expected "TQuantity"test.pas(39,7) Error: Incompatible type for arg no. 1: Got "Double", expected "TQuantity" ---------------------------------------------------------------------- Thaddy · 2025-04-14 06:54 Neat! ---------------------------------------------------------------------- MarkMLl · 2025-04-14 18:48 That's... interesting. I think I see what's going on, although I might end up using a simpler record-based system since I can justify storing a datum with each value. What version of the compiler does that work with? It looks like trunk, including stuff that isn't documented yet. If one used that to define types for meters, kilograms and seconds, I wonder how much of the MKS system would fall out without further intervention? :-) For complicated reasons I did a batch of science O-levels (mid-teen public examinations) in a rush, and went into the physics exam knowing nothing but Ohm's law and dimensional analysis. Because we were supplied with a leaflet of constants showing what the dimensions of each were, I was able to work out everything else I needed on the fly :-) MarkMLl p.s. is that line 17 correct or should the RHS be Self rather than T? ---------------------------------------------------------------------- TRon · 2025-04-14 20:27 Quote from: MarkMLl on April 14, 2025, 08:48:59 pmWhat version of the compiler does that work with? It looks like trunk, including stuff that isn't documented yet. It requires trunk for the time being (it does not compile with 3.2.2), might have been back-ported to fixes (I did not checked). ---------------------------------------------------------------------- PascalDragon · 2025-04-15 20:31 Quote from: TRon on April 14, 2025, 10:27:50 pmQuote from: MarkMLl on April 14, 2025, 08:48:59 pmWhat version of the compiler does that work with? It looks like trunk, including stuff that isn't documented yet. It requires trunk for the time being (it does not compile with 3.2.2), might have been back-ported to fixes (I did not checked). You probably mean constant generic parameters. These are only supported in main. ---------------------------------------------------------------------- TRon · 2025-04-16 01:14 Quote from: PascalDragon on April 15, 2025, 10:31:33 pmYou probably mean constant generic parameters. These are only supported in main. Thx, that is indeed the terminology I wasn't able to reproduce. I'm also not sure if that is considered a new feature or correction on/for existing generics implementation (e.g. which release will eventually contain it, besides main that is). ---------------------------------------------------------------------- H₂SO₄ · 2025-04-16 05:42 Quote from: MarkMLl on April 14, 2025, 08:48:59 pmp.s. is that line 17 correct or should the RHS be Self rather than T? Whoops, you're right. Now it's correct  And yes, I tested this on trunk, although the constant generic parameter feature will turn 5 years old this month. ---------------------------------------------------------------------- Thaddy · 2025-04-16 10:02 Quote from: MarkMLl on April 14, 2025, 08:48:59 pmWhat version of the compiler does that work with? It looks like trunk, including stuff that isn't documented yet. It may be documented when you build the documentation for main from source but I did not check that. I only occasionally do that. Much, much less then I build main. Building docs is easiest done, requires, Linux. The docs are in a separate git repository. Code: Bash  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i git clone cd https://gitlab.com/freepascal.org/fpc/documentation.git documentation#required dependenciessudo apt-get install texlive-latex- basesudo apt-get install texlive-latex-extrasudo apt-get install texlive-latex-recommendedsudo apt install pandoc #dunno of this is necessarycd documentationsudo make pdfI think I left out something.. find out what.. edit later. (I forgot building docs can take a long time on a slow computer, even on a fast computer.... silly me.) ---------------------------------------------------------------------- Thaddy · 2025-04-19 13:13 How about:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}type  generic TMyGenericRecord = record    value:T;  end;beginend.Initial tests show assignment is only to specialized T, nothing else. Will finish it later.