Browse Source

merge revisions: r14008,r14041,r14042,r14043,r14044,r14045,r14065,r14067,r14087,r14088,r14093,r14095,r14171:

r14008:
merge revisions: 13909,13923,13924,13934,13935,13942,13943,13944,13946,13948,13950,13951,13952,13983,13994:
rtl: add enumerators to the basic classes
tests: add enumerators test which compiles and work both by fpc and dcc
compiler: 
  + start for-in loop implementation: implement for-in loop for types (enumerations and ranges), strings, arrays and sets. todo: perform type checking, optimize array and string loops - use temp for expression, implement for-in loop for classes
test:
  + add a simple test for the 'for-in' loop
compiler: fix string for-in loop. now it uses a temp variable to store string expression result
complier: fix for-in array loop. use a temp variable for the loop expression only if loop is not an open array loop
complier: continue enumerator implementation:
  + add operator enumerator which give an ability to add enumerator for an existent type (for example to override builtin string enumerator)
  + add class enumerator support via delphi compatible GetEnumerator method + enumerator class/object template (function MoveNext: Boolean; property Current)
  + tests
compiler: fix for-in loop for arrays. delphi does not copy arrays to a temp variable and it is possible to change array during loop. + test
compiler: add reference for the enumerator operator when it is used + another test for operator enumerator for a class
compiler: add reference for the enumerator operator when it is used + another test for operator enumerator for a class
compiler: enumerator directive support:
  + allow to mark methods and properties by 'enumerator MoveNext' and 'enumerator Current' modifiers. Parser checks return types and duplicates.
  + prefer *marked* by enumerator directive methods and properties than GetEnumerator and Current builtin symbols
  + increase ppu version
  + test
rtl: add IEnumerator and IEnumerable interfaces declarations
tests: for-in loop tests:
  + add small comment at the top of test program
compiler: allow 'enumerator MoveNext' for the interface function declaration + test
compiler: move all for-in loop helpers to the nflw unit
compiler: don't allow the compiler to choose the non-valid enumerator operator for the for-in loop

r14041:
compiler: 
  - fix for-in loop for string const array
  - add some test from Alexander S. Klenin
(issue #0014990)

r14042:
compiler: 
  - fix for-in loop for empty sets
  - add some test from Alexander S. Klenin
(issue #0014990)

r14043:
compiler:
  - don't allow operator enumerator with non object/class/interface result type
  - add some test from Alexander S. Klenin
(issue #0014990)

r14044:
compiler:
  - don't find MoveNext functions with the required arguments
  - add some test from Alexander S. Klenin
(issue #0014990)

r14045:
compiler: check that method marked by 'enumerator MoveNext' have no required arguments. correct error message.

r14065:
packages: add enumerator for TFields class

r14067:
compiler: don't allow for-in loop for the enums with jumps. test should fail.

r14087:
compiler: fix position information of the for-in loop (needs for correct debug info)

r14088:
compiler: fix error message positions for the for-in loop errors

r14093:
compiler: allow enumeration of multidimensional arrays with implicit array conversion + test

r14095:
compiler: for-in loop: fix temporary array range type

r14171:
compiler: add fpc_has_operator_enumerator define

git-svn-id: branches/fixes_2_4@14738 -
paul 15 years ago
parent
commit
56531ae398
51 changed files with 2483 additions and 420 deletions
  1. 24 0
      .gitattributes
  2. 11 4
      compiler/htypechk.pas
  3. 26 2
      compiler/msg/errore.msg
  4. 12 2
      compiler/msgidx.inc
  5. 250 235
      compiler/msgtxt.inc
  6. 433 5
      compiler/nflw.pas
  7. 20 0
      compiler/nutils.pas
  8. 1 0
      compiler/options.pas
  9. 25 0
      compiler/pdecobj.pas
  10. 46 4
      compiler/pdecsub.pas
  11. 2 21
      compiler/pexpr.pas
  12. 3 1
      compiler/pp.lpi
  13. 1 1
      compiler/ppu.pas
  14. 160 133
      compiler/pstatmnt.pas
  15. 10 3
      compiler/symconst.pas
  16. 117 0
      compiler/symdef.pas
  17. 80 0
      compiler/symsym.pas
  18. 40 2
      compiler/symtable.pas
  19. 5 1
      compiler/tokens.pas
  20. 12 4
      compiler/utils/ppudump.pp
  21. 12 0
      rtl/inc/objpash.inc
  22. 78 0
      rtl/objpas/classes/classesh.inc
  23. 29 0
      rtl/objpas/classes/collect.inc
  24. 29 0
      rtl/objpas/classes/compon.inc
  25. 29 0
      rtl/objpas/classes/intf.inc
  26. 52 2
      rtl/objpas/classes/lists.inc
  27. 28 0
      rtl/objpas/classes/stringl.inc
  28. 166 0
      tests/test/tenumerators1.pp
  29. 71 0
      tests/test/tforin1.pp
  30. 29 0
      tests/test/tforin10.pp
  31. 17 0
      tests/test/tforin11.pp
  32. 10 0
      tests/test/tforin12.pp
  33. 8 0
      tests/test/tforin13.pp
  34. 24 0
      tests/test/tforin14.pp
  35. 39 0
      tests/test/tforin15.pp
  36. 7 0
      tests/test/tforin16.pp
  37. 6 0
      tests/test/tforin17.pp
  38. 6 0
      tests/test/tforin18.pp
  39. 7 0
      tests/test/tforin19.pp
  40. 84 0
      tests/test/tforin2.pp
  41. 9 0
      tests/test/tforin20.pp
  42. 14 0
      tests/test/tforin21.pp
  43. 27 0
      tests/test/tforin22.pp
  44. 24 0
      tests/test/tforin23.pp
  45. 48 0
      tests/test/tforin3.pp
  46. 59 0
      tests/test/tforin4.pp
  47. 50 0
      tests/test/tforin5.pp
  48. 58 0
      tests/test/tforin6.pp
  49. 56 0
      tests/test/tforin7.pp
  50. 61 0
      tests/test/tforin8.pp
  51. 68 0
      tests/test/tforin9.pp

+ 24 - 0
.gitattributes

@@ -8261,6 +8261,7 @@ tests/test/tcmp0.pp svneol=native#text/plain
 tests/test/tendian1.pp svneol=native#text/plain
 tests/test/tendian1.pp svneol=native#text/plain
 tests/test/tenum1.pp svneol=native#text/plain
 tests/test/tenum1.pp svneol=native#text/plain
 tests/test/tenum2.pp svneol=native#text/plain
 tests/test/tenum2.pp svneol=native#text/plain
+tests/test/tenumerators1.pp svneol=native#text/pascal
 tests/test/testcmem.pp svneol=native#text/plain
 tests/test/testcmem.pp svneol=native#text/plain
 tests/test/testda1.pp svneol=native#text/plain
 tests/test/testda1.pp svneol=native#text/plain
 tests/test/testfpuc.pp svneol=native#text/plain
 tests/test/testfpuc.pp svneol=native#text/plain
@@ -8288,6 +8289,29 @@ tests/test/texception7.pp svneol=native#text/plain
 tests/test/texception8.pp svneol=native#text/plain
 tests/test/texception8.pp svneol=native#text/plain
 tests/test/texception9.pp svneol=native#text/plain
 tests/test/texception9.pp svneol=native#text/plain
 tests/test/tfillchr.pp svneol=native#text/plain
 tests/test/tfillchr.pp svneol=native#text/plain
+tests/test/tforin1.pp svneol=native#text/pascal
+tests/test/tforin10.pp svneol=native#text/plain
+tests/test/tforin11.pp svneol=native#text/plain
+tests/test/tforin12.pp svneol=native#text/pascal
+tests/test/tforin13.pp svneol=native#text/pascal
+tests/test/tforin14.pp svneol=native#text/pascal
+tests/test/tforin15.pp svneol=native#text/pascal
+tests/test/tforin16.pp svneol=native#text/pascal
+tests/test/tforin17.pp svneol=native#text/pascal
+tests/test/tforin18.pp svneol=native#text/pascal
+tests/test/tforin19.pp svneol=native#text/pascal
+tests/test/tforin2.pp svneol=native#text/pascal
+tests/test/tforin20.pp svneol=native#text/pascal
+tests/test/tforin21.pp svneol=native#text/pascal
+tests/test/tforin22.pp svneol=native#text/pascal
+tests/test/tforin23.pp svneol=native#text/pascal
+tests/test/tforin3.pp svneol=native#text/pascal
+tests/test/tforin4.pp svneol=native#text/pascal
+tests/test/tforin5.pp svneol=native#text/pascal
+tests/test/tforin6.pp svneol=native#text/pascal
+tests/test/tforin7.pp svneol=native#text/pascal
+tests/test/tforin8.pp svneol=native#text/pascal
+tests/test/tforin9.pp svneol=native#text/pascal
 tests/test/tfpu1.pp svneol=native#text/plain
 tests/test/tfpu1.pp svneol=native#text/plain
 tests/test/tfpu2.pp svneol=native#text/plain
 tests/test/tfpu2.pp svneol=native#text/plain
 tests/test/tfpu3.pp svneol=native#text/plain
 tests/test/tfpu3.pp svneol=native#text/plain

+ 11 - 4
compiler/htypechk.pas

@@ -108,9 +108,9 @@ interface
         (tok:_LTE     ;nod:lten;op_overloading_supported:true),      { binary overloading supported }
         (tok:_LTE     ;nod:lten;op_overloading_supported:true),      { binary overloading supported }
         (tok:_SYMDIF  ;nod:symdifn;op_overloading_supported:true),   { binary overloading supported }
         (tok:_SYMDIF  ;nod:symdifn;op_overloading_supported:true),   { binary overloading supported }
         (tok:_STARSTAR;nod:starstarn;op_overloading_supported:true), { binary overloading supported }
         (tok:_STARSTAR;nod:starstarn;op_overloading_supported:true), { binary overloading supported }
-        (tok:_OP_AS     ;nod:asn;op_overloading_supported:false),     { binary overloading NOT supported }
-        (tok:_OP_IN     ;nod:inn;op_overloading_supported:false),     { binary overloading NOT supported }
-        (tok:_OP_IS     ;nod:isn;op_overloading_supported:false),     { binary overloading NOT supported }
+        (tok:_OP_AS     ;nod:asn;op_overloading_supported:false),    { binary overloading NOT supported }
+        (tok:_OP_IN     ;nod:inn;op_overloading_supported:false),    { binary overloading NOT supported }
+        (tok:_OP_IS     ;nod:isn;op_overloading_supported:false),    { binary overloading NOT supported }
         (tok:_OP_OR     ;nod:orn;op_overloading_supported:true),     { binary overloading supported }
         (tok:_OP_OR     ;nod:orn;op_overloading_supported:true),     { binary overloading supported }
         (tok:_OP_AND    ;nod:andn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_OP_AND    ;nod:andn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_OP_DIV    ;nod:divn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_OP_DIV    ;nod:divn;op_overloading_supported:true),    { binary overloading supported }
@@ -120,7 +120,7 @@ interface
         (tok:_OP_SHR    ;nod:shrn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_OP_SHR    ;nod:shrn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_OP_XOR    ;nod:xorn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_OP_XOR    ;nod:xorn;op_overloading_supported:true),    { binary overloading supported }
         (tok:_ASSIGNMENT;nod:assignn;op_overloading_supported:true), { unary overloading supported }
         (tok:_ASSIGNMENT;nod:assignn;op_overloading_supported:true), { unary overloading supported }
-        (tok:_UNEQUAL ;nod:unequaln;op_overloading_supported:false)   { binary overloading NOT supported  overload = instead }
+        (tok:_UNEQUAL ;nod:unequaln;op_overloading_supported:false)  { binary overloading NOT supported  overload = instead }
       );
       );
 
 
       { true, if we are parsing stuff which allows array constructors }
       { true, if we are parsing stuff which allows array constructors }
@@ -421,6 +421,13 @@ implementation
                       (not is_shortstring(pf.returndef) or
                       (not is_shortstring(pf.returndef) or
                        (tstringdef(pf.returndef).len=255));
                        (tstringdef(pf.returndef).len=255));
                   end
                   end
+                else
+                { enumerator is a special case too }
+                if optoken=_OP_ENUMERATOR then
+                  begin
+                    result:=
+                      is_class_or_interface_or_object(pf.returndef);
+                  end
                 else
                 else
                   begin
                   begin
                     for i:=1 to tok2nodes do
                     for i:=1 to tok2nodes do

+ 26 - 2
compiler/msg/errore.msg

@@ -366,7 +366,7 @@ scan_w_multiple_main_name_overrides=02086_W_Overriding name of "main" procedure
 #
 #
 # Parser
 # Parser
 #
 #
-# 03252 is the last used one
+# 03265 is the last used one
 #
 #
 % \section{Parser messages}
 % \section{Parser messages}
 % This section lists all parser messages. The parser takes care of the
 % This section lists all parser messages. The parser takes care of the
@@ -1189,6 +1189,20 @@ parser_e_no_local_para_def=03252_E_Parameters cannot contain local type definiti
 % refer to the same type definition in the procedure headers of the interface and implementation of a unit
 % refer to the same type definition in the procedure headers of the interface and implementation of a unit
 % (both procedure headers would define a separate type). Keep in mind that expressions such as
 % (both procedure headers would define a separate type). Keep in mind that expressions such as
 % ``file of byte'' or ``string[50]'' also define a new type.
 % ``file of byte'' or ``string[50]'' also define a new type.
+parser_e_invalid_enumerator_identifier=03259_E_Invalid enumerator identifier: "$1"
+% Only "MoveNext" and "Current" enumerator identifiers are supported.
+parser_e_enumerator_identifier_required=03260_E_Enumerator identifier required
+% "MoveNext" or "Current" identifier must follow the \var{enumerator} modifier.
+parser_e_enumerator_movenext_is_not_valid=03261_E_Enumerator MoveNext pattern method is not valid. Method must be a function with the Boolean return type and no required arguments.
+% "MoveNext" enumerator pattern method must be a function with Boolean return type and no required arguments
+parser_e_enumerator_current_is_not_valid=03262_E_Enumerator Current pattern property is not valid. Property must have a getter.
+% "Current" enumerator pattern property must have a getter
+parser_e_only_one_enumerator_movenext=03263_E_Only one enumerator MoveNext method is allowed per class/object
+% Class or Object can have only one enumerator MoveNext declaration.
+parser_e_only_one_enumerator_current=03264_E_Only one enumerator Current property is allowed per class/object
+% Class or Object can have only one enumerator Current declaration.
+parser_e_for_in_loop_cannot_be_used_for_the_type=03265_E_For in loop can not be used for the type "$1"
+% For in loop can be used not for all types. For example it can not be used for the enumerations with jumps.
 % \end{description}
 % \end{description}
 #
 #
 # Type Checking
 # Type Checking
@@ -1495,7 +1509,7 @@ type_e_no_type_info=04087_E_No type info available for this type
 #
 #
 # Symtable
 # Symtable
 #
 #
-# 05064 is the last used one
+# 05069 is the last used one
 #
 #
 % \section{Symbol handling}
 % \section{Symbol handling}
 % This section lists all the messages that concern the handling of symbols.
 % This section lists all the messages that concern the handling of symbols.
@@ -1666,6 +1680,16 @@ sym_w_experimental_symbol=05063_W_Symbol "$1" is experimental
 sym_w_forward_not_resolved=05064_W_Forward declaration "$1" not resolved, assumed external
 sym_w_forward_not_resolved=05064_W_Forward declaration "$1" not resolved, assumed external
 % This happens if you declare a function in the \var{interface} of a unit in macpas mode,
 % This happens if you declare a function in the \var{interface} of a unit in macpas mode,
 % but do not implement it.
 % but do not implement it.
+sym_e_no_enumerator=05067_E_Can not find an enumerator for the type "$1"
+% This means that compiler can not find an apropriate enumerator to use in the for-in loop.
+% To create an enumerator you need to defind an operator enumerator or add a public or published 
+% GetEnumerator method to the class or object definition.
+sym_e_no_enumerator_move=05068_E_Can not find a "MoveNext" method in enumerator "$1"
+% This means that compiler can not find a public MoveNext method with the Boolean return type in
+% the enumerator class or object definition.
+sym_e_no_enumerator_current=05069_E_Can not find a "Current" property in enumerator "$1"
+% This means that compiler can not find a public Current property in  the enumerator class or object 
+% definition.
 % \end{description}
 % \end{description}
 #
 #
 # Codegenerator
 # Codegenerator

+ 12 - 2
compiler/msgidx.inc

@@ -340,6 +340,13 @@ const
   parser_n_ignore_lower_visibility=03250;
   parser_n_ignore_lower_visibility=03250;
   parser_e_field_not_allowed_here=03251;
   parser_e_field_not_allowed_here=03251;
   parser_e_no_local_para_def=03252;
   parser_e_no_local_para_def=03252;
+  parser_e_invalid_enumerator_identifier=03259;
+  parser_e_enumerator_identifier_required=03260;
+  parser_e_enumerator_movenext_is_not_valid=03261;
+  parser_e_enumerator_current_is_not_valid=03262;
+  parser_e_only_one_enumerator_movenext=03263;
+  parser_e_only_one_enumerator_current=03264;
+  parser_e_for_in_loop_cannot_be_used_for_the_type=03265;
   type_e_mismatch=04000;
   type_e_mismatch=04000;
   type_e_incompatible_types=04001;
   type_e_incompatible_types=04001;
   type_e_not_equal_types=04002;
   type_e_not_equal_types=04002;
@@ -469,6 +476,9 @@ const
   sym_h_abstract_method_list=05062;
   sym_h_abstract_method_list=05062;
   sym_w_experimental_symbol=05063;
   sym_w_experimental_symbol=05063;
   sym_w_forward_not_resolved=05064;
   sym_w_forward_not_resolved=05064;
+  sym_e_no_enumerator=05067;
+  sym_e_no_enumerator_move=05068;
+  sym_e_no_enumerator_current=05069;
   cg_e_parasize_too_big=06009;
   cg_e_parasize_too_big=06009;
   cg_e_file_must_call_by_reference=06012;
   cg_e_file_must_call_by_reference=06012;
   cg_e_cant_use_far_pointer_there=06013;
   cg_e_cant_use_far_pointer_there=06013;
@@ -791,9 +801,9 @@ const
   option_info=11024;
   option_info=11024;
   option_help_pages=11025;
   option_help_pages=11025;
 
 
-  MsgTxtSize = 51811;
+  MsgTxtSize = 52493;
 
 
   MsgIdxMax : array[1..20] of longint=(
   MsgIdxMax : array[1..20] of longint=(
-    24,87,253,88,65,50,108,22,202,63,
+    24,87,266,88,70,50,108,22,202,63,
     48,20,1,1,1,1,1,1,1,1
     48,20,1,1,1,1,1,1,1,1
   );
   );

File diff suppressed because it is too large
+ 250 - 235
compiler/msgtxt.inc


+ 433 - 5
compiler/nflw.pas

@@ -216,17 +216,22 @@ interface
        ctryfinallynode : ttryfinallynodeclass;
        ctryfinallynode : ttryfinallynodeclass;
        connode : tonnodeclass;
        connode : tonnodeclass;
 
 
+// for-in loop helpers
+function create_type_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+function create_string_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+function create_array_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+function create_set_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+function create_enumerator_for_in_loop(hloopvar, hloopbody, expr: tnode;
+   enumerator_get, enumerator_move: tprocdef; enumerator_current: tpropertysym): tnode;
+function create_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
 
 
 implementation
 implementation
 
 
     uses
     uses
       globtype,systems,constexp,
       globtype,systems,constexp,
       cutils,verbose,globals,
       cutils,verbose,globals,
-      symconst,paramgr,defcmp,defutil,htypechk,pass_1,
-      ncal,nadd,ncon,nmem,nld,ncnv,nbas,cgobj,nutils,
-    {$ifdef prefetchnext}
-      ninl,
-    {$endif prefetchnext}
+      symconst,symtable,paramgr,defcmp,defutil,htypechk,pass_1,
+      ncal,nadd,ncon,nmem,nld,ncnv,nbas,cgobj,nutils,ninl,nset,
     {$ifdef state_tracking}
     {$ifdef state_tracking}
       nstate,
       nstate,
     {$endif}
     {$endif}
@@ -234,6 +239,429 @@ implementation
       ;
       ;
 
 
 
 
+// for-in loop helpers
+
+function create_type_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+begin
+  result:=cfornode.create(hloopvar,
+       cinlinenode.create(in_low_x,false,expr.getcopy),
+       cinlinenode.create(in_high_x,false,expr.getcopy),
+       hloopbody,
+       false);
+end;
+
+function create_string_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+var
+  loopstatement, loopbodystatement: tstatementnode;
+  loopvar, stringvar: ttempcreatenode;
+  stringindex, loopbody, forloopnode: tnode;
+begin
+  { result is a block of statements }
+  result:=internalstatements(loopstatement);
+
+  { create a temp variable for expression }
+  stringvar := ctempcreatenode.create(
+    expr.resultdef,
+    expr.resultdef.size,
+    tt_persistent,true);
+
+  addstatement(loopstatement,stringvar);
+  addstatement(loopstatement,cassignmentnode.create(ctemprefnode.create(stringvar),expr.getcopy));
+
+  { create a loop counter: signed integer with size of string length }
+  loopvar := ctempcreatenode.create(
+    sinttype,
+    sinttype.size,
+    tt_persistent,true);
+
+  addstatement(loopstatement,loopvar);
+
+  stringindex:=ctemprefnode.create(loopvar);
+
+  loopbody:=internalstatements(loopbodystatement);
+  // for-in loop variable := string_expression[index]
+  addstatement(loopbodystatement,
+      cassignmentnode.create(hloopvar, cvecnode.create(ctemprefnode.create(stringvar),stringindex)));
+
+  { add the actual statement to the loop }
+  addstatement(loopbodystatement,hloopbody);
+
+  forloopnode:=cfornode.create(ctemprefnode.create(loopvar),
+     genintconstnode(1),
+     cinlinenode.create(in_length_x,false,ctemprefnode.create(stringvar)),
+     loopbody,
+     false);
+
+  addstatement(loopstatement,forloopnode);
+  { free the loop counter }
+  addstatement(loopstatement,ctempdeletenode.create(loopvar));
+  { free the temp variable for expression }
+  addstatement(loopstatement,ctempdeletenode.create(stringvar));
+end;
+
+function create_array_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+var
+  loopstatement, loopbodystatement: tstatementnode;
+  loopvar, arrayvar: ttempcreatenode;
+  arrayindex, lowbound, highbound, loopbody, forloopnode, expression: tnode;
+  is_string: boolean;
+  tmpdef, convertdef: tdef;
+  elementcount: aword;
+begin
+  expression := expr;
+
+  { result is a block of statements }
+  result:=internalstatements(loopstatement);
+
+  is_string:=ado_IsConstString in tarraydef(expr.resultdef).arrayoptions;
+
+  // if array element type <> loovar type then create a conversion if possible
+  if compare_defs(tarraydef(expression.resultdef).elementdef,hloopvar.resultdef,nothingn)=te_incompatible then
+  begin
+    tmpdef:=expression.resultdef;
+    elementcount:=1;
+    while assigned(tmpdef) and (tmpdef.typ=arraydef) and
+          (tarraydef(tmpdef).arrayoptions = []) and
+          (compare_defs(tarraydef(tmpdef).elementdef,hloopvar.resultdef,nothingn)=te_incompatible) do
+    begin
+      elementcount:=elementcount*tarraydef(tmpdef).elecount;
+      tmpdef:=tarraydef(tmpdef).elementdef;
+    end;
+    if assigned(tmpdef) and (tmpdef.typ=arraydef) and (tarraydef(tmpdef).arrayoptions = []) then
+    begin
+      elementcount:=elementcount*tarraydef(tmpdef).elecount;
+      convertdef:=tarraydef.create(0,elementcount-1,s32inttype);
+      tarraydef(convertdef).elementdef:=tarraydef(tmpdef).elementdef;
+      expression:=expr.getcopy;
+      expression:=ctypeconvnode.create_internal(expression,convertdef);
+      typecheckpass(expression);
+      addstatement(loopstatement,expression);
+    end;
+  end;
+
+  if (node_complexity(expression) > 1) and not is_open_array(expression.resultdef) then
+  begin
+    { create a temp variable for expression }
+    arrayvar := ctempcreatenode.create(
+      expression.resultdef,
+      expression.resultdef.size,
+      tt_persistent,true);
+
+    if is_string then
+    begin
+      lowbound:=genintconstnode(1);
+      highbound:=cinlinenode.create(in_length_x,false,ctemprefnode.create(arrayvar))
+    end
+    else
+    begin
+      lowbound:=cinlinenode.create(in_low_x,false,ctemprefnode.create(arrayvar));
+      highbound:=cinlinenode.create(in_high_x,false,ctemprefnode.create(arrayvar));
+    end;
+
+    addstatement(loopstatement,arrayvar);
+    addstatement(loopstatement,cassignmentnode.create(ctemprefnode.create(arrayvar),expression.getcopy));
+  end
+  else
+  begin
+    arrayvar:=nil;
+    if is_string then
+    begin
+      lowbound:=genintconstnode(1);
+      highbound:=cinlinenode.create(in_length_x,false,expression.getcopy);
+    end
+    else
+    begin
+      lowbound:=cinlinenode.create(in_low_x,false,expression.getcopy);
+      highbound:=cinlinenode.create(in_high_x,false,expression.getcopy);
+    end;
+  end;
+
+  { create a loop counter }
+  loopvar := ctempcreatenode.create(
+    tarraydef(expression.resultdef).rangedef,
+    tarraydef(expression.resultdef).rangedef.size,
+    tt_persistent,true);
+
+  addstatement(loopstatement,loopvar);
+
+  arrayindex:=ctemprefnode.create(loopvar);
+
+  loopbody:=internalstatements(loopbodystatement);
+  // for-in loop variable := array_expression[index]
+  if assigned(arrayvar) then
+    addstatement(loopbodystatement,
+        cassignmentnode.create(hloopvar,cvecnode.create(ctemprefnode.create(arrayvar),arrayindex)))
+  else
+    addstatement(loopbodystatement,
+        cassignmentnode.create(hloopvar,cvecnode.create(expression.getcopy,arrayindex)));
+
+  { add the actual statement to the loop }
+  addstatement(loopbodystatement,hloopbody);
+
+  forloopnode:=cfornode.create(ctemprefnode.create(loopvar),
+     lowbound,
+     highbound,
+     loopbody,
+     false);
+
+  addstatement(loopstatement,forloopnode);
+  { free the loop counter }
+  addstatement(loopstatement,ctempdeletenode.create(loopvar));
+  { free the temp variable for expression if needed }
+  if arrayvar<>nil then
+    addstatement(loopstatement,ctempdeletenode.create(arrayvar));
+end;
+
+function create_set_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+var
+  loopstatement, loopbodystatement: tstatementnode;
+  loopvar, setvar: ttempcreatenode;
+  loopbody, forloopnode: tnode;
+begin
+  // first check is set is empty and if it so then skip other processing
+  if not Assigned(tsetdef(expr.resultdef).elementdef) then
+  begin
+    result:=cnothingnode.create;
+    // free unused nodes
+    hloopvar.free;
+    hloopbody.free;
+    exit;
+  end;
+  { result is a block of statements }
+  result:=internalstatements(loopstatement);
+
+  { create a temp variable for expression }
+  setvar := ctempcreatenode.create(
+    expr.resultdef,
+    expr.resultdef.size,
+    tt_persistent,true);
+
+  addstatement(loopstatement,setvar);
+  addstatement(loopstatement,cassignmentnode.create(ctemprefnode.create(setvar),expr.getcopy));
+
+  { create a loop counter }
+  loopvar := ctempcreatenode.create(
+    tsetdef(expr.resultdef).elementdef,
+    tsetdef(expr.resultdef).elementdef.size,
+    tt_persistent,true);
+
+  addstatement(loopstatement,loopvar);
+
+  // if loopvar in set then
+  // begin
+  //   hloopvar := loopvar
+  //   for-in loop body
+  // end
+
+  loopbody:=cifnode.create(
+        cinnode.create(ctemprefnode.create(loopvar),ctemprefnode.create(setvar)),
+        internalstatements(loopbodystatement),
+        nil
+  );
+
+  addstatement(loopbodystatement,cassignmentnode.create(hloopvar,ctemprefnode.create(loopvar)));
+  { add the actual statement to the loop }
+  addstatement(loopbodystatement,hloopbody);
+
+  forloopnode:=cfornode.create(ctemprefnode.create(loopvar),
+     cinlinenode.create(in_low_x,false,ctemprefnode.create(setvar)),
+     cinlinenode.create(in_high_x,false,ctemprefnode.create(setvar)),
+     loopbody,
+     false);
+
+  addstatement(loopstatement,forloopnode);
+  { free the loop counter }
+  addstatement(loopstatement,ctempdeletenode.create(loopvar));
+  { free the temp variable for expression }
+  addstatement(loopstatement,ctempdeletenode.create(setvar));
+end;
+
+function create_enumerator_for_in_loop(hloopvar, hloopbody, expr: tnode;
+   enumerator_get, enumerator_move: tprocdef; enumerator_current: tpropertysym): tnode;
+var
+  loopstatement, loopbodystatement: tstatementnode;
+  enumvar: ttempcreatenode;
+  loopbody, whileloopnode,
+  enum_get, enum_move, enum_current, enum_get_params: tnode;
+  propaccesslist: tpropaccesslist;
+  enumerator_is_class: boolean;
+  enumerator_destructor: tprocdef;
+begin
+  { result is a block of statements }
+  result:=internalstatements(loopstatement);
+
+  enumerator_is_class := is_class(enumerator_get.returndef);
+
+  { create a temp variable for enumerator }
+  enumvar := ctempcreatenode.create(
+    enumerator_get.returndef,
+    enumerator_get.returndef.size,
+    tt_persistent,true);
+
+  addstatement(loopstatement,enumvar);
+
+  if enumerator_get.proctypeoption=potype_operator then
+  begin
+    enum_get_params:=ccallparanode.create(expr.getcopy,nil);
+    enum_get:=ccallnode.create(enum_get_params, tprocsym(enumerator_get.procsym), nil, nil, []);
+    tcallnode(enum_get).procdefinition:=enumerator_get;
+    addsymref(enumerator_get.procsym);
+  end
+  else
+    enum_get:=ccallnode.create(nil, tprocsym(enumerator_get.procsym), enumerator_get.owner, expr.getcopy, []);
+
+  addstatement(loopstatement,
+    cassignmentnode.create(
+      ctemprefnode.create(enumvar),
+      enum_get
+    ));
+
+  loopbody:=internalstatements(loopbodystatement);
+  { for-in loop variable := enumerator.current }
+  if getpropaccesslist(enumerator_current,palt_read,propaccesslist) then
+  begin
+     case propaccesslist.firstsym^.sym.typ of
+       fieldvarsym :
+         begin
+            { generate access code }
+            enum_current:=ctemprefnode.create(enumvar);
+            propaccesslist_to_node(enum_current,enumerator_current.owner,propaccesslist);
+            include(enum_current.flags,nf_isproperty);
+         end;
+       procsym :
+         begin
+            { generate the method call }
+            enum_current:=ccallnode.create(nil,tprocsym(propaccesslist.firstsym^.sym),enumerator_current.owner,ctemprefnode.create(enumvar),[]);
+            include(enum_current.flags,nf_isproperty);
+         end
+       else
+         begin
+            enum_current:=cerrornode.create;
+            Message(type_e_mismatch);
+         end;
+    end;
+  end
+  else
+    enum_current:=cerrornode.create;
+
+  addstatement(loopbodystatement,
+      cassignmentnode.create(hloopvar, enum_current));
+
+  { add the actual statement to the loop }
+  addstatement(loopbodystatement,hloopbody);
+
+  enum_move:=ccallnode.create(nil, tprocsym(enumerator_move.procsym), enumerator_move.owner, ctemprefnode.create(enumvar), []);
+  whileloopnode:=cwhilerepeatnode.create(enum_move,loopbody,true,false);
+
+  if enumerator_is_class then
+  begin
+    { insert a try-finally and call the destructor for the enumerator in the finally section }
+    enumerator_destructor:=tobjectdef(enumerator_get.returndef).Finddestructor;
+    if assigned(enumerator_destructor) then
+    begin
+      whileloopnode:=ctryfinallynode.create(
+        whileloopnode, // try node
+        ccallnode.create(nil,tprocsym(enumerator_destructor.procsym), // finally node
+          enumerator_destructor.procsym.owner,ctemprefnode.create(enumvar),[]));
+    end;
+    { if getenumerator <> nil then do the loop }
+    whileloopnode:=cifnode.create(
+      caddnode.create(unequaln, ctemprefnode.create(enumvar), cnilnode.create),
+      whileloopnode,
+      nil
+      );
+  end;
+
+  addstatement(loopstatement, whileloopnode);
+
+  if is_object(enumerator_get.returndef) then
+  begin
+    // call the object destructor too
+    enumerator_destructor:=tobjectdef(enumerator_get.returndef).Finddestructor;
+    if assigned(enumerator_destructor) then
+    begin
+      addstatement(loopstatement,
+        ccallnode.create(nil,tprocsym(enumerator_destructor.procsym),
+            enumerator_destructor.procsym.owner,ctemprefnode.create(enumvar),[]));
+    end;
+  end;
+
+  { free the temp variable for enumerator }
+  addstatement(loopstatement,ctempdeletenode.create(enumvar));
+end;
+
+function create_for_in_loop(hloopvar, hloopbody, expr: tnode): tnode;
+var
+  pd, movenext: tprocdef;
+  current: tpropertysym;
+  storefilepos: tfileposinfo;
+begin
+  storefilepos:=current_filepos;
+  current_filepos:=hloopvar.fileinfo;
+  if expr.nodetype=typen then
+  begin
+    if (expr.resultdef.typ=enumdef) and tenumdef(expr.resultdef).has_jumps then
+    begin
+      result:=cerrornode.create;
+      hloopvar.free;
+      hloopbody.free;
+      MessagePos1(expr.fileinfo,parser_e_for_in_loop_cannot_be_used_for_the_type,expr.resultdef.typename);
+    end
+    else 
+      result:=create_type_for_in_loop(hloopvar, hloopbody, expr);
+  end
+  else
+  begin
+    { loop is made for an expression }
+    // search for operator first
+    pd:=search_enumerator_operator(expr.resultdef);
+    // if there is no operator then search for class/object enumerator method
+    if (pd=nil) and (expr.resultdef.typ=objectdef) then
+      pd:=tobjectdef(expr.resultdef).search_enumerator_get;
+    if pd<>nil then
+    begin
+      // seach movenext and current symbols
+      movenext:=tobjectdef(pd.returndef).search_enumerator_move;
+      if movenext = nil then
+      begin
+        result:=cerrornode.create;
+        hloopvar.free;
+        hloopbody.free;
+        MessagePos1(expr.fileinfo,sym_e_no_enumerator_move,pd.returndef.GetTypeName);
+      end
+      else
+      begin
+        current:=tpropertysym(tobjectdef(pd.returndef).search_enumerator_current);
+        if current = nil then
+        begin
+          result:=cerrornode.create;
+          hloopvar.free;
+          hloopbody.free;
+          MessagePos1(expr.fileinfo,sym_e_no_enumerator_current,pd.returndef.GetTypeName);
+        end
+        else
+          result:=create_enumerator_for_in_loop(hloopvar, hloopbody, expr, pd, movenext, current);
+      end;
+    end
+    else
+    begin
+      case expr.resultdef.typ of
+        stringdef: result:=create_string_for_in_loop(hloopvar, hloopbody, expr);
+        arraydef: result:=create_array_for_in_loop(hloopvar, hloopbody, expr);
+        setdef: result:=create_set_for_in_loop(hloopvar, hloopbody, expr);
+      else
+        begin
+          result:=cerrornode.create;
+          hloopvar.free;
+          hloopbody.free;
+          MessagePos1(expr.fileinfo,sym_e_no_enumerator,expr.resultdef.GetTypeName);
+        end;
+      end;
+    end;
+  end;
+  current_filepos:=storefilepos;
+end;
+
 {****************************************************************************
 {****************************************************************************
                                  TLOOPNODE
                                  TLOOPNODE
 *****************************************************************************}
 *****************************************************************************}

+ 20 - 0
compiler/nutils.pas

@@ -86,6 +86,7 @@ interface
       containing no code }
       containing no code }
     function has_no_code(n : tnode) : boolean;
     function has_no_code(n : tnode) : boolean;
 
 
+    function getpropaccesslist(propsym:tpropertysym; pap:tpropaccesslisttypes;out propaccesslist:tpropaccesslist):boolean;
     procedure propaccesslist_to_node(var p1:tnode;st:TSymtable;pl:tpropaccesslist);
     procedure propaccesslist_to_node(var p1:tnode;st:TSymtable;pl:tpropaccesslist);
     function node_to_propaccesslist(p1:tnode):tpropaccesslist;
     function node_to_propaccesslist(p1:tnode):tpropaccesslist;
 
 
@@ -926,6 +927,25 @@ implementation
       end;
       end;
 
 
 
 
+    function getpropaccesslist(propsym:tpropertysym; pap:tpropaccesslisttypes;out propaccesslist:tpropaccesslist):boolean;
+    var
+      hpropsym : tpropertysym;
+    begin
+      result:=false;
+      { find property in the overriden list }
+      hpropsym:=propsym;
+      repeat
+        propaccesslist:=hpropsym.propaccesslist[pap];
+        if not propaccesslist.empty then
+          begin
+            result:=true;
+            exit;
+          end;
+        hpropsym:=hpropsym.overridenpropsym;
+      until not assigned(hpropsym);
+    end;
+
+
     procedure propaccesslist_to_node(var p1:tnode;st:TSymtable;pl:tpropaccesslist);
     procedure propaccesslist_to_node(var p1:tnode;st:TSymtable;pl:tpropaccesslist);
       var
       var
         plist : ppropaccesslistitem;
         plist : ppropaccesslistitem;

+ 1 - 0
compiler/options.pas

@@ -2389,6 +2389,7 @@ begin
   def_system_macro('FPC_NEW_BIGENDIAN_SETS');
   def_system_macro('FPC_NEW_BIGENDIAN_SETS');
   def_system_macro('FPC_STRTOSHORTSTRINGPROC');
   def_system_macro('FPC_STRTOSHORTSTRINGPROC');
   def_system_macro('FPC_OBJFPC_EXTENDED_IF');
   def_system_macro('FPC_OBJFPC_EXTENDED_IF');
+  def_system_macro('FPC_HAS_OPERATOR_ENUMERATOR');
 {$if defined(x86) or defined(powerpc) or defined(powerpc64)}
 {$if defined(x86) or defined(powerpc) or defined(powerpc64)}
   def_system_macro('FPC_HAS_INTERNAL_ABS_LONG');
   def_system_macro('FPC_HAS_INTERNAL_ABS_LONG');
 {$endif}
 {$endif}

+ 25 - 0
compiler/pdecobj.pas

@@ -108,6 +108,31 @@ implementation
               end;
               end;
             consume(_SEMICOLON);
             consume(_SEMICOLON);
           end;
           end;
+        { parse possible enumerator modifier }
+        if try_to_consume(_ENUMERATOR) then
+          begin
+            if (token = _ID) then
+            begin
+              if pattern='CURRENT' then
+              begin
+                if oo_has_enumerator_current in current_objectdef.objectoptions then
+                  message(parser_e_only_one_enumerator_current);
+                if not p.propaccesslist[palt_read].empty then
+                begin
+                  include(current_objectdef.objectoptions,oo_has_enumerator_current);
+                  include(p.propoptions,ppo_enumerator_current);
+                end
+                else
+                  Message(parser_e_enumerator_current_is_not_valid) // property has no reader
+              end
+              else
+                Message1(parser_e_invalid_enumerator_identifier, pattern);
+              consume(token);
+            end
+            else
+              Message(parser_e_enumerator_identifier_required);
+            consume(_SEMICOLON);
+          end;
         { hint directives, these can be separated by semicolons here,
         { hint directives, these can be separated by semicolons here,
           that needs to be handled here with a loop (PFV) }
           that needs to be handled here with a loop (PFV) }
         while try_consume_hintdirective(p.symoptions) do
         while try_consume_hintdirective(p.symoptions) do

+ 46 - 4
compiler/pdecsub.pas

@@ -1055,17 +1055,22 @@ implementation
                end
                end
               else
               else
                begin
                begin
+                 { Use the dummy NOTOKEN that is also declared
+                   for the overloaded_operator[] }
+                 optoken:=NOTOKEN;
                  case token of
                  case token of
                    _CARET:
                    _CARET:
                      Message1(parser_e_overload_operator_failed,'**');
                      Message1(parser_e_overload_operator_failed,'**');
+                   _ID:
+                     if idtoken = _ENUMERATOR then
+                       optoken := _OP_ENUMERATOR
+                     else
+                       Message1(parser_e_overload_operator_failed,'');
                    _UNEQUAL:
                    _UNEQUAL:
                      Message1(parser_e_overload_operator_failed,'=');
                      Message1(parser_e_overload_operator_failed,'=');
                    else
                    else
                      Message1(parser_e_overload_operator_failed,'');
                      Message1(parser_e_overload_operator_failed,'');
                  end;
                  end;
-                 { Use the dummy NOTOKEN that is also declared
-                   for the overloaded_operator[] }
-                 optoken:=NOTOKEN;
                end;
                end;
               consume(token);
               consume(token);
               parse_proc_head(aclass,potype_operator,pd);
               parse_proc_head(aclass,potype_operator,pd);
@@ -1258,6 +1263,34 @@ begin
   tprocdef(pd).forwarddef:=false;
   tprocdef(pd).forwarddef:=false;
 end;
 end;
 
 
+procedure pd_enumerator(pd:tabstractprocdef);
+begin
+  if pd.typ<>procdef then
+    internalerror(200910250);
+  if (token = _ID) then
+  begin
+    if pattern='MOVENEXT' then
+    begin
+      if oo_has_enumerator_movenext in tprocdef(pd)._class.objectoptions then
+        message(parser_e_only_one_enumerator_movenext);
+      pd.calcparas;
+      if (pd.proctypeoption = potype_function) and is_boolean(pd.returndef) and
+         (pd.minparacount = 0) then
+      begin
+        include(tprocdef(pd)._class.objectoptions, oo_has_enumerator_movenext);
+        include(pd.procoptions,po_enumerator_movenext);
+      end
+      else
+        Message(parser_e_enumerator_movenext_is_not_valid)
+    end
+    else
+      Message1(parser_e_invalid_enumerator_identifier, pattern);
+    consume(token);
+  end
+  else
+    Message(parser_e_enumerator_identifier_required);
+end;
+
 procedure pd_virtual(pd:tabstractprocdef);
 procedure pd_virtual(pd:tabstractprocdef);
 {$ifdef WITHDMT}
 {$ifdef WITHDMT}
 var
 var
@@ -1648,7 +1681,7 @@ type
    end;
    end;
 const
 const
   {Should contain the number of procedure directives we support.}
   {Should contain the number of procedure directives we support.}
-  num_proc_directives=40;
+  num_proc_directives=41;
   proc_direcdata:array[1..num_proc_directives] of proc_dir_rec=
   proc_direcdata:array[1..num_proc_directives] of proc_dir_rec=
    (
    (
     (
     (
@@ -2023,6 +2056,15 @@ const
       { allowed for external cpp classes }
       { allowed for external cpp classes }
       mutexclpotype : [{potype_constructor,potype_destructor}];
       mutexclpotype : [{potype_constructor,potype_destructor}];
       mutexclpo     : [po_public,po_exports,po_interrupt,po_assembler,po_inline]
       mutexclpo     : [po_public,po_exports,po_interrupt,po_assembler,po_inline]
+    ),(
+      idtok:_ENUMERATOR;
+      pd_flags : [pd_interface,pd_object];
+      handler  : @pd_enumerator;
+      pocall   : pocall_none;
+      pooption : [];
+      mutexclpocall : [pocall_internproc];
+      mutexclpotype : [];
+      mutexclpo     : [po_exports,po_interrupt,po_external,po_inline]
     )
     )
    );
    );
 
 

+ 2 - 21
compiler/pexpr.pas

@@ -1001,25 +1001,6 @@ implementation
          membercall : boolean;
          membercall : boolean;
          callflags  : tcallnodeflags;
          callflags  : tcallnodeflags;
          propaccesslist : tpropaccesslist;
          propaccesslist : tpropaccesslist;
-
-         function getpropaccesslist(pap:tpropaccesslisttypes):boolean;
-         var
-           hpropsym : tpropertysym;
-         begin
-           result:=false;
-           { find property in the overriden list }
-           hpropsym:=propsym;
-           repeat
-             propaccesslist:=hpropsym.propaccesslist[pap];
-             if not propaccesslist.empty then
-               begin
-                 result:=true;
-                 exit;
-               end;
-             hpropsym:=hpropsym.overridenpropsym;
-           until not assigned(hpropsym);
-         end;
-
       begin
       begin
          { property parameters? read them only if the property really }
          { property parameters? read them only if the property really }
          { has parameters                                             }
          { has parameters                                             }
@@ -1042,7 +1023,7 @@ implementation
          { if not(afterassignment) and not(in_args) then }
          { if not(afterassignment) and not(in_args) then }
          if token=_ASSIGNMENT then
          if token=_ASSIGNMENT then
            begin
            begin
-              if getpropaccesslist(palt_write) then
+              if getpropaccesslist(propsym,palt_write,propaccesslist) then
                 begin
                 begin
                    case propaccesslist.firstsym^.sym.typ of
                    case propaccesslist.firstsym^.sym.typ of
                      procsym :
                      procsym :
@@ -1092,7 +1073,7 @@ implementation
            end
            end
          else
          else
            begin
            begin
-              if getpropaccesslist(palt_read) then
+              if getpropaccesslist(propsym,palt_read,propaccesslist) then
                 begin
                 begin
                    case propaccesslist.firstsym^.sym.typ of
                    case propaccesslist.firstsym^.sym.typ of
                      fieldvarsym :
                      fieldvarsym :

+ 3 - 1
compiler/pp.lpi

@@ -23,6 +23,7 @@
     <RunParams>
     <RunParams>
       <local>
       <local>
         <FormatVersion Value="1"/>
         <FormatVersion Value="1"/>
+        <CommandLineParams Value="-MObjFPC -Scgi -O1 -gl -vewnhi -l -FuC:\programming\mytest\fpctest\enumerators\ -Fu. -FUC:\programming\mytest\fpctest\enumerators\lib\i386-win32\ -oproject1.exe C:\programming\mytest\fpctest\enumerators\tforin1.pp"/>
         <LaunchingApplication PathPlusParams="/usr/X11R6/bin/xterm -T 'Lazarus Run Output' -e $(LazarusDir)/tools/runwait.sh $(TargetCmdLine)"/>
         <LaunchingApplication PathPlusParams="/usr/X11R6/bin/xterm -T 'Lazarus Run Output' -e $(LazarusDir)/tools/runwait.sh $(TargetCmdLine)"/>
       </local>
       </local>
     </RunParams>
     </RunParams>
@@ -43,7 +44,7 @@
     <Version Value="8"/>
     <Version Value="8"/>
     <PathDelim Value="\"/>
     <PathDelim Value="\"/>
     <Target>
     <Target>
-      <Filename Value="i386\pp"/>
+      <Filename Value="..\bin\i386-win32\pp.exe"/>
     </Target>
     </Target>
     <SearchPaths>
     <SearchPaths>
       <IncludeFiles Value="i386\"/>
       <IncludeFiles Value="i386\"/>
@@ -60,6 +61,7 @@
     <Linking>
     <Linking>
       <Debugging>
       <Debugging>
         <GenerateDebugInfo Value="True"/>
         <GenerateDebugInfo Value="True"/>
+        <UseHeaptrc Value="True"/>
       </Debugging>
       </Debugging>
     </Linking>
     </Linking>
     <Other>
     <Other>

+ 1 - 1
compiler/ppu.pas

@@ -43,7 +43,7 @@ type
 {$endif Test_Double_checksum}
 {$endif Test_Double_checksum}
 
 
 const
 const
-  CurrentPPUVersion = 100;
+  CurrentPPUVersion = 103;
 
 
 { buffer sizes }
 { buffer sizes }
   maxentrysize = 1024;
   maxentrysize = 1024;

+ 160 - 133
compiler/pstatmnt.pas

@@ -297,150 +297,177 @@ implementation
 {$endif not cpu64bitaddr}
 {$endif not cpu64bitaddr}
         end;
         end;
 
 
-      var
-         hp,
-         hloopvar,
-         hblock,
-         hto,hfrom : tnode;
-         backward : boolean;
-         loopvarsym : tabstractvarsym;
-      begin
-         { parse loop header }
-         consume(_FOR);
-
-         hloopvar:=factor(false);
-         valid_for_loopvar(hloopvar,true);
-
-         { Check loop variable }
-         loopvarsym:=nil;
-
-         { variable must be an ordinal, int64 is not allowed for 32bit targets }
-         if not(is_ordinal(hloopvar.resultdef))
-{$ifndef cpu64bitaddr}
-            or is_64bitint(hloopvar.resultdef)
-{$endif not cpu64bitaddr}
-            then
-           MessagePos(hloopvar.fileinfo,type_e_ordinal_expr_expected);
-
-         hp:=hloopvar;
-         while assigned(hp) and
-               (
-                { record/object fields and array elements are allowed }
-                { in tp7 mode only                                    }
-                (
-                 (m_tp7 in current_settings.modeswitches) and
+        function for_loop_create(hloopvar: tnode): tnode;
+        var
+           hp,
+           hblock,
+           hto,hfrom : tnode;
+           backward : boolean;
+           loopvarsym : tabstractvarsym;
+        begin
+           { Check loop variable }
+           loopvarsym:=nil;
+
+           { variable must be an ordinal, int64 is not allowed for 32bit targets }
+           if not(is_ordinal(hloopvar.resultdef))
+  {$ifndef cpu64bitaddr}
+              or is_64bitint(hloopvar.resultdef)
+  {$endif not cpu64bitaddr}
+              then
+             MessagePos(hloopvar.fileinfo,type_e_ordinal_expr_expected);
+
+           hp:=hloopvar;
+           while assigned(hp) and
                  (
                  (
-                  ((hp.nodetype=subscriptn) and
-                   ((tsubscriptnode(hp).left.resultdef.typ=recorddef) or
-                    is_object(tsubscriptnode(hp).left.resultdef))
+                  { record/object fields and array elements are allowed }
+                  { in tp7 mode only                                    }
+                  (
+                   (m_tp7 in current_settings.modeswitches) and
+                   (
+                    ((hp.nodetype=subscriptn) and
+                     ((tsubscriptnode(hp).left.resultdef.typ=recorddef) or
+                      is_object(tsubscriptnode(hp).left.resultdef))
+                    ) or
+                    { constant array index }
+                    (
+                     (hp.nodetype=vecn) and
+                     is_constintnode(tvecnode(hp).right)
+                    )
+                   )
                   ) or
                   ) or
-                  { constant array index }
+                  { equal typeconversions }
                   (
                   (
-                   (hp.nodetype=vecn) and
-                   is_constintnode(tvecnode(hp).right)
+                   (hp.nodetype=typeconvn) and
+                   (ttypeconvnode(hp).convtype=tc_equal)
                   )
                   )
-                 )
-                ) or
-                { equal typeconversions }
-                (
-                 (hp.nodetype=typeconvn) and
-                 (ttypeconvnode(hp).convtype=tc_equal)
-                )
-               ) do
-           begin
-             { Use the recordfield for loopvarsym }
-             if not assigned(loopvarsym) and
-                (hp.nodetype=subscriptn) then
-               loopvarsym:=tsubscriptnode(hp).vs;
-             hp:=tunarynode(hp).left;
-           end;
+                 ) do
+             begin
+               { Use the recordfield for loopvarsym }
+               if not assigned(loopvarsym) and
+                  (hp.nodetype=subscriptn) then
+                 loopvarsym:=tsubscriptnode(hp).vs;
+               hp:=tunarynode(hp).left;
+             end;
 
 
-         if assigned(hp) and
-            (hp.nodetype=loadn) then
-           begin
-             case tloadnode(hp).symtableentry.typ of
-               staticvarsym,
-               localvarsym,
-               paravarsym :
-                 begin
-                   { we need a simple loadn:
-                       1. The load must be in a global symtable or
-                           in the same level as the para of the current proc.
-                       2. value variables (no const,out or var)
-                       3. No threadvar, readonly or typedconst
-                   }
-                   if (
-                       (tloadnode(hp).symtable.symtablelevel=main_program_level) or
-                       (tloadnode(hp).symtable.symtablelevel=current_procinfo.procdef.parast.symtablelevel)
-                      ) and
-                      (tabstractvarsym(tloadnode(hp).symtableentry).varspez=vs_value) and
-                      ([vo_is_thread_var,vo_is_typed_const] * tabstractvarsym(tloadnode(hp).symtableentry).varoptions=[]) then
-                     begin
-                       { Assigning for-loop variable is only allowed in tp7 and macpas }
-                       if ([m_tp7,m_mac] * current_settings.modeswitches = []) then
-                         begin
-                           if not assigned(loopvarsym) then
-                             loopvarsym:=tabstractvarsym(tloadnode(hp).symtableentry);
-                           include(loopvarsym.varoptions,vo_is_loop_counter);
-                         end;
-                     end
-                   else
-                     begin
-                       { Typed const is allowed in tp7 }
-                       if not(m_tp7 in current_settings.modeswitches) or
-                          not(vo_is_typed_const in tabstractvarsym(tloadnode(hp).symtableentry).varoptions) then
-                         MessagePos(hp.fileinfo,type_e_illegal_count_var);
-                     end;
-                 end;
-               else
-                 MessagePos(hp.fileinfo,type_e_illegal_count_var);
+           if assigned(hp) and
+              (hp.nodetype=loadn) then
+             begin
+               case tloadnode(hp).symtableentry.typ of
+                 staticvarsym,
+                 localvarsym,
+                 paravarsym :
+                   begin
+                     { we need a simple loadn:
+                         1. The load must be in a global symtable or
+                             in the same level as the para of the current proc.
+                         2. value variables (no const,out or var)
+                         3. No threadvar, readonly or typedconst
+                     }
+                     if (
+                         (tloadnode(hp).symtable.symtablelevel=main_program_level) or
+                         (tloadnode(hp).symtable.symtablelevel=current_procinfo.procdef.parast.symtablelevel)
+                        ) and
+                        (tabstractvarsym(tloadnode(hp).symtableentry).varspez=vs_value) and
+                        ([vo_is_thread_var,vo_is_typed_const] * tabstractvarsym(tloadnode(hp).symtableentry).varoptions=[]) then
+                       begin
+                         { Assigning for-loop variable is only allowed in tp7 and macpas }
+                         if ([m_tp7,m_mac] * current_settings.modeswitches = []) then
+                           begin
+                             if not assigned(loopvarsym) then
+                               loopvarsym:=tabstractvarsym(tloadnode(hp).symtableentry);
+                             include(loopvarsym.varoptions,vo_is_loop_counter);
+                           end;
+                       end
+                     else
+                       begin
+                         { Typed const is allowed in tp7 }
+                         if not(m_tp7 in current_settings.modeswitches) or
+                            not(vo_is_typed_const in tabstractvarsym(tloadnode(hp).symtableentry).varoptions) then
+                           MessagePos(hp.fileinfo,type_e_illegal_count_var);
+                       end;
+                   end;
+                 else
+                   MessagePos(hp.fileinfo,type_e_illegal_count_var);
+               end;
+             end
+           else
+             MessagePos(hloopvar.fileinfo,type_e_illegal_count_var);
+
+           hfrom:=comp_expr(true);
+
+           if try_to_consume(_DOWNTO) then
+             backward:=true
+           else
+             begin
+               consume(_TO);
+               backward:=false;
              end;
              end;
-           end
-         else
-           MessagePos(hloopvar.fileinfo,type_e_illegal_count_var);
 
 
-         consume(_ASSIGNMENT);
+           hto:=comp_expr(true);
+           consume(_DO);
+
+           { Check if the constants fit in the range }
+           check_range(hfrom);
+           check_range(hto);
+
+           { first set the varstate for from and to, so
+             uses of loopvar in those expressions will also
+             trigger a warning when it is not used yet. This
+             needs to be done before the instruction block is
+             parsed to have a valid hloopvar }
+           typecheckpass(hfrom);
+           set_varstate(hfrom,vs_read,[vsf_must_be_valid]);
+           typecheckpass(hto);
+           set_varstate(hto,vs_read,[vsf_must_be_valid]);
+           typecheckpass(hloopvar);
+           { in two steps, because vs_readwritten may turn on vsf_must_be_valid }
+           { for some subnodes                                                  }
+           set_varstate(hloopvar,vs_written,[]);
+           set_varstate(hloopvar,vs_read,[vsf_must_be_valid]);
+
+           { ... now the instruction block }
+           hblock:=statement;
+
+           { variable is not used for loop counter anymore }
+           if assigned(loopvarsym) then
+             exclude(loopvarsym.varoptions,vo_is_loop_counter);
+
+           result:=cfornode.create(hloopvar,hfrom,hto,hblock,backward);
+        end;
+         
+        function for_in_loop_create(hloopvar: tnode): tnode;
+        var
+          expr: tnode;
+        begin
+          expr := comp_expr(true);
 
 
-         hfrom:=comp_expr(true);
+          consume(_DO);
 
 
-         if try_to_consume(_DOWNTO) then
-           backward:=true
-         else
-           begin
-             consume(_TO);
-             backward:=false;
-           end;
+          set_varstate(hloopvar,vs_written,[]);
+          set_varstate(hloopvar,vs_read,[vsf_must_be_valid]);
+
+          result := create_for_in_loop(hloopvar, statement, expr);
+ 
+          expr.free;
+        end;
+
+      var
+         hloopvar: tnode;
+      begin
+         { parse loop header }
+         consume(_FOR);
+
+         hloopvar:=factor(false);
+         valid_for_loopvar(hloopvar,true);
 
 
-         hto:=comp_expr(true);
-         consume(_DO);
 
 
-         { Check if the constants fit in the range }
-         check_range(hfrom);
-         check_range(hto);
-
-         { first set the varstate for from and to, so
-           uses of loopvar in those expressions will also
-           trigger a warning when it is not used yet. This
-           needs to be done before the instruction block is
-           parsed to have a valid hloopvar }
-         typecheckpass(hfrom);
-         set_varstate(hfrom,vs_read,[vsf_must_be_valid]);
-         typecheckpass(hto);
-         set_varstate(hto,vs_read,[vsf_must_be_valid]);
-         typecheckpass(hloopvar);
-         { in two steps, because vs_readwritten may turn on vsf_must_be_valid }
-         { for some subnodes                                                  }
-         set_varstate(hloopvar,vs_written,[]);
-         set_varstate(hloopvar,vs_read,[vsf_must_be_valid]);
-
-         { ... now the instruction block }
-         hblock:=statement;
-
-         { variable is not used for loop counter anymore }
-         if assigned(loopvarsym) then
-           exclude(loopvarsym.varoptions,vo_is_loop_counter);
-
-         result:=cfornode.create(hloopvar,hfrom,hto,hblock,backward);
+         if try_to_consume(_ASSIGNMENT) then
+           result:=for_loop_create(hloopvar)
+         else
+         if try_to_consume(_IN) then
+           result:=for_in_loop_create(hloopvar)
+         else
+           consume(_ASSIGNMENT); // fail
       end;
       end;
 
 
 
 

+ 10 - 3
compiler/symconst.pas

@@ -274,7 +274,11 @@ type
     po_kylixlocal,
     po_kylixlocal,
     po_dispid,
     po_dispid,
     { weakly linked (i.e., may or may not exist at run time) }
     { weakly linked (i.e., may or may not exist at run time) }
-    po_weakexternal
+    po_weakexternal,
+    { Objective-C method }
+    po_objc,
+    { enumerator support }
+    po_enumerator_movenext
   );
   );
   tprocoptions=set of tprocoption;
   tprocoptions=set of tprocoption;
 
 
@@ -314,7 +318,9 @@ type
     oo_has_msgint,
     oo_has_msgint,
     oo_can_have_published,{ the class has rtti, i.e. you can publish properties }
     oo_can_have_published,{ the class has rtti, i.e. you can publish properties }
     oo_has_default_property,
     oo_has_default_property,
-    oo_has_valid_guid
+    oo_has_valid_guid,
+    oo_has_enumerator_movenext,
+    oo_has_enumerator_current
   );
   );
   tobjectoptions=set of tobjectoption;
   tobjectoptions=set of tobjectoption;
 
 
@@ -335,7 +341,8 @@ type
     ppo_defaultproperty,
     ppo_defaultproperty,
     ppo_stored,
     ppo_stored,
     ppo_hasparameters,
     ppo_hasparameters,
-    ppo_implements
+    ppo_implements,
+    ppo_enumerator_current
   );
   );
   tpropertyoptions=set of tpropertyoption;
   tpropertyoptions=set of tpropertyoption;
 
 

+ 117 - 0
compiler/symdef.pas

@@ -296,6 +296,10 @@ interface
           function FindDestructor : tprocdef;
           function FindDestructor : tprocdef;
           function implements_any_interfaces: boolean;
           function implements_any_interfaces: boolean;
           procedure reset; override;
           procedure reset; override;
+          { enumerator support }
+          function search_enumerator_get: tprocdef;
+          function search_enumerator_move: tprocdef;
+          function search_enumerator_current: tsym;
           { WPO }
           { WPO }
           procedure register_created_object_type;override;
           procedure register_created_object_type;override;
           procedure register_maybe_created_object_type;
           procedure register_maybe_created_object_type;
@@ -4268,6 +4272,119 @@ implementation
         classref_created_in_current_module:=false;
         classref_created_in_current_module:=false;
       end;
       end;
 
 
+    function tobjectdef.search_enumerator_get: tprocdef;
+     var
+        objdef : tobjectdef;
+        sym : tsym;
+        i : integer;
+        pd : tprocdef;
+        hashedid : THashedIDString;
+     begin
+        result:=nil;
+        objdef:=self;
+        hashedid.id:='GETENUMERATOR';
+        while assigned(objdef) do
+          begin
+            sym:=tsym(objdef.symtable.FindWithHash(hashedid));
+            if assigned(sym) and (sym.typ=procsym) then
+              begin
+                for i := 0 to Tprocsym(sym).ProcdefList.Count - 1 do
+                begin
+                  pd := tprocdef(Tprocsym(sym).ProcdefList[i]);
+                  if (pd.proctypeoption = potype_function) and
+                     is_class_or_interface_or_object(pd.returndef) and
+                     (pd.visibility >= vis_public) then
+                  begin
+                    result:=pd;
+                    exit;
+                  end;
+                end;
+              end;
+            objdef:=objdef.childof;
+          end;
+      end;
+
+    function tobjectdef.search_enumerator_move: tprocdef;
+     var
+        objdef : tobjectdef;
+        sym : tsym;
+        i : integer;
+        pd : tprocdef;
+        hashedid : THashedIDString;
+     begin
+        result:=nil;
+        objdef:=self;
+        // first search for po_enumerator_movenext method modifier
+        // then search for public function MoveNext: Boolean
+        hashedid.id:='MOVENEXT';
+        while assigned(objdef) do
+          begin
+            for i:=0 to objdef.symtable.SymList.Count-1 do
+              begin
+                sym:=TSym(objdef.symtable.SymList[i]);
+                if (sym.typ=procsym) then
+                begin
+                  pd:=Tprocsym(sym).find_procdef_byoptions([po_enumerator_movenext]);
+                  if assigned(pd) then
+                    begin
+                      result:=pd;
+                      exit;
+                    end;
+                end;
+              end;
+            sym:=tsym(objdef.symtable.FindWithHash(hashedid));
+            if assigned(sym) and (sym.typ=procsym) then
+              begin
+                for i := 0 to Tprocsym(sym).ProcdefList.Count - 1 do
+                begin
+                  pd := tprocdef(Tprocsym(sym).ProcdefList[i]);
+                  if (pd.proctypeoption = potype_function) and
+                     is_boolean(pd.returndef) and
+                     (pd.minparacount = 0) and
+                     (pd.visibility >= vis_public) then
+                  begin
+                    result:=pd;
+                    exit;
+                  end;
+                end;
+              end;
+            objdef:=objdef.childof;
+          end;
+      end;
+
+    function tobjectdef.search_enumerator_current: tsym;
+     var
+        objdef : tobjectdef;
+        sym: tsym;
+        i: integer;
+        hashedid : THashedIDString;
+     begin
+        result:=nil;
+        objdef:=self;
+        hashedid.id:='CURRENT';
+        // first search for ppo_enumerator_current property modifier
+        // then search for public property Current
+        while assigned(objdef) do
+          begin
+            for i:=0 to objdef.symtable.SymList.Count-1 do
+              begin
+                sym:=TSym(objdef.symtable.SymList[i]);
+                if (sym.typ=propertysym) and (ppo_enumerator_current in tpropertysym(sym).propoptions) then
+                begin
+                  result:=sym;
+                  exit;
+                end;
+              end;
+            sym:=tsym(objdef.symtable.FindWithHash(hashedid));
+            if assigned(sym) and (sym.typ=propertysym) and
+               (sym.visibility >= vis_public) and not tpropertysym(sym).propaccesslist[palt_read].empty then
+              begin
+                result:=sym;
+                exit;
+              end;
+            objdef:=objdef.childof;
+          end;
+      end;
 
 
     procedure tobjectdef.register_created_classref_type;
     procedure tobjectdef.register_created_classref_type;
       begin
       begin

+ 80 - 0
compiler/symsym.pas

@@ -79,6 +79,8 @@ interface
           constructor create;
           constructor create;
        end;
        end;
 
 
+       { tprocsym }
+
        tprocsym = class(tstoredsym)
        tprocsym = class(tstoredsym)
        protected
        protected
           FProcdefList   : TFPObjectList;
           FProcdefList   : TFPObjectList;
@@ -97,8 +99,10 @@ interface
           procedure deref;override;
           procedure deref;override;
           function find_procdef_bytype(pt:Tproctypeoption):Tprocdef;
           function find_procdef_bytype(pt:Tproctypeoption):Tprocdef;
           function find_procdef_bypara(para:TFPObjectList;retdef:tdef;cpoptions:tcompare_paras_options):Tprocdef;
           function find_procdef_bypara(para:TFPObjectList;retdef:tdef;cpoptions:tcompare_paras_options):Tprocdef;
+          function find_procdef_byoptions(ops:tprocoptions): Tprocdef;
           function find_procdef_byprocvardef(d:Tprocvardef):Tprocdef;
           function find_procdef_byprocvardef(d:Tprocvardef):Tprocdef;
           function find_procdef_assignment_operator(fromdef,todef:tdef;var besteq:tequaltype):Tprocdef;
           function find_procdef_assignment_operator(fromdef,todef:tdef;var besteq:tequaltype):Tprocdef;
+          function find_procdef_enumerator_operator(typedef:tdef;var besteq:tequaltype):Tprocdef;
           property ProcdefList:TFPObjectList read FProcdefList;
           property ProcdefList:TFPObjectList read FProcdefList;
        end;
        end;
 
 
@@ -649,6 +653,22 @@ implementation
           end;
           end;
       end;
       end;
 
 
+    function tprocsym.find_procdef_byoptions(ops: tprocoptions): Tprocdef;
+      var
+        i  : longint;
+        pd : tprocdef;
+      begin
+        result:=nil;
+        for i:=0 to ProcdefList.Count-1 do
+          begin
+            pd:=tprocdef(ProcdefList[i]);
+            if ops * pd.procoptions = ops then
+              begin
+                result:=pd;
+                exit;
+              end;
+          end;
+      end;
 
 
     function Tprocsym.Find_procdef_byprocvardef(d:Tprocvardef):Tprocdef;
     function Tprocsym.Find_procdef_byprocvardef(d:Tprocvardef):Tprocdef;
       var
       var
@@ -751,6 +771,66 @@ implementation
         result:=bestpd;
         result:=bestpd;
       end;
       end;
 
 
+      function Tprocsym.find_procdef_enumerator_operator(typedef:tdef;var besteq:tequaltype):Tprocdef;
+      var
+        paraidx, realparamcount,
+        i, j : longint;
+        bestpd,
+        hpd,
+        pd : tprocdef;
+        convtyp : tconverttype;
+        eq      : tequaltype;
+      begin
+        { This function will return the pprocdef of pprocsym that
+          is the best match for procvardef. When there are multiple
+          matches it returns nil.}
+        result:=nil;
+        bestpd:=nil;
+        besteq:=te_incompatible;
+        for i:=0 to ProcdefList.Count-1 do
+          begin
+            pd:=tprocdef(ProcdefList[i]);
+            paraidx:=0;
+            { ignore vs_hidden parameters }
+            while (paraidx<pd.paras.count) and
+                  assigned(pd.paras[paraidx]) and
+                  (vo_is_hidden_para in tparavarsym(pd.paras[paraidx]).varoptions) do
+              inc(paraidx);
+            realparamcount:=0;
+            for j := 0 to pd.paras.Count-1 do
+              if assigned(pd.paras[j]) and not (vo_is_hidden_para in tparavarsym(pd.paras[j]).varoptions) then
+                inc(realparamcount);
+            if (paraidx<pd.paras.count) and
+               assigned(pd.paras[paraidx]) and
+               (realparamcount = 1) and
+               is_class_or_interface_or_object(pd.returndef)  then
+              begin
+                eq:=compare_defs_ext(typedef,tparavarsym(pd.paras[paraidx]).vardef,nothingn,convtyp,hpd,[]);
+
+                { alias? if yes, only l1 choice,
+                  if you mess with this code, check tw4093 }
+                if (eq=te_exact) and
+                   (typedef<>tparavarsym(pd.paras[paraidx]).vardef) and
+                   ((df_unique in typedef.defoptions) or
+                   (df_unique in tparavarsym(pd.paras[paraidx]).vardef.defoptions)) then
+                  eq:=te_convert_l1;
+
+                if eq=te_exact then
+                  begin
+                    besteq:=eq;
+                    result:=pd;
+                    exit;
+                  end;
+                if eq>besteq then
+                  begin
+                    bestpd:=pd;
+                    besteq:=eq;
+                  end;
+              end;
+          end;
+        result:=bestpd;
+      end;
+
 
 
 {****************************************************************************
 {****************************************************************************
                                   TERRORSYM
                                   TERRORSYM

+ 40 - 2
compiler/symtable.pas

@@ -201,6 +201,7 @@ interface
     function  search_system_type(const s: TIDString): ttypesym;
     function  search_system_type(const s: TIDString): ttypesym;
     function  search_class_member(pd : tobjectdef;const s : string):tsym;
     function  search_class_member(pd : tobjectdef;const s : string):tsym;
     function  search_assignment_operator(from_def,to_def:Tdef):Tprocdef;
     function  search_assignment_operator(from_def,to_def:Tdef):Tprocdef;
+    function  search_enumerator_operator(type_def:Tdef):Tprocdef;
     {Looks for macro s (must be given in upper case) in the macrosymbolstack, }
     {Looks for macro s (must be given in upper case) in the macrosymbolstack, }
     {and returns it if found. Returns nil otherwise.}
     {and returns it if found. Returns nil otherwise.}
     function  search_macro(const s : string):tsym;
     function  search_macro(const s : string):tsym;
@@ -254,7 +255,7 @@ interface
           'sym_diff','starstar',
           'sym_diff','starstar',
           'as','is','in','or',
           'as','is','in','or',
           'and','div','mod','not','shl','shr','xor',
           'and','div','mod','not','shl','shr','xor',
-          'assign');
+          'assign','enumerator');
 
 
 
 
 
 
@@ -1897,6 +1898,44 @@ implementation
       end;
       end;
 
 
 
 
+    function search_enumerator_operator(type_def:Tdef): Tprocdef;
+      var
+        sym : Tprocsym;
+        hashedid : THashedIDString;
+        curreq,
+        besteq : tequaltype;
+        currpd,
+        bestpd : tprocdef;
+        stackitem : psymtablestackitem;
+      begin
+        hashedid.id:='enumerator';
+        besteq:=te_incompatible;
+        bestpd:=nil;
+        stackitem:=symtablestack.stack;
+        while assigned(stackitem) do
+          begin
+            sym:=Tprocsym(stackitem^.symtable.FindWithHash(hashedid));
+            if sym<>nil then
+              begin
+                if sym.typ<>procsym then
+                  internalerror(200910241);
+                { if the source type is an alias then this is only the second choice,
+                  if you mess with this code, check tw4093 }
+                currpd:=sym.find_procdef_enumerator_operator(type_def,curreq);
+                if curreq>besteq then
+                  begin
+                    besteq:=curreq;
+                    bestpd:=currpd;
+                    if (besteq=te_exact) then
+                      break;
+                  end;
+              end;
+            stackitem:=stackitem^.next;
+          end;
+        result:=bestpd;
+    end;
+
+
     function search_system_type(const s: TIDString): ttypesym;
     function search_system_type(const s: TIDString): ttypesym;
       var
       var
         sym : tsym;
         sym : tsym;
@@ -1929,7 +1968,6 @@ implementation
         search_class_member:=nil;
         search_class_member:=nil;
       end;
       end;
 
 
-
     function search_macro(const s : string):tsym;
     function search_macro(const s : string):tsym;
       var
       var
         stackitem  : psymtablestackitem;
         stackitem  : psymtablestackitem;

+ 5 - 1
compiler/tokens.pas

@@ -53,6 +53,7 @@ type
     _OP_SHR,
     _OP_SHR,
     _OP_XOR,
     _OP_XOR,
     _ASSIGNMENT,
     _ASSIGNMENT,
+    _OP_ENUMERATOR,
     { special chars }
     { special chars }
     _CARET,
     _CARET,
     _UNEQUAL,
     _UNEQUAL,
@@ -230,6 +231,7 @@ type
     _WRITEONLY,
     _WRITEONLY,
     _DEPRECATED,
     _DEPRECATED,
     _DESTRUCTOR,
     _DESTRUCTOR,
+    _ENUMERATOR,
     _IMPLEMENTS,
     _IMPLEMENTS,
     _INTERNPROC,
     _INTERNPROC,
     _OLDFPCCALL,
     _OLDFPCCALL,
@@ -258,7 +260,7 @@ const
   { last operator which can be overloaded, the first_overloaded should
   { last operator which can be overloaded, the first_overloaded should
     be declared directly after NOTOKEN }
     be declared directly after NOTOKEN }
   first_overloaded = succ(NOTOKEN);
   first_overloaded = succ(NOTOKEN);
-  last_overloaded  = _ASSIGNMENT;
+  last_overloaded  = _OP_ENUMERATOR;
 
 
 type
 type
   tokenrec=record
   tokenrec=record
@@ -305,6 +307,7 @@ const
       (str:'shr'           ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:'shr'           ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:'xor'           ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:'xor'           ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:':='            ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:':='            ;special:true ;keyword:m_none;op:NOTOKEN),
+      (str:'enumerator'    ;special:true ;keyword:m_none;op:NOTOKEN),
     { Special chars }
     { Special chars }
       (str:'^'             ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:'^'             ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:'<>'            ;special:true ;keyword:m_none;op:NOTOKEN),
       (str:'<>'            ;special:true ;keyword:m_none;op:NOTOKEN),
@@ -482,6 +485,7 @@ const
       (str:'WRITEONLY'     ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'WRITEONLY'     ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'DEPRECATED'    ;special:false;keyword:m_all;op:NOTOKEN),
       (str:'DEPRECATED'    ;special:false;keyword:m_all;op:NOTOKEN),
       (str:'DESTRUCTOR'    ;special:false;keyword:m_all;op:NOTOKEN),
       (str:'DESTRUCTOR'    ;special:false;keyword:m_all;op:NOTOKEN),
+      (str:'ENUMERATOR'    ;special:false;keyword:m_none;op:_OP_ENUMERATOR),
       (str:'IMPLEMENTS'    ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'IMPLEMENTS'    ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'INTERNPROC'    ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'INTERNPROC'    ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'OLDFPCCALL'    ;special:false;keyword:m_none;op:NOTOKEN),
       (str:'OLDFPCCALL'    ;special:false;keyword:m_none;op:NOTOKEN),

+ 12 - 4
compiler/utils/ppudump.pp

@@ -1128,7 +1128,9 @@ type
     po_kylixlocal,
     po_kylixlocal,
     po_dispid,
     po_dispid,
     { weakly linked (i.e., may or may not exist at run time) }
     { weakly linked (i.e., may or may not exist at run time) }
-    po_weakexternal
+    po_weakexternal,
+    po_objc,
+    po_enumerator_movenext
   );
   );
   tprocoptions=set of tprocoption;
   tprocoptions=set of tprocoption;
 
 
@@ -1211,7 +1213,9 @@ const
      (mask:po_has_importname;  str:'HasImportName'),
      (mask:po_has_importname;  str:'HasImportName'),
      (mask:po_kylixlocal;      str:'KylixLocal'),
      (mask:po_kylixlocal;      str:'KylixLocal'),
      (mask:po_dispid;          str:'DispId'),
      (mask:po_dispid;          str:'DispId'),
-     (mask:po_weakexternal;    str:'WeakExternal')
+     (mask:po_weakexternal;    str:'WeakExternal'),
+     (mask:po_objc;            str:'ObjC'),
+     (mask:po_enumerator_movenext; str:'EnumeratorMoveNext')
   );
   );
 var
 var
   proctypeoption  : tproctypeoption;
   proctypeoption  : tproctypeoption;
@@ -1372,7 +1376,9 @@ type
     oo_has_msgint,
     oo_has_msgint,
     oo_can_have_published,{ the class has rtti, i.e. you can publish properties }
     oo_can_have_published,{ the class has rtti, i.e. you can publish properties }
     oo_has_default_property,
     oo_has_default_property,
-    oo_has_valid_guid
+    oo_has_valid_guid,
+    oo_has_enumerator_movenext,
+    oo_has_enumerator_current
   );
   );
   tobjectoptions=set of tobjectoption;
   tobjectoptions=set of tobjectoption;
   tsymopt=record
   tsymopt=record
@@ -1394,7 +1400,9 @@ const
      (mask:oo_has_msgint;         str:'HasMsgInt'),
      (mask:oo_has_msgint;         str:'HasMsgInt'),
      (mask:oo_can_have_published; str:'CanHavePublished'),
      (mask:oo_can_have_published; str:'CanHavePublished'),
      (mask:oo_has_default_property;str:'HasDefaultProperty'),
      (mask:oo_has_default_property;str:'HasDefaultProperty'),
-     (mask:oo_has_valid_guid;     str:'HasValidGUID')
+     (mask:oo_has_valid_guid;     str:'HasValidGUID'),
+     (mask:oo_has_enumerator_movenext; str:'HasEnumeratorMoveNext'),
+     (mask:oo_has_enumerator_current;  str:'HasEnumeratorCurrent')
   );
   );
 var
 var
   symoptions : tobjectoptions;
   symoptions : tobjectoptions;

+ 12 - 0
rtl/inc/objpash.inc

@@ -234,6 +234,18 @@
        end;
        end;
        {$M-}
        {$M-}
 
 
+       { enumerator support }
+       IEnumerator = interface(IInterface)
+         function GetCurrent: TObject;
+         function MoveNext: Boolean;
+         procedure Reset;
+         property Current: TObject read GetCurrent;
+       end;
+
+       IEnumerable = interface(IInterface)
+         function GetEnumerator: IEnumerator;
+       end;
+
        { for native dispinterface support }
        { for native dispinterface support }
        IDispatch = interface(IUnknown)
        IDispatch = interface(IUnknown)
           ['{00020400-0000-0000-C000-000000000046}']
           ['{00020400-0000-0000-C000-000000000046}']

+ 78 - 0
rtl/objpas/classes/classesh.inc

@@ -166,6 +166,18 @@ type
 {$IFNDEF FPC_TESTGENERICS}
 {$IFNDEF FPC_TESTGENERICS}
 
 
   TListAssignOp = (laCopy, laAnd, laOr, laXor, laSrcUnique, laDestUnique);
   TListAssignOp = (laCopy, laAnd, laOr, laXor, laSrcUnique, laDestUnique);
+  TFPList = class;
+
+  TFPListEnumerator = class
+  private
+    FList: TFPList;
+    FPosition: Integer;
+  public
+    constructor Create(AList: TFPList);
+    function GetCurrent: Pointer;
+    function MoveNext: Boolean;
+    property Current: Pointer read GetCurrent;
+  end;
 
 
   TFPList = class(TObject)
   TFPList = class(TObject)
   private
   private
@@ -197,6 +209,7 @@ type
     function Expand: TFPList; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
     function Expand: TFPList; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
     function Extract(Item: Pointer): Pointer;
     function Extract(Item: Pointer): Pointer;
     function First: Pointer;
     function First: Pointer;
+    function GetEnumerator: TFPListEnumerator;
     function IndexOf(Item: Pointer): Integer;
     function IndexOf(Item: Pointer): Integer;
     procedure Insert(Index: Integer; Item: Pointer); {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
     procedure Insert(Index: Integer; Item: Pointer); {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
     function Last: Pointer;
     function Last: Pointer;
@@ -228,8 +241,20 @@ type
 {$endif}
 {$endif}
 
 
 { TList class}
 { TList class}
+
   TListNotification = (lnAdded, lnExtracted, lnDeleted);
   TListNotification = (lnAdded, lnExtracted, lnDeleted);
+  TList = class;
 
 
+  TListEnumerator = class
+  private
+    FList: TList;
+    FPosition: Integer;
+  public
+    constructor Create(AList: TList);
+    function GetCurrent: Pointer;
+    function MoveNext: Boolean;
+    property Current: Pointer read GetCurrent;
+  end;
 
 
   TList = class(TObject)
   TList = class(TObject)
   private
   private
@@ -264,6 +289,7 @@ type
     function Expand: TList;
     function Expand: TList;
     function Extract(item: Pointer): Pointer;
     function Extract(item: Pointer): Pointer;
     function First: Pointer;
     function First: Pointer;
+    function GetEnumerator: TListEnumerator;
     function IndexOf(Item: Pointer): Integer;
     function IndexOf(Item: Pointer): Integer;
     procedure Insert(Index: Integer; Item: Pointer);
     procedure Insert(Index: Integer; Item: Pointer);
     function Last: Pointer;
     function Last: Pointer;
@@ -424,6 +450,17 @@ type
     property DisplayName: string read GetDisplayName write SetDisplayName;
     property DisplayName: string read GetDisplayName write SetDisplayName;
   end;
   end;
 
 
+  TCollectionEnumerator = class
+  private
+    FCollection: TCollection;
+    FPosition: Integer;
+  public
+    constructor Create(ACollection: TCollection);
+    function GetCurrent: TCollectionItem;
+    function MoveNext: Boolean;
+    property Current: TCollectionItem read GetCurrent;
+  end;
+
   TCollectionItemClass = class of TCollectionItem;
   TCollectionItemClass = class of TCollectionItem;
   TCollectionNotification = (cnAdded, cnExtracting, cnDeleting);
   TCollectionNotification = (cnAdded, cnExtracting, cnDeleting);
   TCollectionSortCompare = function (Item1, Item2: TCollectionItem): Integer;
   TCollectionSortCompare = function (Item1, Item2: TCollectionItem): Integer;
@@ -463,6 +500,7 @@ type
     procedure Clear;
     procedure Clear;
     procedure EndUpdate; virtual;
     procedure EndUpdate; virtual;
     procedure Delete(Index: Integer);
     procedure Delete(Index: Integer);
+    function GetEnumerator: TCollectionEnumerator;
     function GetNamePath: string; override;
     function GetNamePath: string; override;
     function Insert(Index: Integer): TCollectionItem;
     function Insert(Index: Integer): TCollectionItem;
     function FindItemID(ID: Integer): TCollectionItem;
     function FindItemID(ID: Integer): TCollectionItem;
@@ -492,6 +530,19 @@ type
     procedure ReleaseStrings;
     procedure ReleaseStrings;
   end;
   end;
 
 
+{ TStringsEnumerator class }
+
+  TStringsEnumerator = class
+  private
+    FStrings: TStrings;
+    FPosition: Integer;
+  public
+    constructor Create(AStrings: TStrings);
+    function GetCurrent: String;
+    function MoveNext: Boolean;
+    property Current: String read GetCurrent;
+  end;
+
 { TStrings class }
 { TStrings class }
 
 
   TStrings = class(TPersistent)
   TStrings = class(TPersistent)
@@ -551,6 +602,7 @@ type
     procedure EndUpdate;
     procedure EndUpdate;
     function Equals(TheStrings: TStrings): Boolean;
     function Equals(TheStrings: TStrings): Boolean;
     procedure Exchange(Index1, Index2: Integer); virtual;
     procedure Exchange(Index1, Index2: Integer); virtual;
+    function GetEnumerator: TStringsEnumerator;
     function GetText: PChar; virtual;
     function GetText: PChar; virtual;
     function IndexOf(const S: string): Integer; virtual;
     function IndexOf(const S: string): Integer; virtual;
     function IndexOfName(const Name: string): Integer; virtual;
     function IndexOfName(const Name: string): Integer; virtual;
@@ -1501,6 +1553,17 @@ type
     procedure Notification(AnObject: TPersistent; Operation: TOperation);
     procedure Notification(AnObject: TPersistent; Operation: TOperation);
   end;
   end;
 
 
+  TComponentEnumerator = class
+  private
+    FComponent: TComponent;
+    FPosition: Integer;
+  public
+    constructor Create(AComponent: TComponent);
+    function GetCurrent: TComponent;
+    function MoveNext: Boolean;
+    property Current: TComponent read GetCurrent;
+  end;
+
   TBasicAction = class;
   TBasicAction = class;
 
 
   { TComponent }
   { TComponent }
@@ -1585,6 +1648,7 @@ type
     procedure FreeNotification(AComponent: TComponent);
     procedure FreeNotification(AComponent: TComponent);
     procedure RemoveFreeNotification(AComponent: TComponent);
     procedure RemoveFreeNotification(AComponent: TComponent);
     procedure FreeOnRelease;
     procedure FreeOnRelease;
+    function GetEnumerator: TComponentEnumerator;
     function GetNamePath: string; override;
     function GetNamePath: string; override;
     function GetParentComponent: TComponent; dynamic;
     function GetParentComponent: TComponent; dynamic;
     function HasParent: Boolean; dynamic;
     function HasParent: Boolean; dynamic;
@@ -1692,6 +1756,19 @@ type
     property Items[index : Integer] : IUnknown read Get write Put;default;
     property Items[index : Integer] : IUnknown read Get write Put;default;
   end;
   end;
 
 
+  TInterfaceList = class;
+
+  TInterfaceListEnumerator = class
+  private
+    FList: TInterfaceList;
+    FPosition: Integer;
+  public
+    constructor Create(AList: TInterfaceList);
+    function GetCurrent: IUnknown;
+    function MoveNext: Boolean;
+    property Current: IUnknown read GetCurrent;
+  end;
+
   TInterfaceList = class(TInterfacedObject,IInterfaceList)
   TInterfaceList = class(TInterfacedObject,IInterfaceList)
   private
   private
     FList : TThreadList;
     FList : TThreadList;
@@ -1710,6 +1787,7 @@ type
     procedure Delete(index : Integer);
     procedure Delete(index : Integer);
     procedure Exchange(index1,index2 : Integer);
     procedure Exchange(index1,index2 : Integer);
     function First : IUnknown;
     function First : IUnknown;
+    function GetEnumerator: TInterfaceListEnumerator;
     function IndexOf(item : IUnknown) : Integer;
     function IndexOf(item : IUnknown) : Integer;
     function Add(item : IUnknown) : Integer;
     function Add(item : IUnknown) : Integer;
     procedure Insert(i : Integer;item : IUnknown);
     procedure Insert(i : Integer;item : IUnknown);

+ 29 - 0
rtl/objpas/classes/collect.inc

@@ -117,6 +117,29 @@ begin
   Inherited Destroy;
   Inherited Destroy;
 end;
 end;
 
 
+{****************************************************************************}
+{*                          TCollectionEnumerator                           *}
+{****************************************************************************}
+
+constructor TCollectionEnumerator.Create(ACollection: TCollection);
+begin
+  inherited Create;
+  FCollection := ACollection;
+  FPosition := -1;
+end;
+
+function TCollectionEnumerator.GetCurrent: TCollectionItem;
+begin
+  Result := FCollection.Items[FPosition];
+end;
+
+function TCollectionEnumerator.MoveNext: Boolean;
+begin
+  Inc(FPosition);
+  Result := FPosition < FCollection.Count;
+end;
+
+
 {****************************************************************************}
 {****************************************************************************}
 {*                             TCollection                                  *}
 {*                             TCollection                                  *}
 {****************************************************************************}
 {****************************************************************************}
@@ -218,6 +241,12 @@ begin
 end;
 end;
 
 
 
 
+function TCollection.GetEnumerator: TCollectionEnumerator;
+begin
+  Result := TCollectionEnumerator.Create(Self);
+end;
+
+
 function TCollection.GetNamePath: string;
 function TCollection.GetNamePath: string;
 var o : TObject;
 var o : TObject;
 begin
 begin

+ 29 - 0
rtl/objpas/classes/compon.inc

@@ -11,6 +11,29 @@
 
 
  **********************************************************************}
  **********************************************************************}
 
 
+{****************************************************************************}
+{*                        TComponentEnumerator                              *}
+{****************************************************************************}
+
+constructor TComponentEnumerator.Create(AComponent: TComponent);
+begin
+  inherited Create;
+  FComponent := AComponent;
+  FPosition := -1;
+end;
+
+function TComponentEnumerator.GetCurrent: TComponent;
+begin
+  Result := FComponent.Components[FPosition];
+end;
+
+function TComponentEnumerator.MoveNext: Boolean;
+begin
+  Inc(FPosition);
+  Result := FPosition < FComponent.ComponentCount;
+end;
+
+
 {****************************************************************************}
 {****************************************************************************}
 {*                             TComponent                                   *}
 {*                             TComponent                                   *}
 {****************************************************************************}
 {****************************************************************************}
@@ -213,6 +236,12 @@ begin
 end;
 end;
 
 
 
 
+Function  TComponent.GetEnumerator: TComponentEnumerator;
+
+begin
+  Result:=TComponentEnumerator.Create(Self);
+end;
+
 Function  TComponent.GetNamePath: string;
 Function  TComponent.GetNamePath: string;
 
 
 begin
 begin

+ 29 - 0
rtl/objpas/classes/intf.inc

@@ -10,6 +10,29 @@
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 
  **********************************************************************}
  **********************************************************************}
+{ TInerfaceListEnumerator }
+
+    constructor TInterfaceListEnumerator.Create(AList: TInterfaceList);
+      begin
+        inherited create;
+        FList:=AList;
+        FPosition:=-1;
+      end;
+
+
+    function TInterfaceListEnumerator.GetCurrent: IUnknown;
+      begin
+        Result:=FList[FPosition];
+      end;
+
+
+    function TInterfaceListEnumerator.MoveNext: Boolean;
+      begin
+        Inc(FPosition);
+        Result:=FPosition<FList.Count;
+      end;
+
+{ TInterfaceList }
 
 
     constructor TInterfaceList.Create;
     constructor TInterfaceList.Create;
       begin
       begin
@@ -142,6 +165,12 @@
       end;
       end;
 
 
 
 
+    function TInterfaceList.GetEnumerator: TInterfaceListEnumerator;
+      begin
+        result:=TInterfaceListEnumerator.Create(Self)
+      end;
+
+
     function TInterfaceList.IndexOf(item : IUnknown) : Integer;
     function TInterfaceList.IndexOf(item : IUnknown) : Integer;
       begin
       begin
         FList.Locklist;
         FList.Locklist;

+ 52 - 2
rtl/objpas/classes/lists.inc

@@ -13,6 +13,28 @@
 
 
 {$if defined(VER2_0) or not defined(FPC_TESTGENERICS)}
 {$if defined(VER2_0) or not defined(FPC_TESTGENERICS)}
 
 
+{****************************************************************************}
+{*                           TFPListEnumerator                              *}
+{****************************************************************************}
+
+constructor TFPListEnumerator.Create(AList: TFPList);
+begin
+  inherited Create;
+  FList := AList;
+  FPosition := -1;
+end;
+
+function TFPListEnumerator.GetCurrent: Pointer;
+begin
+  Result := FList[FPosition];
+end;
+
+function TFPListEnumerator.MoveNext: Boolean;
+begin
+  Inc(FPosition);
+  Result := FPosition < FList.Count;
+end;
+
 {****************************************************************************}
 {****************************************************************************}
 {*                           TFPList                                        *}
 {*                           TFPList                                        *}
 {****************************************************************************}
 {****************************************************************************}
@@ -169,6 +191,11 @@ begin
     Result := Items[0];
     Result := Items[0];
 end;
 end;
 
 
+function TFPList.GetEnumerator: TFPListEnumerator;
+begin
+  Result := TFPListEnumerator.Create(Self);
+end;
+
 function TFPList.IndexOf(Item: Pointer): Integer;
 function TFPList.IndexOf(Item: Pointer): Integer;
 begin
 begin
   Result := 0;
   Result := 0;
@@ -480,7 +507,27 @@ end;
 
 
 {$endif}
 {$endif}
 
 
+{****************************************************************************}
+{*                TListEnumerator                                           *}
+{****************************************************************************}
+
+constructor TListEnumerator.Create(AList: TList);
+begin
+  inherited Create;
+  FList := AList;
+  FPosition := -1;
+end;
+
+function TListEnumerator.GetCurrent: Pointer;
+begin
+  Result := FList[FPosition];
+end;
 
 
+function TListEnumerator.MoveNext: Boolean;
+begin
+  Inc(FPosition);
+  Result := FPosition < FList.Count;
+end;
 
 
 {****************************************************************************}
 {****************************************************************************}
 {*                TList                                                     *}
 {*                TList                                                     *}
@@ -491,8 +538,6 @@ end;
     FList: TFPList;
     FList: TFPList;
 }
 }
 
 
-
-
 function TList.Get(Index: Integer): Pointer;
 function TList.Get(Index: Integer): Pointer;
 begin
 begin
   Result := FList.Get(Index);
   Result := FList.Get(Index);
@@ -616,6 +661,11 @@ begin
   Result := FList.First;
   Result := FList.First;
 end;
 end;
 
 
+function TList.GetEnumerator: TListEnumerator;
+begin
+  Result := TListEnumerator.Create(Self);
+end;
+
 function TList.IndexOf(Item: Pointer): Integer;
 function TList.IndexOf(Item: Pointer): Integer;
 begin
 begin
   Result := FList.IndexOf(Item);
   Result := FList.IndexOf(Item);

+ 28 - 0
rtl/objpas/classes/stringl.inc

@@ -10,6 +10,29 @@
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 
  **********************************************************************}
  **********************************************************************}
+
+{****************************************************************************}
+{*                        TStringsEnumerator                                *}
+{****************************************************************************}
+
+constructor TStringsEnumerator.Create(AStrings: TStrings);
+begin
+  inherited Create;
+  FStrings := AStrings;
+  FPosition := -1;
+end;
+
+function TStringsEnumerator.GetCurrent: String;
+begin
+  Result := FStrings[FPosition];
+end;
+
+function TStringsEnumerator.MoveNext: Boolean;
+begin
+  Inc(FPosition);
+  Result := FPosition < FStrings.Count;
+end;
+
 {****************************************************************************}
 {****************************************************************************}
 {*                             TStrings                                     *}
 {*                             TStrings                                     *}
 {****************************************************************************}
 {****************************************************************************}
@@ -666,6 +689,11 @@ begin
 end;
 end;
 
 
 
 
+function TStrings.GetEnumerator: TStringsEnumerator;
+begin
+  Result:=TStringsEnumerator.Create(Self);
+end;
+
 
 
 Function TStrings.GetText: PChar;
 Function TStrings.GetText: PChar;
 begin
 begin

+ 166 - 0
tests/test/tenumerators1.pp

@@ -0,0 +1,166 @@
+program tenumerators1;
+
+{$ifdef fpc}
+{$mode objfpc}{$H+}
+{$endif}
+{$apptype console}
+uses
+  Classes;
+
+{$ifndef fpc}
+type
+  PtrInt = integer;
+{$endif}
+
+{$ifdef fpc}
+procedure CheckFPListEnumerator;
+var
+  Item: Pointer;
+  List: TFPList;
+  Enumerator: TFPListEnumerator;
+begin
+  // check TFPList enumerator
+  List := TFPList.Create;
+  List.Add(Pointer(1));
+  List.Add(Pointer(2));
+  List.Add(Pointer(3));
+
+  Enumerator := List.GetEnumerator;
+  while Enumerator.MoveNext do
+  begin
+    Item := Enumerator.Current;
+    WriteLn(PtrInt(Item));
+  end;
+  Enumerator.Free;
+  List.Free;
+end;
+{$endif}
+
+procedure CheckListEnumerator;
+var
+  Item: Pointer;
+  List: TList;
+  Enumerator: TListEnumerator;
+begin
+  // check TList enumerator
+  List := TList.Create;
+  List.Add(Pointer(1));
+  List.Add(Pointer(2));
+  List.Add(Pointer(3));
+
+  Enumerator := List.GetEnumerator;
+  while Enumerator.MoveNext do
+  begin
+    Item := Enumerator.Current;
+    WriteLn(PtrInt(Item));
+  end;
+  Enumerator.Free;
+  List.Free;
+end;
+
+procedure CheckCollectionEnumerator;
+var
+  Item: TCollectionItem;
+  Collection: TCollection;
+  Enumerator: TCollectionEnumerator;
+begin
+  // check TCollection enumerator
+  Collection := TCollection.Create(TCollectionItem);
+  Collection.Add;
+  Collection.Add;
+  Collection.Add;
+
+  Enumerator := Collection.GetEnumerator;
+  while Enumerator.MoveNext do
+  begin
+    Item := Enumerator.Current;
+    WriteLn(PtrInt(Item));
+  end;
+  Enumerator.Free;
+  Collection.Free;
+end;
+
+procedure CheckStringsEnumerator;
+var
+  Item: String;
+  Strings: TStrings;
+  Enumerator: TStringsEnumerator;
+begin
+  // check TStrings enumerator
+  Strings := TStringList.Create;
+  Strings.Add('1');
+  Strings.Add('2');
+  Strings.Add('3');
+
+  Enumerator := Strings.GetEnumerator;
+  while Enumerator.MoveNext do
+  begin
+    Item := Enumerator.Current;
+    WriteLn(Item);
+  end;
+  Enumerator.Free;
+  Strings.Free;
+end;
+
+procedure CheckComponentEnumerator;
+var
+  Item: TComponent;
+  Component: TComponent;
+  Enumerator: TComponentEnumerator;
+begin
+  // check TComponent enumerator
+  Component := TComponent.Create(nil);
+  TComponent.Create(Component);
+  TComponent.Create(Component);
+  TComponent.Create(Component);
+
+  Enumerator := Component.GetEnumerator;
+  while Enumerator.MoveNext do
+  begin
+    Item := Enumerator.Current;
+    WriteLn(PtrInt(Item));
+  end;
+  Enumerator.Free;
+  Component.Free;
+end;
+
+procedure CheckInterfaceListEnumerator;
+var
+  Item: IUnknown;
+  List: TInterfaceList;
+  Enumerator: TInterfaceListEnumerator;
+begin
+  // check TInterfaceList enumerator
+  List := TInterfaceList.Create;
+  Item := TInterfacedObject.Create;
+  List.Add(Item);
+  Item := TInterfacedObject.Create;
+  List.Add(Item);
+  Item := TInterfacedObject.Create;
+  List.Add(Item);
+
+  Enumerator := List.GetEnumerator;
+  while Enumerator.MoveNext do
+  begin
+    Item := Enumerator.Current;
+    WriteLn(PtrInt(Item));
+  end;
+  Enumerator.Free;
+  Item := nil;
+  List.Free;
+end;
+
+begin
+{$ifdef fpc}
+  WriteLn('Testing FPC');
+  CheckFPListEnumerator;
+{$else}
+  WriteLn('Testing Delphi');
+{$endif}
+  CheckListEnumerator;
+  CheckCollectionEnumerator;
+  CheckStringsEnumerator;
+  CheckComponentEnumerator;
+  CheckInterfaceListEnumerator;
+end.
+

+ 71 - 0
tests/test/tforin1.pp

@@ -0,0 +1,71 @@
+program tforin1;
+
+// test for-in loop for the basic types: Enumeration, Range, Array, String and Set
+
+{$mode objfpc}{$H+}
+{$apptype console}
+uses
+  Classes, typinfo;
+
+type
+  TColor = (clRed, clGreen, clBlue);
+
+procedure LoopTypes;
+type
+  IntRange = 0..9;
+var
+  c: TColor;
+  i: integer;
+begin
+  // check loop in range
+  for i in IntRange do
+    writeln(i);
+
+  // check loop in enum
+  for c in TColor do
+    writeln(GetEnumName(TypeInfo(c), ord(c)));
+end;
+
+procedure LoopString(s: string);
+var
+  c: char;
+begin
+  // check loop in string
+  for c in s do
+    write(c);
+  WriteLn;
+end;
+
+procedure LoopArray(a: array of integer);
+var
+  i: integer;
+begin
+  // check loop in array
+  for i in a do
+    write(i);
+  WriteLn;
+end;
+
+procedure LoopSet;
+const
+  s = [clRed, clBlue];
+var
+  c: TColor;
+begin
+  // check loop in set
+  for c in s do
+    writeln(GetEnumName(TypeInfo(c), ord(c)));
+end;
+
+var
+  a: array[0..2] of integer;
+begin
+  LoopTypes;
+  LoopString('test');
+  a[0]:=0;
+  a[1]:=1;
+  a[2]:=2;
+  LoopArray(a);
+  LoopSet;
+end.
+

+ 29 - 0
tests/test/tforin10.pp

@@ -0,0 +1,29 @@
+{ %FAIL}
+
+// test that it is imposible to use non-valid enumerator operator
+
+program tforin10;
+
+{$mode objfpc}{$H+}
+{$apptype console}
+
+type
+  TSomeClass = class
+  end;
+
+  TSomeClassEnumerator = class
+  end;
+
+operator enumerator(s1, s2: TSomeClass): TSomeClassEnumerator;
+begin
+  Result := nil;
+end;
+
+var
+  s: TSomeClass;
+  c: char;
+begin
+  for c in s do
+    write(c);
+end.
+

+ 17 - 0
tests/test/tforin11.pp

@@ -0,0 +1,17 @@
+{ %FAIL}
+
+// test that wrong type using for the for-in loop fails
+
+program tforin11;
+
+{$mode objfpc}{$H+}
+{$apptype console}
+
+var
+  s: String;
+  b: byte;
+begin
+  for b in s do
+    write(b);
+end.
+

+ 10 - 0
tests/test/tforin12.pp

@@ -0,0 +1,10 @@
+{mode objfpc}
+{$apptype console}
+type T = array [1..3] of Char;
+var
+  a: array [1..3] of T = ('asd', 'sdf', 'ddf');
+  s: T;
+begin
+  for s in a do 
+    Writeln(s);
+end.

+ 8 - 0
tests/test/tforin13.pp

@@ -0,0 +1,8 @@
+{mode objfpc}
+{$apptype console}
+var
+  ch: Char;
+begin
+  for ch in ['a'..'c', '0'..'3', '_'] do 
+    Writeln(ch);
+end.

+ 24 - 0
tests/test/tforin14.pp

@@ -0,0 +1,24 @@
+{mode objfpc}
+{$apptype console}
+type
+  T = array [1..3] of Integer;
+
+
+procedure P(a: array of T);
+var
+  r: T;
+  i: Integer;
+begin
+  for r in a do 
+  begin
+    for i in r do Write(i, ' ');
+    Writeln;
+  end;
+end;
+
+const
+  r1: T = (1,2,9);
+  r2: T = (3,4,5);
+begin
+  P([r1, r2]);
+end.

+ 39 - 0
tests/test/tforin15.pp

@@ -0,0 +1,39 @@
+{$mode objfpc}
+{$apptype console}
+
+type
+  T = class
+    stop: boolean;
+    F: Integer;
+    function MoveNext: Boolean;
+    property Current: Integer read F;
+  end;
+
+Twice = type Integer;
+
+function T.MoveNext: Boolean;
+begin
+  Result := not stop;
+  stop := true;
+end;
+
+operator enumerator(a: Integer): T;
+begin
+  Result := T.Create;
+  Result.F := a;
+  Result.stop := false;
+end;
+
+operator enumerator(a: Twice): T;
+begin
+  Result := T.Create;
+  Result.F := a * 2;
+  Result.stop := false;
+end;
+
+var
+  i: Integer;
+begin
+  for i in Twice(1) do
+    Writeln(i);
+end.

+ 7 - 0
tests/test/tforin16.pp

@@ -0,0 +1,7 @@
+{mode objfpc}
+{$apptype console}
+const S = 'abc';
+var ch: Char;
+begin
+  for ch in S do Writeln(ch);
+end.

+ 6 - 0
tests/test/tforin17.pp

@@ -0,0 +1,6 @@
+{mode objfpc}
+{$apptype console}
+var ch: Char;
+begin
+  for ch in 'abc' do Writeln(ch);
+end.

+ 6 - 0
tests/test/tforin18.pp

@@ -0,0 +1,6 @@
+{ %FAIL}
+{$mode objfpc}
+{$apptype console}
+begin
+  for ch in S do Writeln(ch);
+end.

+ 7 - 0
tests/test/tforin19.pp

@@ -0,0 +1,7 @@
+{$mode objfpc}
+{$apptype console}
+var
+  ch: Char;
+begin
+  for ch in [] do Writeln(ch);
+end.

+ 84 - 0
tests/test/tforin2.pp

@@ -0,0 +1,84 @@
+program tforin2;
+
+// test operator Enumerator for the string type and built-in into RTL TStrings enumerator
+
+{$mode objfpc}{$H+}
+{$apptype console}
+uses
+  Classes;
+
+type
+  { TStringEnumerator }
+
+  TStringEnumerator = class // reverse enumerator
+  private
+    FString: String;
+    FIndex: Integer;
+    function GetCurrent: Char; inline;
+  public
+    constructor Create(AString: String);
+    function MoveNext: Boolean;
+    property Current: Char read GetCurrent;
+  end;
+
+{ TStringEnumerator }
+
+function TStringEnumerator.GetCurrent: Char;
+begin
+  Result := FString[FIndex];
+end;
+
+constructor TStringEnumerator.Create(AString: String);
+begin
+  inherited Create;
+  FString := AString;
+  FIndex := Length(FString) + 1;
+end;
+
+function TStringEnumerator.MoveNext: Boolean;
+begin
+  dec(FIndex);
+  Result := FIndex > 0;
+end;
+
+// define an operator for the string type
+operator enumerator (const s: string): TStringEnumerator;inline;
+begin
+  Result := TStringEnumerator.Create(s);
+end;
+
+procedure LoopString(s: string);
+
+  function getstring(s: string): string;
+  begin
+    result:=s;
+  end;
+
+var
+  c: char;
+begin
+  // check loop in string. output is 'tset' for the string 'test' :)
+  for c in getstring(s) do
+    write(c);
+  WriteLn;
+end;
+
+procedure LoopClass;
+var
+  L: TStringList;
+  S: String;
+begin
+  L := TStringList.Create;
+  L.Add('1');
+  L.Add('2');
+  L.Add('3');
+  for S in L do
+    WriteLn(S);
+  L.Free;
+end;
+
+begin
+  LoopString('test');
+  LoopClass;
+end.
+

+ 9 - 0
tests/test/tforin20.pp

@@ -0,0 +1,9 @@
+{ %FAIL}
+{$mode objfpc}
+{$apptype console}
+type T = (a1, b1=5);
+var
+  ch: T;
+begin
+  for ch in T do Writeln(ch);
+end.

+ 14 - 0
tests/test/tforin21.pp

@@ -0,0 +1,14 @@
+{ %FAIL}
+{$mode objfpc}
+{$apptype console}
+
+operator enumerator(a: Integer): Integer;
+begin
+  Result := 0;
+end;
+
+var
+  i: Integer;
+begin
+  for i in 1 do Writeln(i);
+end.

+ 27 - 0
tests/test/tforin22.pp

@@ -0,0 +1,27 @@
+{ %FAIL}
+{$mode objfpc}
+{$apptype console}
+
+type 
+  T = class
+    F: Integer;
+    function MoveNext(a: Integer): Boolean;
+    property Current: Integer read F;
+  end;
+
+function T.MoveNext(a: Integer): Boolean; 
+begin 
+  Result := true; 
+end;
+
+operator enumerator(a: Integer): T;
+begin
+  Result := T.Create;
+  Result.F := a;
+end;
+
+var
+  i: Integer;
+begin
+  for i in 1 do Writeln(i);
+end.

+ 24 - 0
tests/test/tforin23.pp

@@ -0,0 +1,24 @@
+{$mode objfpc}
+{$apptype console}
+
+// test enumerating multidimensional arrays with and without conversion
+
+type
+  TSingleDimArray = array[0..1] of integer;
+  TMultyDimArray = array[0..1] of TSingleDimArray;
+var
+  MultyDimArray: TMultyDimArray;
+  a: TSingleDimArray;
+  i: integer;
+begin
+  MultyDimArray[0,0]:=1;
+  MultyDimArray[0,1]:=2;
+  MultyDimArray[1,0]:=3;
+  MultyDimArray[1,1]:=4;
+  for a in MultyDimArray do
+    for i in a do
+      WriteLn(i);
+
+  for i in MultyDimArray do
+    Writeln(i);
+end.

+ 48 - 0
tests/test/tforin3.pp

@@ -0,0 +1,48 @@
+program tforin3;
+
+// check for-in loop if GetEnumerator returns nil
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+
+  { TListEnumerator }
+
+  TListEnumerator = class
+  private
+    FCurrent: String;
+  public
+    function MoveNext: Boolean;
+    property Current: String read FCurrent;
+  end;
+
+  TMyList = class
+  public
+    function GetEnumerator: TListEnumerator;
+  end;
+
+{ TListEnumerator }
+
+function TListEnumerator.MoveNext: Boolean;
+begin
+  Result := True;
+end;
+
+{ TMyList }
+
+function TMyList.GetEnumerator: TListEnumerator;
+begin
+  Result := nil;
+end;
+
+var
+  S: String;
+  L: TMyList;
+begin
+  L := TMyList.Create;
+  for S in L do
+    ;
+  L.Free;
+end.
+

+ 59 - 0
tests/test/tforin4.pp

@@ -0,0 +1,59 @@
+program tforin4;
+
+// test that for-in loop allows array modifications inside the loop body
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+  TMyArray = array of integer;
+
+function return_array: TMyArray;
+begin
+  SetLength(result, 3);
+  result[0] := 1;
+  result[1] := 2;
+  result[2] := 3;
+end;
+
+procedure TestArrayReturn;
+var
+  i: integer;
+begin
+  for i in return_array do
+    WriteLn(i);
+end;
+
+procedure TestDynamicArray;
+var
+  i: integer;
+  a: array of integer;
+begin
+  setlength(a, 3);
+  a[0]:=1;
+  a[1]:=2;
+  a[2]:=3;
+  for i in a do
+  begin
+    WriteLn(i);
+    a[2] := -1;
+  end;
+end;
+
+procedure TestOpenArray(a: array of integer);
+var
+  i: integer;
+begin
+  for i in a do
+  begin
+    WriteLn(i);
+    a[2] := -1;
+  end;
+end;
+
+begin
+  TestOpenArray([1,2,3]);
+  TestDynamicArray;
+  TestArrayReturn;
+end.
+

+ 50 - 0
tests/test/tforin5.pp

@@ -0,0 +1,50 @@
+program tforin5;
+
+// test operator Enumerator support for classes
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+  TMyList = class
+  end;
+
+  { TMyListEnumerator }
+
+  TMyListEnumerator = class
+  private
+    FCurrent: Integer;
+  public
+    constructor Create;
+    function MoveNext: Boolean;
+    property Current: Integer read FCurrent;
+  end;
+
+{ TMyListEnumerator }
+
+constructor TMyListEnumerator.Create;
+begin
+  FCurrent := 0;
+end;
+
+function TMyListEnumerator.MoveNext: Boolean;
+begin
+  inc(FCurrent);
+  Result := FCurrent <= 3;
+end;
+
+operator enumerator (AList: TMyList): TMyListEnumerator;
+begin
+  Result := TMyListEnumerator.Create;
+end;
+
+var
+  List: TMyList;
+  i: integer;
+begin
+  List := TMyList.Create;
+  for i in List do
+    WriteLn(i);
+  List.Free;
+end.
+

+ 58 - 0
tests/test/tforin6.pp

@@ -0,0 +1,58 @@
+program tforin6;
+
+// test Object enumerator implementation
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+  { TMyListEnumerator }
+
+  TMyListEnumerator = object
+  private
+    FCurrent: Integer;
+  public
+    constructor Create;
+    destructor Destroy;
+    function MoveNext: Boolean;
+    property Current: Integer read FCurrent;
+  end;
+
+  TMyList = class
+  end;
+
+{ TMyListEnumerator }
+
+constructor TMyListEnumerator.Create;
+begin
+  WriteLn('create');
+  FCurrent := 0;
+end;
+
+destructor TMyListEnumerator.Destroy;
+begin
+  WriteLn('destroy');
+  inherited;
+end;
+
+function TMyListEnumerator.MoveNext: Boolean;
+begin
+  inc(FCurrent);
+  Result := FCurrent <= 3;
+end;
+
+operator enumerator (AList: TMyList): TMyListEnumerator;
+begin
+  Result.Create;
+end;
+
+var
+  List: TMyList;
+  i: integer;
+begin
+  List := TMyList.Create;
+  for i in List do
+    WriteLn(i);
+  List.Free;
+end.
+

+ 56 - 0
tests/test/tforin7.pp

@@ -0,0 +1,56 @@
+program tforin7;
+
+// test 'enumerator MoveNext' and 'enumrator Current' directives
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+  { TMyListEnumerator }
+
+  TMyListEnumerator = object
+  private
+    FCurrent: Integer;
+  public
+    constructor Create;
+    destructor Destroy;
+    function StepNext: Boolean; enumerator MoveNext;
+    property Value: Integer read FCurrent; enumerator Current;
+  end;
+
+  TMyList = class
+  end;
+
+{ TMyListEnumerator }
+
+constructor TMyListEnumerator.Create;
+begin
+  FCurrent := 0;
+end;
+
+destructor TMyListEnumerator.Destroy;
+begin
+  inherited;
+end;
+
+function TMyListEnumerator.StepNext: Boolean;
+begin
+  inc(FCurrent);
+  Result := FCurrent <= 3;
+end;
+
+operator enumerator (AList: TMyList): TMyListEnumerator;
+begin
+  Result.Create;
+end;
+
+var
+  List: TMyList;
+  i: integer;
+begin
+  List := TMyList.Create;
+  for i in List do
+    WriteLn(i);
+  List.Free;
+end.
+

+ 61 - 0
tests/test/tforin8.pp

@@ -0,0 +1,61 @@
+program tformin8;
+
+// Test IEnumerable and IEnumerator in the for-in loop
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+  { TMyListEnumerator }
+
+  TMyListEnumerator = class(TInterfacedObject, IEnumerator)
+  private
+    FCurrent: Pointer;
+    function GetCurrent: TObject;
+  public
+    function MoveNext: Boolean;
+    procedure Reset;
+    property Current: TObject read GetCurrent;
+  end;
+
+  TMyList = class(TInterfacedObject, IEnumerable)
+  public
+    function GetEnumerator: IEnumerator;
+  end;
+
+{ TMyListEnumerator }
+
+
+function TMyListEnumerator.GetCurrent: TObject;
+begin
+  Result := TObject(FCurrent);
+end;
+
+function TMyListEnumerator.MoveNext: Boolean;
+begin
+  inc(PByte(FCurrent));
+  Result := FCurrent <= Pointer(3);
+end;
+
+procedure TMyListEnumerator.Reset;
+begin
+  FCurrent := nil;
+end;
+
+{ TMyList }
+
+function TMyList.GetEnumerator: IEnumerator;
+begin
+  Result := TMyListEnumerator.Create;
+end;
+
+var
+  List: IEnumerable;
+  i: TObject;
+begin
+  List := TMyList.Create;
+  for i in List do
+    WriteLn(Integer(i));
+  List := nil;
+end.
+

+ 68 - 0
tests/test/tforin9.pp

@@ -0,0 +1,68 @@
+program tforin9;
+
+// Test interface with 'enumerator MoveNext', 'enumerator Current' directives
+
+{$mode objfpc}{$H+}
+{$APPTYPE CONSOLE}
+
+type
+
+  { IMyIterator }
+
+  IMyIterator = interface
+    function GetValue: TObject;
+    function StepForward: Boolean; enumerator MoveNext;
+    property Value: TObject read GetValue; enumerator Current;
+  end;
+  { TMyListEnumerator }
+
+  TMyListEnumerator = class(TInterfacedObject, IMyIterator)
+  private
+    FValue: Pointer;
+    function GetValue: TObject;
+  public
+    function StepForward: Boolean;
+    property Value: TObject read GetValue;
+  end;
+
+  TMyList = class
+  public
+    function GetIterator: IMyIterator;
+  end;
+
+operator Enumerator(AList: TMyList): IMyIterator;
+begin
+  Result := AList.GetIterator;
+end;
+
+{ TMyListEnumerator }
+
+
+function TMyListEnumerator.GetValue: TObject;
+begin
+  Result := TObject(FValue);
+end;
+
+function TMyListEnumerator.StepForward: Boolean;
+begin
+  inc(PByte(FValue));
+  Result := FValue <= Pointer(3);
+end;
+
+{ TMyList }
+
+function TMyList.GetIterator: IMyIterator;
+begin
+  Result := TMyListEnumerator.Create;
+end;
+
+var
+  List: TMyList;
+  i: TObject;
+begin
+  List := TMyList.Create;
+  for i in List do
+    WriteLn(PtrInt(i));
+  List.Free;
+end.
+

Some files were not shown because too many files changed in this diff