compiler/libec: (#205) Fixed integer promotions to follow the C standard (6.3.1.1)
[sdk] / compiler / libec / src / pass15.ec
1 import "ecdefs"
2
3 // UNTIL IMPLEMENTED IN GRAMMAR
4 #define ACCESS_CLASSDATA(_class, baseClass) \
5    (_class ? ((void *)(((char *)_class.data) + baseClass.offsetClass)) : null)
6
7 #define YYLTYPE Location
8 #include "grammar.h"
9
10 extern OldList * ast;
11 extern int returnCode;
12 extern Expression parsedExpression;
13 extern bool yydebug;
14 public void SetYydebug(bool b) { yydebug = b; }
15 extern bool echoOn;
16
17 void resetScanner();
18
19 // TODO: Reset this to 0 on reinitialization
20 int propWatcherID;
21
22 int expression_yyparse();
23 static Statement curCompound;
24 External curExternal, afterExternal;
25 static Type curSwitchType;
26 static Class currentClass;
27 Class thisClass;
28 public void SetThisClass(Class c) { thisClass = c; } public Class GetThisClass() { return thisClass; }
29 static char * thisNameSpace;
30 /*static */Class containerClass;
31 bool thisClassParams = true;
32
33 uint internalValueCounter;
34
35 #ifdef _DEBUG
36 Time findSymbolTotalTime;
37 #endif
38
39 // WARNING: PrintExpression CONCATENATES to string. Please initialize.
40 /*static */public void PrintExpression(Expression exp, char * string)
41 {
42    //if(inCompiler)
43    {
44       TempFile f { };
45       int count;
46       bool backOutputLineNumbers = outputLineNumbers;
47       outputLineNumbers = false;
48
49       if(exp)
50          OutputExpression(exp, f);
51       f.Seek(0, start);
52       count = strlen(string);
53       count += f.Read(string + count, 1, 1023);
54       string[count] = '\0';
55       delete f;
56
57       outputLineNumbers = backOutputLineNumbers;
58    }
59 }
60
61 Type ProcessTemplateParameterType(TemplateParameter param)
62 {
63    if(param && param.type == TemplateParameterType::type && (param.dataType || param.dataTypeString))
64    {
65       // TOFIX: Will need to free this Type
66       if(!param.baseType)
67       {
68          if(param.dataTypeString)
69             param.baseType = ProcessTypeString(param.dataTypeString, false);
70          else
71             param.baseType = ProcessType(param.dataType.specifiers, param.dataType.decl);
72       }
73       return param.baseType;
74    }
75    return null;
76 }
77
78 bool NeedCast(Type type1, Type type2)
79 {
80    if(!type1 || !type2 || type1.keepCast || type2.keepCast) return true;
81
82    if(type1.kind == templateType && type2.kind == int64Type && type2.passAsTemplate == false)
83    {
84       return false;
85    }
86
87    if(type1.kind == type2.kind && type1.isLong == type2.isLong)
88    {
89       switch(type1.kind)
90       {
91          case _BoolType:
92          case charType:
93          case shortType:
94          case intType:
95          case int64Type:
96          case intPtrType:
97          case intSizeType:
98             if(type1.passAsTemplate && !type2.passAsTemplate)
99                return true;
100             return type1.isSigned != type2.isSigned;
101          case classType:
102             return type1._class != type2._class;
103          case pointerType:
104             return (type1.type && type2.type && type1.type.constant != type2.type.constant) || NeedCast(type1.type, type2.type);
105          default:
106             return true; //false; ????
107       }
108    }
109    return true;
110 }
111
112 static void ReplaceClassMembers(Expression exp, Class _class)
113 {
114    if(exp.type == identifierExp && exp.identifier)
115    {
116       Identifier id = exp.identifier;
117       Context ctx;
118       Symbol symbol = null;
119       if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
120       {
121          // First, check if the identifier is declared inside the function
122          for(ctx = curContext; ctx != topContext.parent && !symbol; ctx = ctx.parent)
123          {
124             symbol = (Symbol)ctx.symbols.FindString(id.string);
125             if(symbol) break;
126          }
127       }
128
129       // If it is not, check if it is a member of the _class
130       if(!symbol && ((!id._class || (id._class.name && !strcmp(id._class.name, "property"))) || (id.classSym && eClass_IsDerived(_class, id.classSym.registered))))
131       {
132          Property prop = eClass_FindProperty(_class, id.string, privateModule);
133          Method method = null;
134          DataMember member = null;
135          ClassProperty classProp = null;
136          if(!prop)
137          {
138             method = eClass_FindMethod(_class, id.string, privateModule);
139          }
140          if(!prop && !method)
141             member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
142          if(!prop && !method && !member)
143          {
144             classProp = eClass_FindClassProperty(_class, id.string);
145          }
146          if(prop || method || member || classProp)
147          {
148             // Replace by this.[member]
149             exp.type = memberExp;
150             exp.member.member = id;
151             exp.member.memberType = unresolvedMember;
152             exp.member.exp = QMkExpId("this");
153             //exp.member.exp.loc = exp.loc;
154             exp.addedThis = true;
155          }
156          else if(_class && _class.templateParams.first)
157          {
158             Class sClass;
159             for(sClass = _class; sClass; sClass = sClass.base)
160             {
161                if(sClass.templateParams.first)
162                {
163                   ClassTemplateParameter param;
164                   for(param = sClass.templateParams.first; param; param = param.next)
165                   {
166                      if(param.type == expression && !strcmp(param.name, id.string))
167                      {
168                         Expression argExp = GetTemplateArgExpByName(param.name, _class, TemplateParameterType::expression);
169
170                         if(argExp)
171                         {
172                            Declarator decl;
173                            OldList * specs = MkList();
174
175                            FreeIdentifier(exp.member.member);
176
177                            ProcessExpressionType(argExp);
178
179                            decl = SpecDeclFromString(param.dataTypeString, specs, null);
180
181                            exp.expType = ProcessType(specs, decl);
182
183                            // *[expType] *[argExp]
184                            exp.type = bracketsExp;
185                            exp.list = MkListOne(MkExpOp(null, '*',
186                               MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpOp(null, '&', argExp))));
187                         }
188                      }
189                   }
190                }
191             }
192          }
193       }
194    }
195 }
196
197 ////////////////////////////////////////////////////////////////////////
198 // PRINTING ////////////////////////////////////////////////////////////
199 ////////////////////////////////////////////////////////////////////////
200
201 public char * PrintInt(int64 result)
202 {
203    char temp[100];
204    if(result > MAXINT)
205       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
206    else
207       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
208    if(result > MAXINT || result < MININT)
209       strcat(temp, "LL");
210    return CopyString(temp);
211 }
212
213 public char * PrintUInt(uint64 result)
214 {
215    char temp[100];
216    if(result > MAXDWORD)
217       sprintf(temp, FORMAT64HEXLL /*"0x%I64X"*/, result);
218    else if(result > MAXINT)
219       sprintf(temp, FORMAT64HEX /*"0x%I64X"*/, result);
220    else
221       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
222    return CopyString(temp);
223 }
224
225 public char *  PrintInt64(int64 result)
226 {
227    char temp[100];
228    if(result > MAXINT || result < MININT)
229       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
230    else
231       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
232    return CopyString(temp);
233 }
234
235 public char * PrintUInt64(uint64 result)
236 {
237    char temp[100];
238    if(result > MAXDWORD)
239       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
240    else if(result > MAXINT)
241       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
242    else
243       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
244    return CopyString(temp);
245 }
246
247 public char * PrintHexUInt(uint64 result)
248 {
249    char temp[100];
250    if(result > MAXDWORD)
251       sprintf(temp, FORMAT64HEX /*"0x%I64xLL"*/, result);
252    else
253       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
254    if(result > MAXDWORD)
255       strcat(temp, "LL");
256    return CopyString(temp);
257 }
258
259 public char * PrintHexUInt64(uint64 result)
260 {
261    char temp[100];
262    if(result > MAXDWORD)
263       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
264    else
265       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
266    return CopyString(temp);
267 }
268
269 public char * PrintShort(short result)
270 {
271    char temp[100];
272    sprintf(temp, "%d", (unsigned short)result);
273    return CopyString(temp);
274 }
275
276 public char * PrintUShort(unsigned short result)
277 {
278    char temp[100];
279    if(result > 32767)
280       sprintf(temp, "0x%X", (int)result);
281    else
282       sprintf(temp, "%d", (int)result);
283    return CopyString(temp);
284 }
285
286 public char * PrintChar(char result)
287 {
288    char temp[100];
289    if(result > 0 && isprint(result))
290       sprintf(temp, "'%c'", result);
291    else if(result < 0)
292       sprintf(temp, "%d", (int)result);
293    else
294       //sprintf(temp, "%#X", result);
295       sprintf(temp, "0x%X", (unsigned char)result);
296    return CopyString(temp);
297 }
298
299 public char * PrintUChar(unsigned char result)
300 {
301    char temp[100];
302    sprintf(temp, "0x%X", result);
303    return CopyString(temp);
304 }
305
306 public char * PrintFloat(float result)
307 {
308    char temp[350];
309    if(result.isInf)
310    {
311       if(result.signBit)
312          strcpy(temp, "-inf");
313       else
314          strcpy(temp, "inf");
315    }
316    else if(result.isNan)
317    {
318       if(result.signBit)
319          strcpy(temp, "-nan");
320       else
321          strcpy(temp, "nan");
322    }
323    else
324       sprintf(temp, "%.16ff", result);
325    return CopyString(temp);
326 }
327
328 public char * PrintDouble(double result)
329 {
330    char temp[350];
331    if(result.isInf)
332    {
333       if(result.signBit)
334          strcpy(temp, "-inf");
335       else
336          strcpy(temp, "inf");
337    }
338    else if(result.isNan)
339    {
340       if(result.signBit)
341          strcpy(temp, "-nan");
342       else
343          strcpy(temp, "nan");
344    }
345    else
346       sprintf(temp, "%.16f", result);
347    return CopyString(temp);
348 }
349
350 ////////////////////////////////////////////////////////////////////////
351 ////////////////////////////////////////////////////////////////////////
352
353 //public Operand GetOperand(Expression exp);
354
355 #define GETVALUE(name, t) \
356    public bool GetOp##name(Operand op2, t * value2) \
357    {                                                        \
358       if(op2.kind == intType && op2.type.isSigned) *value2 = (t) op2.i; \
359       else if(op2.kind == intType) *value2 = (t) op2.ui;                 \
360       else if(op2.kind == int64Type && op2.type.isSigned) *value2 = (t) op2.i64; \
361       else if(op2.kind == int64Type) *value2 = (t) op2.ui64;                 \
362       else if(op2.kind == intSizeType && op2.type.isSigned) *value2 = (t) op2.i64; \
363       else if(op2.kind == intSizeType) *value2 = (t) op2.ui64; \
364       else if(op2.kind == intPtrType && op2.type.isSigned) *value2 = (t) op2.i64; \
365       else if(op2.kind == intPtrType) *value2 = (t) op2.ui64;                 \
366       else if(op2.kind == shortType && op2.type.isSigned) *value2 = (t) op2.s;   \
367       else if(op2.kind == shortType) *value2 = (t) op2.us;                        \
368       else if(op2.kind == charType && op2.type.isSigned) *value2 = (t) op2.c;    \
369       else if(op2.kind == _BoolType || op2.kind == charType) *value2 = (t) op2.uc; \
370       else if(op2.kind == floatType) *value2 = (t) op2.f;                         \
371       else if(op2.kind == doubleType) *value2 = (t) op2.d;                        \
372       else if(op2.kind == pointerType) *value2 = (t) op2.ui64;                    \
373       else                                                                          \
374          return false;                                                              \
375       return true;                                                                  \
376    } \
377    public bool Get##name(Expression exp, t * value2) \
378    {                                                        \
379       Operand op2 = GetOperand(exp);                        \
380       return GetOp##name(op2, value2); \
381    }
382
383 // To help the debugger currently not preprocessing...
384 #define HELP(x) x
385
386 GETVALUE(Int, HELP(int));
387 GETVALUE(UInt, HELP(unsigned int));
388 GETVALUE(Int64, HELP(int64));
389 GETVALUE(UInt64, HELP(uint64));
390 GETVALUE(IntPtr, HELP(intptr));
391 GETVALUE(UIntPtr, HELP(uintptr));
392 GETVALUE(IntSize, HELP(intsize));
393 GETVALUE(UIntSize, HELP(uintsize));
394 GETVALUE(Short, HELP(short));
395 GETVALUE(UShort, HELP(unsigned short));
396 GETVALUE(Char, HELP(char));
397 GETVALUE(UChar, HELP(unsigned char));
398 GETVALUE(Float, HELP(float));
399 GETVALUE(Double, HELP(double));
400
401 void ComputeExpression(Expression exp);
402
403 void ComputeClassMembers(Class _class, bool isMember)
404 {
405    DataMember member = isMember ? (DataMember) _class : null;
406    Context context = isMember ? null : SetupTemplatesContext(_class);
407    if(member || ((_class.type == bitClass || _class.type == normalClass || _class.type == structClass || _class.type == noHeadClass) &&
408                  (_class.type == bitClass || (!_class.structSize || _class.structSize == _class.offset)) && _class.computeSize))
409    {
410       int unionMemberOffset = 0;
411       int bitFields = 0;
412
413       /*
414       if(!member && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass) && _class.memberOffset && _class.memberOffset > _class.base.structSize)
415          _class.memberOffset = (_class.base && _class.base.type != systemClass) ? _class.base.structSize : 0;
416       */
417
418       if(member)
419       {
420          member.memberOffset = 0;
421          if(targetBits < sizeof(void *) * 8)
422             member.structAlignment = 0;
423       }
424       else if(targetBits < sizeof(void *) * 8)
425          _class.structAlignment = 0;
426
427       // Confusion here: non struct classes seem to have their memberOffset restart at 0 at each hierarchy level
428       if(!member && ((_class.type == normalClass || _class.type == noHeadClass) || (_class.type == structClass && _class.memberOffset && _class.memberOffset > _class.base.structSize)))
429          _class.memberOffset = (_class.base && _class.type == structClass) ? _class.base.structSize : 0;
430
431       if(!member && _class.destructionWatchOffset)
432          _class.memberOffset += sizeof(OldList);
433
434       // To avoid reentrancy...
435       //_class.structSize = -1;
436
437       {
438          DataMember dataMember;
439          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
440          {
441             if(!dataMember.isProperty)
442             {
443                if(dataMember.type == normalMember && dataMember.dataTypeString && !dataMember.dataType)
444                {
445                   dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
446                   /*if(!dataMember.dataType)
447                      dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
448                      */
449                }
450             }
451          }
452       }
453
454       {
455          DataMember dataMember;
456          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
457          {
458             if(!dataMember.isProperty && (dataMember.type != normalMember || dataMember.dataTypeString))
459             {
460                if(!isMember && _class.type == bitClass && dataMember.dataType)
461                {
462                   BitMember bitMember = (BitMember) dataMember;
463                   uint64 mask = 0;
464                   int d;
465
466                   ComputeTypeSize(dataMember.dataType);
467
468                   if(bitMember.pos == -1) bitMember.pos = _class.memberOffset;
469                   if(!bitMember.size) bitMember.size = dataMember.dataType.size * 8;
470
471                   _class.memberOffset = bitMember.pos + bitMember.size;
472                   for(d = 0; d<bitMember.size; d++)
473                   {
474                      if(d)
475                         mask <<= 1;
476                      mask |= 1;
477                   }
478                   bitMember.mask = mask << bitMember.pos;
479                }
480                else if(dataMember.type == normalMember && dataMember.dataType)
481                {
482                   int size;
483                   int alignment = 0;
484
485                   // Prevent infinite recursion
486                   if(dataMember.dataType.kind != classType ||
487                      ((!dataMember.dataType._class || !dataMember.dataType._class.registered || dataMember.dataType._class.registered != _class ||
488                      _class.type != structClass)))
489                      ComputeTypeSize(dataMember.dataType);
490
491                   if(dataMember.dataType.bitFieldCount)
492                   {
493                      bitFields += dataMember.dataType.bitFieldCount;
494                      size = 0;
495                   }
496                   else
497                   {
498                      if(bitFields)
499                      {
500                         int size = (bitFields + 7) / 8;
501
502                         if(isMember)
503                         {
504                            // TESTING THIS PADDING CODE
505                            if(alignment)
506                            {
507                               member.structAlignment = Max(member.structAlignment, alignment);
508
509                               if(member.memberOffset % alignment)
510                                  member.memberOffset += alignment - (member.memberOffset % alignment);
511                            }
512
513                            dataMember.offset = member.memberOffset;
514                            if(member.type == unionMember)
515                               unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
516                            else
517                            {
518                               member.memberOffset += size;
519                            }
520                         }
521                         else
522                         {
523                            // TESTING THIS PADDING CODE
524                            if(alignment)
525                            {
526                               _class.structAlignment = Max(_class.structAlignment, alignment);
527
528                               if(_class.memberOffset % alignment)
529                                  _class.memberOffset += alignment - (_class.memberOffset % alignment);
530                            }
531
532                            dataMember.offset = _class.memberOffset;
533                            _class.memberOffset += size;
534                         }
535                         bitFields = 0;
536                      }
537                      size = dataMember.dataType.size;
538                      alignment = dataMember.dataType.alignment;
539                   }
540
541                   if(isMember)
542                   {
543                      // TESTING THIS PADDING CODE
544                      if(alignment)
545                      {
546                         member.structAlignment = Max(member.structAlignment, alignment);
547
548                         if(member.memberOffset % alignment)
549                            member.memberOffset += alignment - (member.memberOffset % alignment);
550                      }
551
552                      dataMember.offset = member.memberOffset;
553                      if(member.type == unionMember)
554                         unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
555                      else
556                      {
557                         member.memberOffset += size;
558                      }
559                   }
560                   else
561                   {
562                      // TESTING THIS PADDING CODE
563                      if(alignment)
564                      {
565                         _class.structAlignment = Max(_class.structAlignment, alignment);
566
567                         if(_class.memberOffset % alignment)
568                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
569                      }
570
571                      dataMember.offset = _class.memberOffset;
572                      _class.memberOffset += size;
573                   }
574                }
575                else
576                {
577                   int alignment;
578
579                   ComputeClassMembers((Class)dataMember, true);
580                   alignment = dataMember.structAlignment;
581
582                   if(isMember)
583                   {
584                      if(alignment)
585                      {
586                         if(member.memberOffset % alignment)
587                            member.memberOffset += alignment - (member.memberOffset % alignment);
588
589                         member.structAlignment = Max(member.structAlignment, alignment);
590                      }
591                      dataMember.offset = member.memberOffset;
592                      if(member.type == unionMember)
593                         unionMemberOffset = Max(unionMemberOffset, dataMember.memberOffset);
594                      else
595                         member.memberOffset += dataMember.memberOffset;
596                   }
597                   else
598                   {
599                      if(alignment)
600                      {
601                         if(_class.memberOffset % alignment)
602                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
603                         _class.structAlignment = Max(_class.structAlignment, alignment);
604                      }
605                      dataMember.offset = _class.memberOffset;
606                      _class.memberOffset += dataMember.memberOffset;
607                   }
608                }
609             }
610          }
611          if(bitFields)
612          {
613             int alignment = 0;
614             int size = (bitFields + 7) / 8;
615
616             if(isMember)
617             {
618                // TESTING THIS PADDING CODE
619                if(alignment)
620                {
621                   member.structAlignment = Max(member.structAlignment, alignment);
622
623                   if(member.memberOffset % alignment)
624                      member.memberOffset += alignment - (member.memberOffset % alignment);
625                }
626
627                if(member.type == unionMember)
628                   unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
629                else
630                {
631                   member.memberOffset += size;
632                }
633             }
634             else
635             {
636                // TESTING THIS PADDING CODE
637                if(alignment)
638                {
639                   _class.structAlignment = Max(_class.structAlignment, alignment);
640
641                   if(_class.memberOffset % alignment)
642                      _class.memberOffset += alignment - (_class.memberOffset % alignment);
643                }
644                _class.memberOffset += size;
645             }
646             bitFields = 0;
647          }
648       }
649       if(member && member.type == unionMember)
650       {
651          member.memberOffset = unionMemberOffset;
652       }
653
654       if(!isMember)
655       {
656          /*if(_class.type == structClass)
657             _class.size = _class.memberOffset;
658          else
659          */
660
661          if(_class.type != bitClass)
662          {
663             int extra = 0;
664             if(_class.structAlignment)
665             {
666                if(_class.memberOffset % _class.structAlignment)
667                   extra += _class.structAlignment - (_class.memberOffset % _class.structAlignment);
668             }
669             _class.structSize = (_class.base ? (_class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize) : 0) + _class.memberOffset + extra;
670             if(!member)
671             {
672                Property prop;
673                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
674                {
675                   if(prop.isProperty && prop.isWatchable)
676                   {
677                      prop.watcherOffset = _class.structSize;
678                      _class.structSize += sizeof(OldList);
679                   }
680                }
681             }
682
683             // Fix Derivatives
684             {
685                OldLink derivative;
686                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
687                {
688                   Class deriv = derivative.data;
689
690                   if(deriv.computeSize)
691                   {
692                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
693                      deriv.offset = /*_class.offset + */_class.structSize;
694                      deriv.memberOffset = 0;
695                      // ----------------------
696
697                      deriv.structSize = deriv.offset;
698
699                      ComputeClassMembers(deriv, false);
700                   }
701                }
702             }
703          }
704       }
705    }
706    if(context)
707       FinishTemplatesContext(context);
708 }
709
710 public void ComputeModuleClasses(Module module)
711 {
712    Class _class;
713    OldLink subModule;
714
715    for(subModule = module.modules.first; subModule; subModule = subModule.next)
716       ComputeModuleClasses(subModule.data);
717    for(_class = module.classes.first; _class; _class = _class.next)
718       ComputeClassMembers(_class, false);
719 }
720
721
722 public int ComputeTypeSize(Type type)
723 {
724    uint size = type ? type.size : 0;
725    if(!size && type && !type.computing)
726    {
727       type.computing = true;
728       switch(type.kind)
729       {
730          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
731          case charType: type.alignment = size = sizeof(char); break;
732          case intType: type.alignment = size = sizeof(int); break;
733          case int64Type: type.alignment = size = sizeof(int64); break;
734          case intPtrType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
735          case intSizeType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
736          case longType: type.alignment = size = sizeof(long); break;
737          case shortType: type.alignment = size = sizeof(short); break;
738          case floatType: type.alignment = size = sizeof(float); break;
739          case doubleType: type.alignment = size = sizeof(double); break;
740          case classType:
741          {
742             Class _class = type._class ? type._class.registered : null;
743
744             if(_class && _class.type == structClass)
745             {
746                // Ensure all members are properly registered
747                ComputeClassMembers(_class, false);
748                type.alignment = _class.structAlignment;
749                type.pointerAlignment = (bool)_class.pointerAlignment;
750                size = _class.structSize;
751                if(type.alignment && size % type.alignment)
752                   size += type.alignment - (size % type.alignment);
753
754             }
755             else if(_class && (_class.type == unitClass ||
756                    _class.type == enumClass ||
757                    _class.type == bitClass))
758             {
759                if(!_class.dataType)
760                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
761                size = type.alignment = ComputeTypeSize(_class.dataType);
762             }
763             else
764             {
765                size = type.alignment = targetBits / 8; // sizeof(Instance *);
766                type.pointerAlignment = true;
767             }
768             break;
769          }
770          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */ type.pointerAlignment = true; break;
771          case arrayType:
772             if(type.arraySizeExp)
773             {
774                ProcessExpressionType(type.arraySizeExp);
775                ComputeExpression(type.arraySizeExp);
776                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType &&
777                   type.arraySizeExp.expType.kind != shortType &&
778                   type.arraySizeExp.expType.kind != charType &&
779                   type.arraySizeExp.expType.kind != longType &&
780                   type.arraySizeExp.expType.kind != int64Type &&
781                   type.arraySizeExp.expType.kind != intSizeType &&
782                   type.arraySizeExp.expType.kind != intPtrType &&
783                   type.arraySizeExp.expType.kind != enumType &&
784                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
785                {
786                   Location oldLoc = yylloc;
787                   // bool isConstant = type.arraySizeExp.isConstant;
788                   char expression[10240];
789                   expression[0] = '\0';
790                   type.arraySizeExp.expType = null;
791                   yylloc = type.arraySizeExp.loc;
792                   if(inCompiler)
793                      PrintExpression(type.arraySizeExp, expression);
794                   Compiler_Error($"Array size not constant int (%s)\n", expression);
795                   yylloc = oldLoc;
796                }
797                GetInt(type.arraySizeExp, &type.arraySize);
798             }
799             else if(type.enumClass)
800             {
801                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
802                {
803                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
804                }
805                else
806                   type.arraySize = 0;
807             }
808             else
809             {
810                // Unimplemented auto size
811                type.arraySize = 0;
812             }
813
814             size = ComputeTypeSize(type.type) * type.arraySize;
815             if(type.type)
816             {
817                type.alignment = type.type.alignment;
818                type.pointerAlignment = type.type.pointerAlignment;
819             }
820
821             break;
822          case structType:
823          {
824             if(!type.members.first && type.enumName)
825             {
826                Symbol symbol = FindStruct(curContext, type.enumName);
827                if(symbol && symbol.type)
828                {
829                   ComputeTypeSize(symbol.type);
830                   size = symbol.type.size;
831                }
832             }
833             else
834             {
835                Type member;
836                for(member = type.members.first; member; member = member.next)
837                {
838                   uint addSize = ComputeTypeSize(member);
839
840                   member.offset = size;
841                   if(member.alignment && size % member.alignment)
842                      member.offset += member.alignment - (size % member.alignment);
843                   size = member.offset;
844
845                   if(member.pointerAlignment && type.size <= 4)
846                      type.pointerAlignment = true;
847                   else if(!member.pointerAlignment && member.alignment >= 8)
848                      type.pointerAlignment = false;
849
850                   type.alignment = Max(type.alignment, member.alignment);
851                   size += addSize;
852                }
853                if(type.alignment && size % type.alignment)
854                   size += type.alignment - (size % type.alignment);
855             }
856             break;
857          }
858          case unionType:
859          {
860             if(!type.members.first && type.enumName)
861             {
862                Symbol symbol = FindStruct(curContext, type.enumName);
863                if(symbol && symbol.type)
864                {
865                   ComputeTypeSize(symbol.type);
866                   size = symbol.type.size;
867                   type.alignment = symbol.type.alignment;
868                }
869             }
870             else
871             {
872                Type member;
873                for(member = type.members.first; member; member = member.next)
874                {
875                   uint addSize = ComputeTypeSize(member);
876
877                   member.offset = size;
878                   if(member.alignment && size % member.alignment)
879                      member.offset += member.alignment - (size % member.alignment);
880                   size = member.offset;
881
882                   if(member.pointerAlignment && type.size <= 4)
883                      type.pointerAlignment = true;
884                   else if(!member.pointerAlignment && member.alignment >= 8)
885                      type.pointerAlignment = false;
886
887                   type.alignment = Max(type.alignment, member.alignment);
888
889                   size = Max(size, addSize);
890                }
891                if(type.alignment && size % type.alignment)
892                   size += type.alignment - (size % type.alignment);
893             }
894             break;
895          }
896          case templateType:
897          {
898             TemplateParameter param = type.templateParameter;
899             Type baseType = ProcessTemplateParameterType(param);
900             if(baseType)
901             {
902                size = ComputeTypeSize(baseType);
903                type.alignment = baseType.alignment;
904                type.pointerAlignment = baseType.pointerAlignment;
905             }
906             else
907                type.alignment = size = sizeof(uint64);
908             break;
909          }
910          case enumType:
911          {
912             type.alignment = size = sizeof(enum { test });
913             break;
914          }
915          case thisClassType:
916          {
917             type.alignment = size = targetBits / 8; //sizeof(void *);
918             type.pointerAlignment = true;
919             break;
920          }
921       }
922       type.size = size;
923       type.computing = false;
924    }
925    return size;
926 }
927
928
929 /*static */int AddMembers(External neededBy, OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
930 {
931    // This function is in need of a major review when implementing private members etc.
932    DataMember topMember = isMember ? (DataMember) _class : null;
933    uint totalSize = 0;
934    uint maxSize = 0;
935    int alignment;
936    uint size;
937    DataMember member;
938    int anonID = 1;
939    Context context = isMember ? null : SetupTemplatesContext(_class);
940    if(addedPadding)
941       *addedPadding = false;
942
943    if(!isMember && _class.base)
944    {
945       maxSize = _class.structSize;
946       //if(_class.base.type != systemClass) // Commented out with new Instance _class
947       {
948          // DANGER: Testing this noHeadClass here...
949          if(_class.type == structClass || _class.type == noHeadClass)
950             /*totalSize = */AddMembers(neededBy, declarations, _class.base, false, &totalSize, topClass, null);
951          else
952          {
953             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
954             if(maxSize > baseSize)
955                maxSize -= baseSize;
956             else
957                maxSize = 0;
958          }
959       }
960    }
961
962    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
963    {
964       if(!member.isProperty)
965       {
966          switch(member.type)
967          {
968             case normalMember:
969             {
970                if(member.dataTypeString)
971                {
972                   OldList * specs = MkList(), * decls = MkList();
973                   Declarator decl;
974
975                   decl = SpecDeclFromString(member.dataTypeString, specs,
976                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
977                   ListAdd(decls, MkStructDeclarator(decl, null));
978                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
979
980                   if(!member.dataType)
981                      member.dataType = ProcessType(specs, decl);
982
983                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
984
985                   {
986                      Type type = ProcessType(specs, decl);
987                      DeclareType(neededBy, member.dataType, true, false);
988                      FreeType(type);
989                   }
990                   /*
991                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
992                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
993                      DeclareStruct(member.dataType._class.string, false);
994                   */
995
996                   ComputeTypeSize(member.dataType);
997                   size = member.dataType.size;
998                   alignment = member.dataType.alignment;
999
1000                   if(alignment)
1001                   {
1002                      if(totalSize % alignment)
1003                         totalSize += alignment - (totalSize % alignment);
1004                   }
1005                   totalSize += size;
1006                }
1007                break;
1008             }
1009             case unionMember:
1010             case structMember:
1011             {
1012                OldList * specs = MkList(), * list = MkList();
1013                char id[100];
1014                sprintf(id, "__anon%d", anonID++);
1015
1016                size = 0;
1017                AddMembers(neededBy, list, (Class)member, true, &size, topClass, null);
1018                ListAdd(specs,
1019                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
1020                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, MkListOne(MkDeclaratorIdentifier(MkIdentifier(id))),null)));
1021                alignment = member.structAlignment;
1022
1023                if(alignment)
1024                {
1025                   if(totalSize % alignment)
1026                      totalSize += alignment - (totalSize % alignment);
1027                }
1028                totalSize += size;
1029                break;
1030             }
1031          }
1032       }
1033    }
1034    if(retSize)
1035    {
1036       if(topMember && topMember.type == unionMember)
1037          *retSize = Max(*retSize, totalSize);
1038       else
1039          *retSize += totalSize;
1040    }
1041    else if(totalSize < maxSize && _class.type != systemClass)
1042    {
1043       int autoPadding = 0;
1044       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
1045          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
1046       if(totalSize + autoPadding < maxSize)
1047       {
1048          char sizeString[50];
1049          sprintf(sizeString, "%d", maxSize - totalSize);
1050          ListAdd(declarations,
1051             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
1052             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
1053          if(addedPadding)
1054             *addedPadding = true;
1055       }
1056    }
1057    if(context)
1058       FinishTemplatesContext(context);
1059    return topMember ? topMember.memberID : _class.memberID;
1060 }
1061
1062 static int DeclareMembers(External neededBy, Class _class, bool isMember)
1063 {
1064    DataMember topMember = isMember ? (DataMember) _class : null;
1065    DataMember member;
1066    Context context = isMember ? null : SetupTemplatesContext(_class);
1067
1068    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1069       DeclareMembers(neededBy, _class.base, false);
1070
1071    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1072    {
1073       if(!member.isProperty)
1074       {
1075          switch(member.type)
1076          {
1077             case normalMember:
1078             {
1079                if(!member.dataType && member.dataTypeString)
1080                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1081                if(member.dataType)
1082                   DeclareType(neededBy, member.dataType, true, false);
1083                break;
1084             }
1085             case unionMember:
1086             case structMember:
1087             {
1088                DeclareMembers(neededBy, (Class)member, true);
1089                break;
1090             }
1091          }
1092       }
1093    }
1094    if(context)
1095       FinishTemplatesContext(context);
1096
1097    return topMember ? topMember.memberID : _class.memberID;
1098 }
1099
1100 static void IdentifyAnonStructs(OldList/*<ClassDef>*/ *  definitions)
1101 {
1102    ClassDef def;
1103    int anonID = 1;
1104    for(def = definitions->first; def; def = def.next)
1105    {
1106       if(def.type == declarationClassDef)
1107       {
1108          Declaration decl = def.decl;
1109          if(decl && decl.specifiers)
1110          {
1111             Specifier spec;
1112             bool isStruct = false;
1113             for(spec = decl.specifiers->first; spec; spec = spec.next)
1114             {
1115                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1116                {
1117                   if(spec.definitions)
1118                      IdentifyAnonStructs(spec.definitions);
1119                   isStruct = true;
1120                }
1121             }
1122             if(isStruct)
1123             {
1124                Declarator d = null;
1125                if(decl.declarators)
1126                {
1127                   for(d = decl.declarators->first; d; d = d.next)
1128                   {
1129                      Identifier idDecl = GetDeclId(d);
1130                      if(idDecl)
1131                         break;
1132                   }
1133                }
1134                if(!d)
1135                {
1136                   char id[100];
1137                   sprintf(id, "__anon%d", anonID++);
1138                   if(!decl.declarators)
1139                      decl.declarators = MkList();
1140                   ListAdd(decl.declarators, MkDeclaratorIdentifier(MkIdentifier(id)));
1141                }
1142             }
1143          }
1144       }
1145    }
1146 }
1147
1148 External DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference)
1149 {
1150    return _DeclareStruct(neededBy, name, skipNoHead, needDereference, false);
1151 }
1152
1153 External _DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference, bool fwdDecl)
1154 {
1155    External external = null;
1156    Symbol classSym = FindClass(name);
1157    OldList * curDeclarations = null;
1158    Specifier curSpec = null;
1159
1160    if(!inCompiler || !classSym) return null;
1161
1162    // We don't need any declaration for bit classes...
1163    if(classSym.registered &&
1164       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1165       return null;
1166
1167    if(!classSym.registered || (classSym.registered.type == normalClass && classSym.registered.structSize && classSym.registered.base && classSym.registered.base.base))
1168       _DeclareStruct(neededBy, "ecere::com::Instance", false, true, fwdDecl);
1169
1170    external = classSym.structExternal;
1171
1172    if(external && external.declaration)
1173    {
1174       Specifier spec;
1175       for(spec = external.declaration.specifiers ? external.declaration.specifiers->first : null; spec; spec = spec.next)
1176          if(spec.type == structSpecifier || spec.type == unionSpecifier)
1177          {
1178             curSpec = spec;
1179             curDeclarations = spec.definitions;
1180             break;
1181          }
1182    }
1183
1184    if(classSym.registered && !classSym.declaring && classSym.imported && (!classSym.declaredStructSym || (classSym.registered.type == noHeadClass && !skipNoHead && external && !curDeclarations)))
1185    {
1186       OldList * specifiers, * declarators;
1187       OldList * declarations = null;
1188       char structName[1024];
1189       bool addedPadding = false;
1190
1191       classSym.declaring++;
1192
1193       if(strchr(classSym.string, '<'))
1194       {
1195          if(classSym.registered.templateClass)
1196          {
1197             external = _DeclareStruct(neededBy, classSym.registered.templateClass.fullName, skipNoHead, needDereference, fwdDecl);
1198             classSym.declaring--;
1199          }
1200          return external;
1201       }
1202
1203       structName[0] = 0;
1204       FullClassNameCat(structName, name, false);
1205
1206       classSym.declaredStructSym = true;
1207       if(!external || (classSym.registered.type == noHeadClass && !skipNoHead && !curDeclarations))
1208       {
1209          bool add = false;
1210          if(!external)
1211          {
1212             external = MkExternalDeclaration(null);
1213             classSym.structExternal = external;
1214             external.symbol = classSym;
1215
1216             add = true;
1217          }
1218
1219          if(!skipNoHead)
1220          {
1221             declarations = MkList();
1222             AddMembers(external, declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1223          }
1224
1225          if(declarations && (!declarations->count || (declarations->count == 1 && addedPadding)))
1226          {
1227             FreeList(declarations, FreeClassDef);
1228             declarations = null;
1229          }
1230
1231          if(classSym.registered.type != noHeadClass && !declarations)
1232          {
1233             FreeExternal(external);
1234             external = null;
1235             classSym.structExternal = null;
1236          }
1237          else
1238          {
1239             if(curSpec)
1240                curSpec.definitions = declarations;
1241             else
1242             {
1243                char className[1024];
1244                strcpy(className, "__ecereClass_");
1245                FullClassNameCat(className, classSym.string, true);
1246
1247                specifiers = MkList();
1248                declarators = MkList();
1249                ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1250                external.declaration = MkDeclaration(specifiers, declarators);
1251             }
1252             if(add)
1253                ast->Add(external);
1254          }
1255       }
1256       classSym.declaring--;
1257    }
1258    else if(!classSym.declaredStructSym && classSym.structExternal)
1259    {
1260       classSym.declaredStructSym = true;
1261
1262       if(classSym.registered)
1263          DeclareMembers(classSym.structExternal, classSym.registered, false);
1264
1265       if(classSym.structExternal.declaration && classSym.structExternal.declaration.specifiers)
1266       {
1267          Specifier spec;
1268          for(spec = classSym.structExternal.declaration.specifiers->first; spec; spec = spec.next)
1269          {
1270             if(spec.definitions)
1271                IdentifyAnonStructs(spec.definitions);
1272          }
1273       }
1274    }
1275    if(inCompiler && neededBy && (external || !classSym.imported))
1276    {
1277       if(!external)
1278       {
1279          classSym.structExternal = external = MkExternalDeclaration(null);
1280          external.symbol = classSym;
1281          ast->Add(external);
1282       }
1283       if(fwdDecl)
1284       {
1285          External e = external.fwdDecl ? external.fwdDecl : external;
1286          if(e.incoming.count)
1287             neededBy.CreateUniqueEdge(e, !needDereference && !external.fwdDecl);
1288       }
1289       else
1290          neededBy.CreateUniqueEdge(external, !needDereference);
1291    }
1292    return external;
1293 }
1294
1295 void DeclareProperty(External neededBy, Property prop, char * setName, char * getName)
1296 {
1297    Symbol symbol = prop.symbol;
1298    bool imported = false;
1299    bool dllImport = false;
1300    External structExternal = null;
1301    External instExternal = null;
1302
1303    strcpy(setName, "__ecereProp_");
1304    FullClassNameCat(setName, prop._class.fullName, false);
1305    strcat(setName, "_Set_");
1306    FullClassNameCat(setName, prop.name, true);
1307
1308    strcpy(getName, "__ecereProp_");
1309    FullClassNameCat(getName, prop._class.fullName, false);
1310    strcat(getName, "_Get_");
1311    FullClassNameCat(getName, prop.name, true);
1312
1313    if(!symbol || symbol._import)
1314    {
1315       if(!symbol)
1316       {
1317          Symbol classSym;
1318
1319          if(!prop._class.symbol)
1320             prop._class.symbol = FindClass(prop._class.fullName);
1321          classSym = prop._class.symbol;
1322          if(classSym && !classSym._import)
1323          {
1324             ModuleImport module;
1325
1326             if(prop._class.module)
1327                module = FindModule(prop._class.module);
1328             else
1329                module = mainModule;
1330
1331             classSym._import = ClassImport
1332             {
1333                name = CopyString(prop._class.fullName);
1334                isRemote = prop._class.isRemote;
1335             };
1336             module.classes.Add(classSym._import);
1337          }
1338          symbol = prop.symbol = Symbol { };
1339          symbol._import = (ClassImport)PropertyImport
1340          {
1341             name = CopyString(prop.name);
1342             isVirtual = false; //prop.isVirtual;
1343             hasSet = prop.Set ? true : false;
1344             hasGet = prop.Get ? true : false;
1345          };
1346          if(classSym)
1347             classSym._import.properties.Add(symbol._import);
1348       }
1349       imported = true;
1350       // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1351       if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1352          prop._class.module.importType != staticImport)
1353          dllImport = true;
1354    }
1355
1356    if(!symbol.type)
1357    {
1358       Context context = SetupTemplatesContext(prop._class);
1359       symbol.type = ProcessTypeString(prop.dataTypeString, false);
1360       FinishTemplatesContext(context);
1361    }
1362
1363    if((prop.Get && !symbol.externalGet) || (prop.Set && !symbol.externalSet))
1364    {
1365       if(prop._class.type == normalClass && prop._class.structSize)
1366          instExternal = DeclareStruct(null, "ecere::com::Instance", false, true);
1367       structExternal = DeclareStruct(null, prop._class.fullName, prop._class.type != structClass /*true*/, false);
1368    }
1369
1370    // Get
1371    if(prop.Get && !symbol.externalGet)
1372    {
1373       Declaration decl;
1374       OldList * specifiers, * declarators;
1375       Declarator d;
1376       OldList * params;
1377       Specifier spec = null;
1378       External external;
1379       Declarator typeDecl;
1380       bool simple = false;
1381       bool needReference;
1382
1383       specifiers = MkList();
1384       declarators = MkList();
1385       params = MkList();
1386
1387       ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1388          MkDeclaratorIdentifier(MkIdentifier("this"))));
1389
1390       d = MkDeclaratorIdentifier(MkIdentifier(getName));
1391       //if(imported)
1392       if(dllImport)
1393          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1394
1395       {
1396          Context context = SetupTemplatesContext(prop._class);
1397          typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1398          FinishTemplatesContext(context);
1399       }
1400
1401       // Make sure the simple _class's type is declared
1402       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1403       for(spec = specifiers->first; spec; spec = spec.next)
1404       {
1405          if(spec.type == nameSpecifier)
1406          {
1407             Symbol classSym = spec.symbol;
1408             if(needReference)
1409             {
1410                symbol._class = classSym.registered;
1411                if(classSym.registered && classSym.registered.type == structClass)
1412                   simple = true;
1413             }
1414             break;
1415          }
1416       }
1417
1418       if(!simple)
1419          d = PlugDeclarator(typeDecl, d);
1420       else
1421       {
1422          ListAdd(params, MkTypeName(specifiers,
1423             PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1424          specifiers = MkList();
1425       }
1426
1427       d = MkDeclaratorFunction(d, params);
1428
1429       //if(imported)
1430       if(dllImport)
1431          specifiers->Insert(null, MkSpecifier(EXTERN));
1432       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1433          specifiers->Insert(null, MkSpecifier(STATIC));
1434       if(simple)
1435          ListAdd(specifiers, MkSpecifier(VOID));
1436
1437       ListAdd(declarators, MkInitDeclarator(d, null));
1438
1439       decl = MkDeclaration(specifiers, declarators);
1440
1441       external = MkExternalDeclaration(decl);
1442
1443       if(structExternal)
1444          external.CreateEdge(structExternal, false);
1445       if(instExternal)
1446          external.CreateEdge(instExternal, false);
1447
1448       if(spec)
1449          DeclareStruct(external, spec.name, false, needReference);
1450
1451       ast->Add(external);
1452       external.symbol = symbol;
1453       symbol.externalGet = external;
1454
1455       ReplaceThisClassSpecifiers(specifiers, prop._class);
1456
1457       if(typeDecl)
1458          FreeDeclarator(typeDecl);
1459    }
1460
1461    // Set
1462    if(prop.Set && !symbol.externalSet)
1463    {
1464       Declaration decl;
1465       OldList * specifiers, * declarators;
1466       Declarator d;
1467       OldList * params;
1468       Specifier spec = null;
1469       External external;
1470       Declarator typeDecl;
1471       bool needReference;
1472
1473       declarators = MkList();
1474       params = MkList();
1475
1476       if(!prop.conversion || prop._class.type == structClass)
1477       {
1478          ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1479             MkDeclaratorIdentifier(MkIdentifier("this"))));
1480       }
1481
1482       specifiers = MkList();
1483
1484       {
1485          Context context = SetupTemplatesContext(prop._class);
1486          typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1487             MkDeclaratorIdentifier(MkIdentifier("value")));
1488          FinishTemplatesContext(context);
1489       }
1490       if(!strcmp(prop._class.base.fullName, "eda::Row") || !strcmp(prop._class.base.fullName, "eda::Id"))
1491          specifiers->Insert(null, MkSpecifier(CONST));
1492
1493       ListAdd(params, MkTypeName(specifiers, d));
1494
1495       d = MkDeclaratorIdentifier(MkIdentifier(setName));
1496       if(dllImport)
1497          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1498       d = MkDeclaratorFunction(d, params);
1499
1500       // Make sure the simple _class's type is declared
1501       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1502       for(spec = specifiers->first; spec; spec = spec.next)
1503       {
1504          if(spec.type == nameSpecifier)
1505          {
1506             Symbol classSym = spec.symbol;
1507             if(needReference)
1508                symbol._class = classSym.registered;
1509             break;
1510          }
1511       }
1512
1513       ListAdd(declarators, MkInitDeclarator(d, null));
1514
1515       specifiers = MkList();
1516       if(dllImport)
1517          specifiers->Insert(null, MkSpecifier(EXTERN));
1518       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1519          specifiers->Insert(null, MkSpecifier(STATIC));
1520
1521       if(!prop.conversion || prop._class.type == structClass)
1522          ListAdd(specifiers, MkSpecifier(VOID));
1523       else
1524          ListAdd(specifiers, MkSpecifierName(prop._class.fullName));
1525
1526       decl = MkDeclaration(specifiers, declarators);
1527
1528       external = MkExternalDeclaration(decl);
1529
1530       if(structExternal)
1531          external.CreateEdge(structExternal, false);
1532       if(instExternal)
1533          external.CreateEdge(instExternal, false);
1534
1535       if(spec)
1536          DeclareStruct(external, spec.name, false, needReference);
1537
1538       ast->Add(external);
1539       external.symbol = symbol;
1540       symbol.externalSet = external;
1541
1542       ReplaceThisClassSpecifiers(specifiers, prop._class);
1543    }
1544
1545    // Property (for Watchers)
1546    if(!symbol.externalPtr)
1547    {
1548       Declaration decl;
1549       External external;
1550       OldList * specifiers = MkList();
1551       char propName[1024];
1552
1553       if(imported)
1554          specifiers->Insert(null, MkSpecifier(EXTERN));
1555       else
1556       {
1557          specifiers->Insert(null, MkSpecifier(STATIC));
1558          specifiers->Add(MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
1559       }
1560
1561       ListAdd(specifiers, MkSpecifierName("Property"));
1562
1563       strcpy(propName, "__ecereProp_");
1564       FullClassNameCat(propName, prop._class.fullName, false);
1565       strcat(propName, "_");
1566       FullClassNameCat(propName, prop.name, true);
1567
1568       {
1569          OldList * list = MkList();
1570          ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1571
1572          if(!imported)
1573          {
1574             strcpy(propName, "__ecerePropM_");
1575             FullClassNameCat(propName, prop._class.fullName, false);
1576             strcat(propName, "_");
1577             FullClassNameCat(propName, prop.name, true);
1578
1579             ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1580          }
1581          decl = MkDeclaration(specifiers, list);
1582       }
1583
1584       external = MkExternalDeclaration(decl);
1585       ast->Insert(curExternal.prev, external);
1586       external.symbol = symbol;
1587       symbol.externalPtr = external;
1588    }
1589
1590    if(inCompiler && neededBy)
1591    {
1592       // Could improve this to create edge on only what is needed...
1593       if(symbol.externalPtr)
1594          neededBy.CreateUniqueEdge(symbol.externalPtr, false);
1595
1596       if(symbol.externalGet)
1597          neededBy.CreateUniqueEdge(symbol.externalGet, symbol.externalGet.type == functionExternal);
1598
1599       if(symbol.externalSet)
1600          neededBy.CreateUniqueEdge(symbol.externalSet, symbol.externalSet.type == functionExternal);
1601
1602       // IsSet ?
1603    }
1604 }
1605
1606 // ***************** EXPRESSION PROCESSING ***************************
1607 public Type Dereference(Type source)
1608 {
1609    Type type = null;
1610    if(source)
1611    {
1612       if(source.kind == pointerType || source.kind == arrayType)
1613       {
1614          type = source.type;
1615          source.type.refCount++;
1616       }
1617       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1618       {
1619          type = Type
1620          {
1621             kind = charType;
1622             refCount = 1;
1623          };
1624       }
1625       // Support dereferencing of no head classes for now...
1626       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1627       {
1628          type = source;
1629          source.refCount++;
1630       }
1631       else
1632          Compiler_Error($"cannot dereference type\n");
1633    }
1634    return type;
1635 }
1636
1637 static Type Reference(Type source)
1638 {
1639    Type type = null;
1640    if(source)
1641    {
1642       type = Type
1643       {
1644          kind = pointerType;
1645          type = source;
1646          refCount = 1;
1647       };
1648       source.refCount++;
1649    }
1650    return type;
1651 }
1652
1653 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1654 {
1655    Identifier ident = member.identifiers ? member.identifiers->first : null;
1656    bool found = false;
1657    DataMember dataMember = null;
1658    Method method = null;
1659    bool freeType = false;
1660
1661    yylloc = member.loc;
1662
1663    if(!ident)
1664    {
1665       if(curMember)
1666       {
1667          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1668          if(*curMember)
1669          {
1670             found = true;
1671             dataMember = *curMember;
1672          }
1673       }
1674    }
1675    else
1676    {
1677       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1678       DataMember _subMemberStack[256];
1679       int _subMemberStackPos = 0;
1680
1681       // FILL MEMBER STACK
1682       if(!thisMember)
1683          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1684       if(thisMember)
1685       {
1686          dataMember = thisMember;
1687          if(curMember && thisMember.memberAccess == publicAccess)
1688          {
1689             *curMember = thisMember;
1690             *curClass = thisMember._class;
1691             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1692             *subMemberStackPos = _subMemberStackPos;
1693          }
1694          found = true;
1695       }
1696       else
1697       {
1698          // Setting a method
1699          method = eClass_FindMethod(_class, ident.string, privateModule);
1700          if(method && method.type == virtualMethod)
1701             found = true;
1702          else
1703             method = null;
1704       }
1705    }
1706
1707    if(found)
1708    {
1709       Type type = null;
1710       if(dataMember)
1711       {
1712          if(!dataMember.dataType && dataMember.dataTypeString)
1713          {
1714             //Context context = SetupTemplatesContext(dataMember._class);
1715             Context context = SetupTemplatesContext(_class);
1716             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1717             FinishTemplatesContext(context);
1718          }
1719          type = dataMember.dataType;
1720       }
1721       else if(method)
1722       {
1723          // This is for destination type...
1724          if(!method.dataType)
1725             ProcessMethodType(method);
1726          //DeclareMethod(method);
1727          // method.dataType = ((Symbol)method.symbol)->type;
1728          type = method.dataType;
1729       }
1730
1731       if(ident && ident.next)
1732       {
1733          for(ident = ident.next; ident && type; ident = ident.next)
1734          {
1735             if(type.kind == classType)
1736             {
1737                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1738                if(!dataMember)
1739                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1740                if(dataMember)
1741                   type = dataMember.dataType;
1742             }
1743             else if(type.kind == structType || type.kind == unionType)
1744             {
1745                Type memberType;
1746                for(memberType = type.members.first; memberType; memberType = memberType.next)
1747                {
1748                   if(!strcmp(memberType.name, ident.string))
1749                   {
1750                      type = memberType;
1751                      break;
1752                   }
1753                }
1754             }
1755          }
1756       }
1757
1758       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1759       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1760       {
1761          int id = 0;
1762          ClassTemplateParameter curParam = null;
1763          Class sClass;
1764          for(sClass = _class; sClass; sClass = sClass.base)
1765          {
1766             id = 0;
1767             if(sClass.templateClass) sClass = sClass.templateClass;
1768             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1769             {
1770                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1771                {
1772                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1773                   {
1774                      if(sClass.templateClass) sClass = sClass.templateClass;
1775                      id += sClass.templateParams.count;
1776                   }
1777                   break;
1778                }
1779                id++;
1780             }
1781             if(curParam) break;
1782          }
1783
1784          if(curParam)
1785          {
1786             ClassTemplateArgument arg = _class.templateArgs[id];
1787             if(arg.dataTypeString)
1788             {
1789                bool constant = type.constant;
1790                // FreeType(type);
1791                type = ProcessTypeString(arg.dataTypeString, false);
1792                if(type.kind == classType && constant) type.constant = true;
1793                else if(type.kind == pointerType)
1794                {
1795                   Type t = type.type;
1796                   while(t.kind == pointerType) t = t.type;
1797                   if(constant) t.constant = constant;
1798                }
1799                freeType = true;
1800                if(type && _class.templateClass)
1801                   type.passAsTemplate = true;
1802                if(type)
1803                {
1804                   // type.refCount++;
1805                   /*if(!exp.destType)
1806                   {
1807                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1808                      exp.destType.refCount++;
1809                   }*/
1810                }
1811             }
1812          }
1813       }
1814       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1815       {
1816          Class expClass = type._class.registered;
1817          Class cClass = null;
1818          int paramCount = 0;
1819          int lastParam = -1;
1820
1821          char templateString[1024];
1822          ClassTemplateParameter param;
1823          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1824          for(cClass = expClass; cClass; cClass = cClass.base)
1825          {
1826             int p = 0;
1827             if(cClass.templateClass) cClass = cClass.templateClass;
1828             for(param = cClass.templateParams.first; param; param = param.next)
1829             {
1830                int id = p;
1831                Class sClass;
1832                ClassTemplateArgument arg;
1833                for(sClass = cClass.base; sClass; sClass = sClass.base)
1834                {
1835                   if(sClass.templateClass) sClass = sClass.templateClass;
1836                   id += sClass.templateParams.count;
1837                }
1838                arg = expClass.templateArgs[id];
1839
1840                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1841                {
1842                   ClassTemplateParameter cParam;
1843                   //int p = numParams - sClass.templateParams.count;
1844                   int p = 0;
1845                   Class nextClass;
1846                   if(sClass.templateClass) sClass = sClass.templateClass;
1847
1848                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1849                   {
1850                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1851                      p += nextClass.templateParams.count;
1852                   }
1853
1854                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1855                   {
1856                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1857                      {
1858                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1859                         {
1860                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1861                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1862                            break;
1863                         }
1864                      }
1865                   }
1866                }
1867
1868                {
1869                   char argument[256];
1870                   argument[0] = '\0';
1871                   /*if(arg.name)
1872                   {
1873                      strcat(argument, arg.name.string);
1874                      strcat(argument, " = ");
1875                   }*/
1876                   switch(param.type)
1877                   {
1878                      case expression:
1879                      {
1880                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1881                         char expString[1024];
1882                         OldList * specs = MkList();
1883                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1884                         Expression exp;
1885                         char * string = PrintHexUInt64(arg.expression.ui64);
1886                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1887                         delete string;
1888
1889                         ProcessExpressionType(exp);
1890                         ComputeExpression(exp);
1891                         expString[0] = '\0';
1892                         PrintExpression(exp, expString);
1893                         strcat(argument, expString);
1894                         //delete exp;
1895                         FreeExpression(exp);
1896                         break;
1897                      }
1898                      case identifier:
1899                      {
1900                         strcat(argument, arg.member.name);
1901                         break;
1902                      }
1903                      case TemplateParameterType::type:
1904                      {
1905                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1906                            strcat(argument, arg.dataTypeString);
1907                         break;
1908                      }
1909                   }
1910                   if(argument[0])
1911                   {
1912                      if(paramCount) strcat(templateString, ", ");
1913                      if(lastParam != p - 1)
1914                      {
1915                         strcat(templateString, param.name);
1916                         strcat(templateString, " = ");
1917                      }
1918                      strcat(templateString, argument);
1919                      paramCount++;
1920                      lastParam = p;
1921                   }
1922                   p++;
1923                }
1924             }
1925          }
1926          {
1927             int len = strlen(templateString);
1928             if(templateString[len-1] == '<')
1929                len--;
1930             else
1931             {
1932                if(templateString[len-1] == '>')
1933                   templateString[len++] = ' ';
1934                templateString[len++] = '>';
1935             }
1936             templateString[len++] = '\0';
1937          }
1938          {
1939             Context context = SetupTemplatesContext(_class);
1940             if(freeType) FreeType(type);
1941             type = ProcessTypeString(templateString, false);
1942             freeType = true;
1943             FinishTemplatesContext(context);
1944          }
1945       }
1946
1947       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1948       {
1949          ProcessExpressionType(member.initializer.exp);
1950          if(!member.initializer.exp.expType)
1951          {
1952             if(inCompiler)
1953             {
1954                char expString[10240];
1955                expString[0] = '\0';
1956                PrintExpression(member.initializer.exp, expString);
1957                ChangeCh(expString, '\n', ' ');
1958                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1959             }
1960          }
1961          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1962          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
1963          {
1964             Compiler_Error($"incompatible instance method %s\n", ident.string);
1965          }
1966       }
1967       else if(member.initializer)
1968       {
1969          /*
1970          FreeType(member.exp.destType);
1971          member.exp.destType = type;
1972          if(member.exp.destType)
1973             member.exp.destType.refCount++;
1974          ProcessExpressionType(member.exp);
1975          */
1976
1977          ProcessInitializer(member.initializer, type);
1978       }
1979       if(freeType) FreeType(type);
1980    }
1981    else
1982    {
1983       if(_class && _class.type == unitClass)
1984       {
1985          if(member.initializer)
1986          {
1987             /*
1988             FreeType(member.exp.destType);
1989             member.exp.destType = MkClassType(_class.fullName);
1990             ProcessExpressionType(member.initializer, type);
1991             */
1992             Type type = MkClassType(_class.fullName);
1993             ProcessInitializer(member.initializer, type);
1994             FreeType(type);
1995          }
1996       }
1997       else
1998       {
1999          if(member.initializer)
2000          {
2001             //ProcessExpressionType(member.exp);
2002             ProcessInitializer(member.initializer, null);
2003          }
2004          if(ident)
2005          {
2006             if(method)
2007             {
2008                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2009             }
2010             else if(_class)
2011             {
2012                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2013                if(inCompiler)
2014                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2015             }
2016          }
2017          else if(_class)
2018             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2019       }
2020    }
2021 }
2022
2023 void ProcessInstantiationType(Instantiation inst)
2024 {
2025    yylloc = inst.loc;
2026    if(inst._class)
2027    {
2028       MembersInit members;
2029       Symbol classSym;
2030       Class _class;
2031
2032       classSym = inst._class.symbol;
2033       _class = classSym ? classSym.registered : null;
2034
2035       if(!_class || _class.type != noHeadClass)
2036          DeclareStruct(curExternal, inst._class.name, false, true);
2037
2038       afterExternal = afterExternal ? afterExternal : curExternal;
2039
2040       if(inst.exp)
2041          ProcessExpressionType(inst.exp);
2042
2043       inst.isConstant = true;
2044       if(inst.members)
2045       {
2046          DataMember curMember = null;
2047          Class curClass = null;
2048          DataMember subMemberStack[256];
2049          int subMemberStackPos = 0;
2050
2051          for(members = inst.members->first; members; members = members.next)
2052          {
2053             switch(members.type)
2054             {
2055                case methodMembersInit:
2056                {
2057                   char name[1024];
2058                   static uint instMethodID = 0;
2059                   External external = curExternal;
2060                   Context context = curContext;
2061                   Declarator declarator = members.function.declarator;
2062                   Identifier nameID = GetDeclId(declarator);
2063                   char * unmangled = nameID ? nameID.string : null;
2064                   Expression exp;
2065                   External createdExternal = null;
2066
2067                   if(inCompiler)
2068                   {
2069                      char number[16];
2070                      strcpy(name, "__ecereInstMeth_");
2071                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2072                      strcat(name, "_");
2073                      strcat(name, nameID.string);
2074                      strcat(name, "_");
2075                      sprintf(number, "_%08d", instMethodID++);
2076                      strcat(name, number);
2077                      nameID.string = CopyString(name);
2078                   }
2079
2080                   // Do modifications here...
2081                   if(declarator)
2082                   {
2083                      Symbol symbol = declarator.symbol;
2084                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2085
2086                      if(method && method.type == virtualMethod)
2087                      {
2088                         symbol.method = method;
2089                         ProcessMethodType(method);
2090
2091                         if(!symbol.type.thisClass)
2092                         {
2093                            if(method.dataType.thisClass && currentClass &&
2094                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2095                            {
2096                               if(!currentClass.symbol)
2097                                  currentClass.symbol = FindClass(currentClass.fullName);
2098                               symbol.type.thisClass = currentClass.symbol;
2099                            }
2100                            else
2101                            {
2102                               if(!_class.symbol)
2103                                  _class.symbol = FindClass(_class.fullName);
2104                               symbol.type.thisClass = _class.symbol;
2105                            }
2106                         }
2107                         DeclareType(curExternal, symbol.type, true, true);
2108
2109                      }
2110                      else if(classSym)
2111                      {
2112                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2113                            unmangled, classSym.string);
2114                      }
2115                   }
2116
2117                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2118
2119                   if(nameID)
2120                   {
2121                      FreeSpecifier(nameID._class);
2122                      nameID._class = null;
2123                   }
2124
2125                   curExternal = createdExternal;
2126                   if(inCompiler)
2127                   {
2128                      if(createdExternal.function)
2129                         ProcessFunction(createdExternal.function);
2130                   }
2131                   else if(declarator)
2132                   {
2133                      curExternal = declarator.symbol.pointerExternal;
2134                      ProcessFunction((FunctionDefinition)members.function);
2135                   }
2136                   curExternal = external;
2137                   curContext = context;
2138
2139                   if(inCompiler)
2140                   {
2141                      FreeClassFunction(members.function);
2142
2143                      // In this pass, turn this into a MemberInitData
2144                      exp = QMkExpId(name);
2145                      members.type = dataMembersInit;
2146                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2147
2148                      delete unmangled;
2149                   }
2150                   break;
2151                }
2152                case dataMembersInit:
2153                {
2154                   if(members.dataMembers && classSym)
2155                   {
2156                      MemberInit member;
2157                      Location oldyyloc = yylloc;
2158                      for(member = members.dataMembers->first; member; member = member.next)
2159                      {
2160                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2161                         if(member.initializer && !member.initializer.isConstant)
2162                            inst.isConstant = false;
2163                      }
2164                      yylloc = oldyyloc;
2165                   }
2166                   break;
2167                }
2168             }
2169          }
2170       }
2171    }
2172 }
2173
2174 void DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2175 {
2176    _DeclareType(neededFor, type, needDereference, forFunctionDef, false);
2177 }
2178
2179 void DeclareTypeForwardDeclare(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2180 {
2181    _DeclareType(neededFor, type, needDereference, forFunctionDef, true);
2182 }
2183
2184 static void _DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef, bool fwdDecl)
2185 {
2186    if(inCompiler)
2187    {
2188       if(type.kind == functionType)
2189       {
2190          Type param;
2191          for(param = type.params.first; param; param = param.next)
2192             _DeclareType(neededFor, param, forFunctionDef, false, fwdDecl);
2193          _DeclareType(neededFor, type.returnType, forFunctionDef, false, fwdDecl);
2194       }
2195       else if(type.kind == pointerType)
2196          _DeclareType(neededFor, type.type, false, false, fwdDecl);
2197       else if(type.kind == classType)
2198       {
2199          Class c = type._class.registered;
2200          _DeclareStruct(neededFor, c ? c.fullName : "ecere::com::Instance", c ? c.type == noHeadClass : false, needDereference && c && c.type == structClass, fwdDecl);
2201       }
2202       else if(type.kind == structType || type.kind == unionType)
2203       {
2204          Type member;
2205          for(member = type.members.first; member; member = member.next)
2206             _DeclareType(neededFor, member, needDereference, forFunctionDef, fwdDecl);
2207       }
2208       else if(type.kind == arrayType)
2209          _DeclareType(neededFor, type.arrayType, true, false, fwdDecl);
2210    }
2211 }
2212
2213 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2214 {
2215    ClassTemplateArgument * arg = null;
2216    int id = 0;
2217    ClassTemplateParameter curParam = null;
2218    Class sClass;
2219    for(sClass = _class; sClass; sClass = sClass.base)
2220    {
2221       id = 0;
2222       if(sClass.templateClass) sClass = sClass.templateClass;
2223       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2224       {
2225          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2226          {
2227             for(sClass = sClass.base; sClass; sClass = sClass.base)
2228             {
2229                if(sClass.templateClass) sClass = sClass.templateClass;
2230                id += sClass.templateParams.count;
2231             }
2232             break;
2233          }
2234          id++;
2235       }
2236       if(curParam) break;
2237    }
2238    if(curParam)
2239    {
2240       arg = &_class.templateArgs[id];
2241       if(arg && param.type == type)
2242          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2243    }
2244    return arg;
2245 }
2246
2247 public Context SetupTemplatesContext(Class _class)
2248 {
2249    Context context = PushContext();
2250    context.templateTypesOnly = true;
2251    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2252    {
2253       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2254       for(; param; param = param.next)
2255       {
2256          if(param.type == type && param.identifier)
2257          {
2258             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2259             curContext.templateTypes.Add((BTNode)type);
2260          }
2261       }
2262    }
2263    else if(_class)
2264    {
2265       Class sClass;
2266       for(sClass = _class; sClass; sClass = sClass.base)
2267       {
2268          ClassTemplateParameter p;
2269          for(p = sClass.templateParams.first; p; p = p.next)
2270          {
2271             //OldList * specs = MkList();
2272             //Declarator decl = null;
2273             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2274             if(p.type == type)
2275             {
2276                TemplateParameter param = p.param;
2277                TemplatedType type;
2278                if(!param)
2279                {
2280                   // ADD DATA TYPE HERE...
2281                   p.param = param = TemplateParameter
2282                   {
2283                      identifier = MkIdentifier(p.name), type = p.type,
2284                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2285                   };
2286                }
2287                type = TemplatedType { key = (uintptr)p.name, param = param };
2288                curContext.templateTypes.Add((BTNode)type);
2289             }
2290          }
2291       }
2292    }
2293    return context;
2294 }
2295
2296 public void FinishTemplatesContext(Context context)
2297 {
2298    PopContext(context);
2299    FreeContext(context);
2300    delete context;
2301 }
2302
2303 public void ProcessMethodType(Method method)
2304 {
2305    if(!method.dataType)
2306    {
2307       Context context = SetupTemplatesContext(method._class);
2308
2309       method.dataType = ProcessTypeString(method.dataTypeString, false);
2310
2311       FinishTemplatesContext(context);
2312
2313       if(method.type != virtualMethod && method.dataType)
2314       {
2315          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2316          {
2317             if(!method._class.symbol)
2318                method._class.symbol = FindClass(method._class.fullName);
2319             method.dataType.thisClass = method._class.symbol;
2320          }
2321       }
2322
2323       // Why was this commented out? Working fine without now...
2324
2325       /*
2326       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2327          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2328          */
2329    }
2330
2331    /*
2332    if(type)
2333    {
2334       char * par = strstr(type, "(");
2335       char * classOp = null;
2336       int classOpLen = 0;
2337       if(par)
2338       {
2339          int c;
2340          for(c = par-type-1; c >= 0; c++)
2341          {
2342             if(type[c] == ':' && type[c+1] == ':')
2343             {
2344                classOp = type + c - 1;
2345                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2346                {
2347                   classOp--;
2348                   classOpLen++;
2349                }
2350                break;
2351             }
2352             else if(!isspace(type[c]))
2353                break;
2354          }
2355       }
2356       if(classOp)
2357       {
2358          char temp[1024];
2359          int typeLen = strlen(type);
2360          memcpy(temp, classOp, classOpLen);
2361          temp[classOpLen] = '\0';
2362          if(temp[0])
2363             _class = eSystem_FindClass(module, temp);
2364          else
2365             _class = null;
2366          method.dataTypeString = new char[typeLen - classOpLen + 1];
2367          memcpy(method.dataTypeString, type, classOp - type);
2368          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2369       }
2370       else
2371          method.dataTypeString = type;
2372    }
2373    */
2374 }
2375
2376
2377 public void ProcessPropertyType(Property prop)
2378 {
2379    if(!prop.dataType)
2380    {
2381       Context context = SetupTemplatesContext(prop._class);
2382       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2383       FinishTemplatesContext(context);
2384    }
2385 }
2386
2387 public void DeclareMethod(External neededFor, Method method, const char * name)
2388 {
2389    Symbol symbol = method.symbol;
2390    if(!symbol || (!symbol.pointerExternal && (!symbol.methodCodeExternal || method.type == virtualMethod)))
2391    {
2392       bool dllImport = false;
2393
2394       if(!method.dataType)
2395          method.dataType = ProcessTypeString(method.dataTypeString, false);
2396
2397       //if(!symbol || symbol._import || method.type == virtualMethod)
2398       {
2399          if(!symbol || method.type == virtualMethod)
2400          {
2401             Symbol classSym;
2402             if(!method._class.symbol)
2403                method._class.symbol = FindClass(method._class.fullName);
2404             classSym = method._class.symbol;
2405             if(!classSym._import)
2406             {
2407                ModuleImport module;
2408
2409                if(method._class.module && method._class.module.name)
2410                   module = FindModule(method._class.module);
2411                else
2412                   module = mainModule;
2413                classSym._import = ClassImport
2414                {
2415                   name = CopyString(method._class.fullName);
2416                   isRemote = method._class.isRemote;
2417                };
2418                module.classes.Add(classSym._import);
2419             }
2420             if(!symbol)
2421             {
2422                symbol = method.symbol = Symbol { };
2423             }
2424             if(!symbol._import)
2425             {
2426                symbol._import = (ClassImport)MethodImport
2427                {
2428                   name = CopyString(method.name);
2429                   isVirtual = method.type == virtualMethod;
2430                };
2431                classSym._import.methods.Add(symbol._import);
2432             }
2433             if(!symbol)
2434             {
2435                symbol.type = method.dataType;
2436                if(symbol.type) symbol.type.refCount++;
2437             }
2438          }
2439          if(!method.dataType.dllExport)
2440          {
2441             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2442                dllImport = true;
2443          }
2444       }
2445
2446       if(inCompiler)
2447       {
2448          // We need a declaration here :)
2449          Declaration decl;
2450          OldList * specifiers, * declarators;
2451          Declarator d;
2452          Declarator funcDecl;
2453          External external;
2454
2455          specifiers = MkList();
2456          declarators = MkList();
2457
2458          if(dllImport)
2459             ListAdd(specifiers, MkSpecifier(EXTERN));
2460          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2461             ListAdd(specifiers, MkSpecifier(STATIC));
2462
2463          if(method.type == virtualMethod)
2464          {
2465             ListAdd(specifiers, MkSpecifier(INT));
2466             d = MkDeclaratorIdentifier(MkIdentifier(name));
2467          }
2468          else
2469          {
2470             d = MkDeclaratorIdentifier(MkIdentifier(name));
2471             if(dllImport)
2472                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2473             {
2474                Context context = SetupTemplatesContext(method._class);
2475                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2476                FinishTemplatesContext(context);
2477             }
2478             funcDecl = GetFuncDecl(d);
2479
2480             if(dllImport)
2481             {
2482                Specifier spec, next;
2483                for(spec = specifiers->first; spec; spec = next)
2484                {
2485                   next = spec.next;
2486                   if(spec.type == extendedSpecifier)
2487                   {
2488                      specifiers->Remove(spec);
2489                      FreeSpecifier(spec);
2490                   }
2491                }
2492             }
2493
2494             // Add this parameter if not a static method
2495             if(method.dataType && !method.dataType.staticMethod)
2496             {
2497                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2498                {
2499                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2500                   TypeName thisParam = MkTypeName(MkListOne(
2501                      MkSpecifierName(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2502                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2503                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2504                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2505
2506                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2507                   {
2508                      TypeName param = funcDecl.function.parameters->first;
2509                      funcDecl.function.parameters->Remove(param);
2510                      FreeTypeName(param);
2511                   }
2512
2513                   if(!funcDecl.function.parameters)
2514                      funcDecl.function.parameters = MkList();
2515                   funcDecl.function.parameters->Insert(null, thisParam);
2516                }
2517             }
2518          }
2519          ProcessDeclarator(d, true);
2520
2521          ListAdd(declarators, MkInitDeclarator(d, null));
2522
2523          decl = MkDeclaration(specifiers, declarators);
2524
2525          ReplaceThisClassSpecifiers(specifiers, method._class);
2526
2527          external = MkExternalDeclaration(decl);
2528          external.symbol = symbol;
2529          symbol.pointerExternal = external;
2530          ast->Add(external);
2531          DeclareStruct(external, method._class.fullName, true, true);
2532          if(method.dataType)
2533             DeclareType(external, method.dataType, true, true);
2534       }
2535    }
2536    if(inCompiler && neededFor)
2537    {
2538       External external = symbol.pointerExternal ? symbol.pointerExternal : symbol.methodCodeExternal;
2539       neededFor.CreateUniqueEdge(external, external.type == functionExternal);
2540    }
2541 }
2542
2543 char * ReplaceThisClass(Class _class)
2544 {
2545    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2546    {
2547       bool first = true;
2548       int p = 0;
2549       ClassTemplateParameter param;
2550       int lastParam = -1;
2551
2552       char className[1024];
2553       strcpy(className, _class.fullName);
2554       for(param = _class.templateParams.first; param; param = param.next)
2555       {
2556          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2557          {
2558             if(first) strcat(className, "<");
2559             if(!first) strcat(className, ", ");
2560             if(lastParam + 1 != p)
2561             {
2562                strcat(className, param.name);
2563                strcat(className, " = ");
2564             }
2565             strcat(className, param.name);
2566             first = false;
2567             lastParam = p;
2568          }
2569          p++;
2570       }
2571       if(!first)
2572       {
2573          int len = strlen(className);
2574          if(className[len-1] == '>') className[len++] = ' ';
2575          className[len++] = '>';
2576          className[len++] = '\0';
2577       }
2578       return CopyString(className);
2579    }
2580    else
2581       return CopyString(_class.fullName);
2582 }
2583
2584 Type ReplaceThisClassType(Class _class)
2585 {
2586    Type type;
2587    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2588    {
2589       bool first = true;
2590       int p = 0;
2591       ClassTemplateParameter param;
2592       int lastParam = -1;
2593       char className[1024];
2594       strcpy(className, _class.fullName);
2595
2596       for(param = _class.templateParams.first; param; param = param.next)
2597       {
2598          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2599          {
2600             if(first) strcat(className, "<");
2601             if(!first) strcat(className, ", ");
2602             if(lastParam + 1 != p)
2603             {
2604                strcat(className, param.name);
2605                strcat(className, " = ");
2606             }
2607             strcat(className, param.name);
2608             first = false;
2609             lastParam = p;
2610          }
2611          p++;
2612       }
2613       if(!first)
2614       {
2615          int len = strlen(className);
2616          if(className[len-1] == '>') className[len++] = ' ';
2617          className[len++] = '>';
2618          className[len++] = '\0';
2619       }
2620       type = MkClassType(className);
2621       //type = ProcessTypeString(className, false);
2622    }
2623    else
2624    {
2625       type = MkClassType(_class.fullName);
2626       //type = ProcessTypeString(_class.fullName, false);
2627    }
2628    //type.wasThisClass = true;
2629    return type;
2630 }
2631
2632 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2633 {
2634    if(specs != null && _class)
2635    {
2636       Specifier spec;
2637       for(spec = specs.first; spec; spec = spec.next)
2638       {
2639          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2640          {
2641             spec.type = nameSpecifier;
2642             spec.name = ReplaceThisClass(_class);
2643             spec.symbol = FindClass(spec.name); //_class.symbol;
2644          }
2645       }
2646    }
2647 }
2648
2649 // Returns imported or not
2650 bool DeclareFunction(External neededFor, GlobalFunction function, char * name)
2651 {
2652    Symbol symbol = function.symbol;
2653    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2654    if(!symbol || !symbol.pointerExternal)
2655    {
2656       bool imported = false;
2657       bool dllImport = false;
2658
2659       if(!function.dataType)
2660       {
2661          function.dataType = ProcessTypeString(function.dataTypeString, false);
2662          if(!function.dataType.thisClass)
2663             function.dataType.staticMethod = true;
2664       }
2665
2666       if(inCompiler)
2667       {
2668          if(!symbol)
2669          {
2670             ModuleImport module = FindModule(function.module);
2671             // WARNING: This is not added anywhere...
2672             symbol = function.symbol = Symbol {  };
2673
2674             if(module.name)
2675             {
2676                if(!function.dataType.dllExport)
2677                {
2678                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2679                   module.functions.Add(symbol._import);
2680                }
2681             }
2682             // Set the symbol type
2683             {
2684                symbol.type = ProcessTypeString(function.dataTypeString, false);
2685                if(!symbol.type.thisClass)
2686                   symbol.type.staticMethod = true;
2687             }
2688          }
2689          imported = symbol._import ? true : false;
2690          if(imported && function.module != privateModule && function.module.importType != staticImport)
2691             dllImport = true;
2692       }
2693
2694       if(inCompiler)
2695       {
2696          // TOCHECK: What's with the functionExternal check here? Is it Edge breaking / forward declaration?
2697          //if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2698          {
2699             // We need a declaration here :)
2700             Declaration decl;
2701             OldList * specifiers, * declarators;
2702             Declarator d;
2703             Declarator funcDecl;
2704             External external;
2705
2706             specifiers = MkList();
2707             declarators = MkList();
2708
2709             ListAdd(specifiers, MkSpecifier(EXTERN));
2710
2711             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2712             if(dllImport)
2713                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2714
2715             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2716             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2717             if(function.module.importType == staticImport)
2718             {
2719                Specifier spec;
2720                for(spec = specifiers->first; spec; spec = spec.next)
2721                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2722                   {
2723                      specifiers->Remove(spec);
2724                      FreeSpecifier(spec);
2725                      break;
2726                   }
2727             }
2728
2729             funcDecl = GetFuncDecl(d);
2730
2731             // Make sure we don't have empty parameter declarations for static methods...
2732             if(funcDecl && !funcDecl.function.parameters)
2733             {
2734                funcDecl.function.parameters = MkList();
2735                funcDecl.function.parameters->Insert(null,
2736                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2737             }
2738
2739             ListAdd(declarators, MkInitDeclarator(d, null));
2740
2741             {
2742                Context oldCtx = curContext;
2743                curContext = globalContext;
2744                decl = MkDeclaration(specifiers, declarators);
2745                curContext = oldCtx;
2746             }
2747
2748             // Keep a different symbol for the function definition than the declaration...
2749             /* Note: This should be handled by the edge breaking...
2750             if(symbol.pointerExternal && symbol.pointerExternal.type == functionExternal)
2751             {
2752                Symbol functionSymbol { };
2753                // Copy symbol
2754                {
2755                   *functionSymbol = *symbol;
2756                   functionSymbol.string = CopyString(symbol.string);
2757                   if(functionSymbol.type)
2758                      functionSymbol.type.refCount++;
2759                }
2760
2761                excludedSymbols->Add(functionSymbol);
2762
2763                symbol.pointerExternal.symbol = functionSymbol;
2764             }
2765             */
2766             external = MkExternalDeclaration(decl);
2767             ast->Add(external);
2768             external.symbol = symbol;
2769             symbol.pointerExternal = external;
2770
2771             DeclareType(external, function.dataType, true, true);
2772          }
2773       }
2774    }
2775    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2776       neededFor.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
2777    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2778 }
2779
2780 void DeclareGlobalData(External neededFor, GlobalData data)
2781 {
2782    Symbol symbol = data.symbol;
2783    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2784    if(!symbol || !symbol.pointerExternal)
2785    {
2786       if(inCompiler)
2787       {
2788          if(!symbol)
2789             symbol = data.symbol = Symbol { };
2790       }
2791       if(!data.dataType)
2792          data.dataType = ProcessTypeString(data.dataTypeString, false);
2793
2794       if(inCompiler)
2795       {
2796          // We need a declaration here :)
2797          Declaration decl;
2798          OldList * specifiers, * declarators;
2799          Declarator d;
2800          External external;
2801
2802          specifiers = MkList();
2803          declarators = MkList();
2804
2805          ListAdd(specifiers, MkSpecifier(EXTERN));
2806          d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2807          d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2808
2809          ListAdd(declarators, MkInitDeclarator(d, null));
2810
2811          decl = MkDeclaration(specifiers, declarators);
2812          external = MkExternalDeclaration(decl);
2813          if(curExternal)
2814             ast->Insert(curExternal.prev, external);
2815          external.symbol = symbol;
2816          symbol.pointerExternal = external;
2817
2818          DeclareType(external, data.dataType, true, true);
2819       }
2820    }
2821    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2822       neededFor.CreateUniqueEdge(symbol.pointerExternal, false);
2823 }
2824
2825 class Conversion : struct
2826 {
2827    Conversion prev, next;
2828    Property convert;
2829    bool isGet;
2830    Type resultType;
2831 };
2832
2833 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
2834 {
2835    bool status = true;
2836    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
2837       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
2838    {
2839       Class sourceClass = source.kind == classType ? source._class.registered : null;
2840       Class destClass = dest.kind == classType ? dest._class.registered : null;
2841       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
2842          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
2843       {
2844          Type sourceType = source, destType = dest;
2845          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
2846          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
2847          if(!destType.constant && sourceType.constant)
2848          {
2849             status = false;
2850             if(warn)
2851                Compiler_Warning($"discarding const qualifier\n");
2852          }
2853       }
2854    }
2855    return status;
2856 }
2857
2858 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
2859                        bool isConversionExploration, bool warnConst)
2860 {
2861    if(source && dest)
2862    {
2863       if(warnConst)
2864          CheckConstCompatibility(source, dest, true);
2865       // Property convert;
2866
2867       if(source.kind == templateType && dest.kind != templateType)
2868       {
2869          Type type = ProcessTemplateParameterType(source.templateParameter);
2870          if(type) source = type;
2871       }
2872
2873       if(dest.kind == templateType && source.kind != templateType)
2874       {
2875          Type type = ProcessTemplateParameterType(dest.templateParameter);
2876          if(type) dest = type;
2877       }
2878
2879       if(dest.classObjectType == typedObject && dest.kind != functionType)
2880       {
2881          if(source.classObjectType != anyObject)
2882             return true;
2883          else
2884          {
2885             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
2886             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
2887             {
2888                return true;
2889             }
2890          }
2891       }
2892       else
2893       {
2894          if(source.kind != functionType && source.classObjectType == anyObject)
2895             return true;
2896          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
2897             return true;
2898       }
2899
2900       if((dest.kind == structType && source.kind == structType) ||
2901          (dest.kind == unionType && source.kind == unionType))
2902       {
2903          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
2904              (source.members.first && source.members.first == dest.members.first))
2905             return true;
2906       }
2907
2908       if(dest.kind == ellipsisType && source.kind != voidType)
2909          return true;
2910
2911       if(dest.kind == pointerType && dest.type.kind == voidType &&
2912          ((source.kind == classType && (!source._class || !source._class.registered || source._class.registered.type == structClass || source._class.registered.type == normalClass || source._class.registered.type == noHeadClass || source._class.registered.type == systemClass))
2913          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
2914
2915          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
2916
2917          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
2918          return true;
2919       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
2920          ((dest.kind == classType && (!dest._class || !dest._class.registered || dest._class.registered.type == structClass || dest._class.registered.type == normalClass || dest._class.registered.type == noHeadClass || dest._class.registered.type == systemClass))
2921          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
2922          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
2923
2924          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
2925          return true;
2926
2927       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
2928       {
2929          if(source._class.registered && source._class.registered.type == unitClass)
2930          {
2931             if(conversions != null)
2932             {
2933                if(source._class.registered == dest._class.registered)
2934                   return true;
2935             }
2936             else
2937             {
2938                Class sourceBase, destBase;
2939                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
2940                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
2941                if(sourceBase == destBase)
2942                   return true;
2943             }
2944          }
2945          // Don't match enum inheriting from other enum if resolving enumeration values
2946          // TESTING: !dest.classObjectType
2947          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
2948             (enumBaseType ||
2949                (!source._class.registered || source._class.registered.type != enumClass) ||
2950                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
2951             return true;
2952          else
2953          {
2954             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
2955             if(enumBaseType &&
2956                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
2957                ((source._class && source._class.registered && source._class.registered.type != enumClass) || source.kind == classType)) // Added this here for a base enum to be acceptable for a derived enum (#139)
2958             {
2959                if(eClass_IsDerived(dest._class.registered, source._class.registered))
2960                {
2961                   return true;
2962                }
2963             }
2964          }
2965       }
2966
2967       // JUST ADDED THIS...
2968       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
2969          return true;
2970
2971       if(doConversion)
2972       {
2973          // Just added this for Straight conversion of ColorAlpha => Color
2974          if(source.kind == classType)
2975          {
2976             Class _class;
2977             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
2978             {
2979                Property convert;
2980                for(convert = _class.conversions.first; convert; convert = convert.next)
2981                {
2982                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
2983                   {
2984                      Conversion after = (conversions != null) ? conversions.last : null;
2985
2986                      if(!convert.dataType)
2987                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
2988                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
2989                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
2990                         MatchTypes(convert.dataType, dest, conversions, null, null,
2991                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
2992                               convert.dataType.kind == classType, false, true, warnConst))
2993                      {
2994                         if(!conversions && !convert.Get)
2995                            return true;
2996                         else if(conversions != null)
2997                         {
2998                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
2999                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3000                               (dest.kind != classType || dest._class.registered != _class.base))
3001                               return true;
3002                            else
3003                            {
3004                               Conversion conv { convert = convert, isGet = true };
3005                               // conversions.Add(conv);
3006                               conversions.Insert(after, conv);
3007
3008                               return true;
3009                            }
3010                         }
3011                      }
3012                   }
3013                }
3014             }
3015          }
3016
3017          // MOVING THIS??
3018
3019          if(dest.kind == classType)
3020          {
3021             Class _class;
3022             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3023             {
3024                Property convert;
3025                for(convert = _class.conversions.first; convert; convert = convert.next)
3026                {
3027                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3028                   {
3029                      Type constType = null;
3030                      bool success = false;
3031                      // Conversion after = (conversions != null) ? conversions.last : null;
3032
3033                      if(!convert.dataType)
3034                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3035
3036                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3037                      {
3038                         Type ptrType { };
3039                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3040                         CopyTypeInto(ptrType, convert.dataType.type);
3041                         ptrType.constant = true;
3042                      }
3043
3044                      // Just added this equality check to prevent recursion.... Make it safer?
3045                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3046                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3047                      {
3048                         if(!conversions && !convert.Set)
3049                            success = true;
3050                         else if(conversions != null)
3051                         {
3052                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3053                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3054                               (source.kind != classType || source._class.registered != _class.base))
3055                               success = true;
3056                            else
3057                            {
3058                               // *** Testing this! ***
3059                               Conversion conv { convert = convert };
3060                               conversions.Add(conv);
3061                               //conversions.Insert(after, conv);
3062                               success = true;
3063                            }
3064                         }
3065                      }
3066                      if(constType)
3067                         FreeType(constType);
3068                      if(success)
3069                         return true;
3070                   }
3071                }
3072             }
3073             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3074             {
3075                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3076                   (source.kind != classType || source._class.registered.type != structClass))
3077                   return true;
3078             }*/
3079
3080             // TESTING THIS... IS THIS OK??
3081             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3082             {
3083                if(!dest._class.registered.dataType)
3084                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3085                // Only support this for classes...
3086                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3087                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3088                {
3089                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3090                   {
3091                      return true;
3092                   }
3093                }
3094             }
3095          }
3096
3097          // Moved this lower
3098          if(source.kind == classType)
3099          {
3100             Class _class;
3101             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3102             {
3103                Property convert;
3104                for(convert = _class.conversions.first; convert; convert = convert.next)
3105                {
3106                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3107                   {
3108                      Conversion after = (conversions != null) ? conversions.last : null;
3109
3110                      if(!convert.dataType)
3111                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3112                      if(convert.dataType != source &&
3113                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3114                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3115                      {
3116                         if(!conversions && !convert.Get)
3117                            return true;
3118                         else if(conversions != null)
3119                         {
3120                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3121                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3122                               (dest.kind != classType || dest._class.registered != _class.base))
3123                               return true;
3124                            else
3125                            {
3126                               Conversion conv { convert = convert, isGet = true };
3127
3128                               // conversions.Add(conv);
3129                               conversions.Insert(after, conv);
3130                               return true;
3131                            }
3132                         }
3133                      }
3134                   }
3135                }
3136             }
3137
3138             // TESTING THIS... IS THIS OK??
3139             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3140             {
3141                if(!source._class.registered.dataType)
3142                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3143                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3144                {
3145                   if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, source._class.registered.dataType.kind == classType, source._class.registered.dataType.kind == classType, false, false, warnConst))
3146                      return true;
3147                   // For bool to be accepted by byte, short, etc.
3148                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3149                      return true;
3150                }
3151             }
3152          }
3153       }
3154
3155       if(source.kind == classType || source.kind == subClassType)
3156          ;
3157       else if(dest.kind == source.kind &&
3158          (dest.kind != structType && dest.kind != unionType &&
3159           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3160           return true;
3161       // RECENTLY ADDED THESE
3162       else if(dest.kind == doubleType && source.kind == floatType)
3163          return true;
3164       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3165          return true;
3166       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3167          return true;
3168       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3169          return true;
3170       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3171          return true;
3172       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3173          return true;
3174       else if(source.kind == enumType &&
3175          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3176           return true;
3177       else if(dest.kind == enumType && !isConversionExploration &&
3178          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3179           return true;
3180       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3181               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3182       {
3183          Type paramSource, paramDest;
3184
3185          if(dest.kind == methodType)
3186             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3187          if(source.kind == methodType)
3188             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3189
3190          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3191          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3192          if(dest.kind == methodType)
3193             dest = dest.method.dataType;
3194          if(source.kind == methodType)
3195             source = source.method.dataType;
3196
3197          paramSource = source.params.first;
3198          if(paramSource && paramSource.kind == voidType) paramSource = null;
3199          paramDest = dest.params.first;
3200          if(paramDest && paramDest.kind == voidType) paramDest = null;
3201
3202
3203          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3204             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3205          {
3206             // Source thisClass must be derived from destination thisClass
3207             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3208                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3209             {
3210                if(paramDest && paramDest.kind == classType)
3211                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3212                else
3213                   Compiler_Error($"method class should not take an object\n");
3214                return false;
3215             }
3216             paramDest = paramDest.next;
3217          }
3218          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3219          {
3220             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3221             {
3222                if(dest.thisClass)
3223                {
3224                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3225                   {
3226                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3227                      return false;
3228                   }
3229                }
3230                else
3231                {
3232                   // THIS WAS BACKWARDS:
3233                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3234                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3235                   {
3236                      if(owningClassDest)
3237                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3238                      else
3239                         Compiler_Error($"overriding class expected to be derived from method class\n");
3240                      return false;
3241                   }
3242                }
3243                paramSource = paramSource.next;
3244             }
3245             else
3246             {
3247                if(dest.thisClass)
3248                {
3249                   // Source thisClass must be derived from destination thisClass
3250                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3251                   {
3252                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3253                      return false;
3254                   }
3255                }
3256                else
3257                {
3258                   // THIS WAS BACKWARDS TOO??
3259                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3260                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3261                   {
3262                      //if(owningClass)
3263                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3264                      //else
3265                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3266                      return false;
3267                   }
3268                }
3269             }
3270          }
3271
3272
3273          // Source return type must be derived from destination return type
3274          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3275          {
3276             Compiler_Warning($"incompatible return type for function\n");
3277             return false;
3278          }
3279          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3280          else
3281             CheckConstCompatibility(dest.returnType, source.returnType, true);
3282
3283          // Check parameters
3284
3285          for(; paramDest; paramDest = paramDest.next)
3286          {
3287             if(!paramSource)
3288             {
3289                //Compiler_Warning($"not enough parameters\n");
3290                Compiler_Error($"not enough parameters\n");
3291                return false;
3292             }
3293             {
3294                Type paramDestType = paramDest;
3295                Type paramSourceType = paramSource;
3296                Type type = paramDestType;
3297
3298                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3299                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3300                   paramSource.kind != templateType)
3301                {
3302                   int id = 0;
3303                   ClassTemplateParameter curParam = null;
3304                   Class sClass;
3305                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3306                   {
3307                      id = 0;
3308                      if(sClass.templateClass) sClass = sClass.templateClass;
3309                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3310                      {
3311                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3312                         {
3313                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3314                            {
3315                               if(sClass.templateClass) sClass = sClass.templateClass;
3316                               id += sClass.templateParams.count;
3317                            }
3318                            break;
3319                         }
3320                         id++;
3321                      }
3322                      if(curParam) break;
3323                   }
3324
3325                   if(curParam)
3326                   {
3327                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3328                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3329                   }
3330                }
3331
3332                // paramDest must be derived from paramSource
3333                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3334                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3335                {
3336                   char type[1024];
3337                   type[0] = 0;
3338                   PrintType(paramDest, type, false, true);
3339                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3340
3341                   if(paramDestType != paramDest)
3342                      FreeType(paramDestType);
3343                   return false;
3344                }
3345                if(paramDestType != paramDest)
3346                   FreeType(paramDestType);
3347             }
3348
3349             paramSource = paramSource.next;
3350          }
3351          if(paramSource)
3352          {
3353             Compiler_Error($"too many parameters\n");
3354             return false;
3355          }
3356          return true;
3357       }
3358       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3359       {
3360          return true;
3361       }
3362       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3363          (source.kind == arrayType || source.kind == pointerType))
3364       {
3365          // Pointers to pointer is incompatible with non normal/nohead classes
3366          if(!(dest.type && dest.type.kind == pointerType && source.type.kind == classType && source.type._class &&
3367             source.type._class.registered && (source.type._class.registered.type != normalClass && source.type._class.registered.type != noHeadClass) && !source.type.byReference))
3368          {
3369             ComputeTypeSize(source.type);
3370             ComputeTypeSize(dest.type);
3371             if(source.type.size == dest.type.size && MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3372                return true;
3373          }
3374       }
3375    }
3376    return false;
3377 }
3378
3379 static void FreeConvert(Conversion convert)
3380 {
3381    if(convert.resultType)
3382       FreeType(convert.resultType);
3383 }
3384
3385 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3386                               char * string, OldList conversions)
3387 {
3388    BTNamedLink link;
3389
3390    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3391    {
3392       Class _class = link.data;
3393       if(_class.type == enumClass)
3394       {
3395          OldList converts { };
3396          Type type { };
3397          type.kind = classType;
3398
3399          if(!_class.symbol)
3400             _class.symbol = FindClass(_class.fullName);
3401          type._class = _class.symbol;
3402
3403          if(MatchTypes(type, dest, &converts, null, null, dest.kind != classType || !dest._class || strcmp(dest._class.string, "bool"),
3404                false, false, false, false))
3405          {
3406             NamedLink64 value;
3407             Class enumClass = eSystem_FindClass(privateModule, "enum");
3408             if(enumClass)
3409             {
3410                Class baseClass;
3411                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3412                {
3413                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3414                   for(value = e.values.first; value; value = value.next)
3415                   {
3416                      if(!strcmp(value.name, string))
3417                         break;
3418                   }
3419                   if(value)
3420                   {
3421                      FreeType(sourceExp.expType);
3422
3423                      sourceExp.isConstant = true;
3424                      sourceExp.expType = MkClassType(baseClass.fullName);
3425                      if(inCompiler || inPreCompiler || inDebugger)
3426                      {
3427                         char constant[256];
3428                         FreeExpContents(sourceExp);
3429
3430                         sourceExp.type = constantExp;
3431                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3432                            sprintf(constant, FORMAT64D, value.data);
3433                         else
3434                            sprintf(constant, FORMAT64HEXLL, value.data);
3435                         sourceExp.constant = CopyString(constant);
3436                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3437                      }
3438
3439                      while(converts.first)
3440                      {
3441                         Conversion convert = converts.first;
3442                         converts.Remove(convert);
3443                         conversions.Add(convert);
3444                      }
3445                      delete type;
3446                      return true;
3447                   }
3448                }
3449             }
3450          }
3451          if(converts.first)
3452             converts.Free(FreeConvert);
3453          delete type;
3454       }
3455    }
3456    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3457       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3458          return true;
3459    return false;
3460 }
3461
3462 public bool ModuleVisibility(Module searchIn, Module searchFor)
3463 {
3464    SubModule subModule;
3465
3466    if(searchFor == searchIn)
3467       return true;
3468
3469    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3470    {
3471       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3472       {
3473          if(ModuleVisibility(subModule.module, searchFor))
3474             return true;
3475       }
3476    }
3477    return false;
3478 }
3479
3480 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3481 {
3482    Module module;
3483
3484    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3485       return true;
3486    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3487       return true;
3488    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3489       return true;
3490
3491    for(module = mainModule.application.allModules.first; module; module = module.next)
3492    {
3493       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3494          return true;
3495    }
3496    return false;
3497 }
3498
3499 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3500 {
3501    Type source;
3502    Type realDest = dest;
3503    Type backupSourceExpType = null;
3504    Expression computedExp = sourceExp;
3505    dest.refCount++;
3506
3507    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3508       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3509    {
3510       computedExp = CopyExpression(sourceExp);        // Keep the original expression, but compute for checking enum ranges
3511       ComputeExpression(computedExp /*sourceExp*/);
3512    }
3513
3514    source = sourceExp.expType;
3515
3516    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3517    {
3518       if(computedExp != sourceExp)
3519       {
3520          FreeExpression(computedExp);
3521          computedExp = sourceExp;
3522       }
3523       FreeType(dest);
3524       return true;
3525    }
3526
3527    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3528    {
3529        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3530        {
3531           Class sourceBase, destBase;
3532           for(sourceBase = source._class.registered;
3533               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3534               sourceBase = sourceBase.base);
3535           for(destBase = dest._class.registered;
3536               destBase && destBase.base && destBase.base.type != systemClass;
3537               destBase = destBase.base);
3538           //if(source._class.registered == dest._class.registered)
3539           if(sourceBase == destBase)
3540           {
3541             if(computedExp != sourceExp)
3542             {
3543                FreeExpression(computedExp);
3544                computedExp = sourceExp;
3545             }
3546             FreeType(dest);
3547             return true;
3548          }
3549       }
3550    }
3551
3552    if(source)
3553    {
3554       OldList * specs;
3555       bool flag = false;
3556       int64 value = MAXINT;
3557
3558       source.refCount++;
3559
3560       if(computedExp.type == constantExp)
3561       {
3562          if(source.isSigned)
3563             value = strtoll(computedExp.constant, null, 0);
3564          else
3565             value = strtoull(computedExp.constant, null, 0);
3566       }
3567       else if(computedExp.type == opExp && sourceExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3568       {
3569          if(source.isSigned)
3570             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3571          else
3572             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3573       }
3574       if(computedExp != sourceExp)
3575       {
3576          FreeExpression(computedExp);
3577          computedExp = sourceExp;
3578       }
3579
3580       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3581          !strcmp(source._class.registered.fullName, "unichar" /*"ecere::com::unichar"*/))
3582       {
3583          FreeType(source);
3584          source = Type { kind = intType, isSigned = false, refCount = 1 };
3585       }
3586
3587       if(dest.kind == classType)
3588       {
3589          Class _class = dest._class ? dest._class.registered : null;
3590
3591          if(_class && _class.type == unitClass)
3592          {
3593             if(source.kind != classType)
3594             {
3595                Type tempType { };
3596                Type tempDest, tempSource;
3597
3598                for(; _class.base.type != systemClass; _class = _class.base);
3599                tempSource = dest;
3600                tempDest = tempType;
3601
3602                tempType.kind = classType;
3603                if(!_class.symbol)
3604                   _class.symbol = FindClass(_class.fullName);
3605
3606                tempType._class = _class.symbol;
3607                tempType.truth = dest.truth;
3608                if(tempType._class)
3609                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3610
3611                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3612                backupSourceExpType = sourceExp.expType;
3613                if(dest.passAsTemplate)
3614                {
3615                   // Don't carry passAsTemplate
3616                   sourceExp.expType = { };
3617                   CopyTypeInto(sourceExp.expType, dest);
3618                   sourceExp.expType.passAsTemplate = false;
3619                }
3620                else
3621                {
3622                   sourceExp.expType = dest;
3623                   dest.refCount++;
3624                }
3625                //sourceExp.expType = MkClassType(_class.fullName);
3626                flag = true;
3627
3628                delete tempType;
3629             }
3630          }
3631
3632
3633          // Why wasn't there something like this?
3634          if(_class && _class.type == bitClass && source.kind != classType)
3635          {
3636             if(!dest._class.registered.dataType)
3637                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3638             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3639             {
3640                FreeType(source);
3641                FreeType(sourceExp.expType);
3642                source = sourceExp.expType = MkClassType(dest._class.string);
3643                source.refCount++;
3644
3645                //source.kind = classType;
3646                //source._class = dest._class;
3647             }
3648          }
3649
3650          // Adding two enumerations
3651          /*
3652          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3653          {
3654             if(!source._class.registered.dataType)
3655                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3656             if(!dest._class.registered.dataType)
3657                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3658
3659             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3660             {
3661                FreeType(source);
3662                source = sourceExp.expType = MkClassType(dest._class.string);
3663                source.refCount++;
3664
3665                //source.kind = classType;
3666                //source._class = dest._class;
3667             }
3668          }*/
3669
3670          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3671          {
3672             OldList * specs = MkList();
3673             Declarator decl;
3674             char string[1024];
3675
3676             ReadString(string, sourceExp.string);
3677             decl = SpecDeclFromString(string, specs, null);
3678
3679             FreeExpContents(sourceExp);
3680             FreeType(sourceExp.expType);
3681
3682             sourceExp.type = classExp;
3683             sourceExp._classExp.specifiers = specs;
3684             sourceExp._classExp.decl = decl;
3685             sourceExp.expType = dest;
3686             dest.refCount++;
3687
3688             FreeType(source);
3689             FreeType(dest);
3690             if(backupSourceExpType) FreeType(backupSourceExpType);
3691             return true;
3692          }
3693       }
3694       else if(source.kind == classType)
3695       {
3696          Class _class = source._class ? source._class.registered : null;
3697
3698          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || _class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3699          {
3700             /*
3701             if(dest.kind != classType)
3702             {
3703                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3704                if(!source._class.registered.dataType)
3705                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3706
3707                FreeType(dest);
3708                dest = MkClassType(source._class.string);
3709                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3710                //   dest = MkClassType(source._class.string);
3711             }
3712             */
3713
3714             if(dest.kind != classType)
3715             {
3716                Type tempType { };
3717                Type tempDest, tempSource;
3718
3719                if(!source._class.registered.dataType)
3720                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3721
3722                for(; _class.base.type != systemClass; _class = _class.base);
3723                tempDest = source;
3724                tempSource = tempType;
3725                tempType.kind = classType;
3726                tempType._class = FindClass(_class.fullName);
3727                tempType.truth = source.truth;
3728                tempType.classObjectType = source.classObjectType;
3729
3730                if(tempType._class)
3731                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3732
3733                // PUT THIS BACK TESTING UNITS?
3734                if(conversions && conversions.last)
3735                {
3736                   ((Conversion)(conversions.last)).resultType = dest;
3737                   dest.refCount++;
3738                }
3739
3740                FreeType(sourceExp.expType);
3741                sourceExp.expType = MkClassType(_class.fullName);
3742                sourceExp.expType.truth = source.truth;
3743                sourceExp.expType.classObjectType = source.classObjectType;
3744
3745                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3746
3747                if(!sourceExp.destType)
3748                {
3749                   FreeType(sourceExp.destType);
3750                   sourceExp.destType = sourceExp.expType;
3751                   if(sourceExp.expType)
3752                      sourceExp.expType.refCount++;
3753                }
3754                //flag = true;
3755                //source = _class.dataType;
3756
3757
3758                // TOCHECK: TESTING THIS NEW CODE
3759                if(!_class.dataType)
3760                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3761                FreeType(dest);
3762                dest = MkClassType(source._class.string);
3763                dest.truth = source.truth;
3764                dest.classObjectType = source.classObjectType;
3765
3766                FreeType(source);
3767                source = _class.dataType;
3768                source.refCount++;
3769
3770                delete tempType;
3771             }
3772          }
3773       }
3774
3775       if(!flag)
3776       {
3777          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3778          {
3779             FreeType(source);
3780             FreeType(dest);
3781             return true;
3782          }
3783       }
3784
3785       // Implicit Casts
3786       /*
3787       if(source.kind == classType)
3788       {
3789          Class _class = source._class.registered;
3790          if(_class.type == unitClass)
3791          {
3792             if(!_class.dataType)
3793                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3794             source = _class.dataType;
3795          }
3796       }*/
3797
3798       if(dest.kind == classType)
3799       {
3800          Class _class = dest._class ? dest._class.registered : null;
3801          bool fittingValue = false;
3802          if(_class && _class.type == enumClass)
3803          {
3804             Class enumClass = eSystem_FindClass(privateModule, "enum");
3805             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3806             if(c && value >= 0 && value <= c.largest)
3807                fittingValue = true;
3808          }
3809
3810          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3811             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3812          {
3813             if(_class.type == normalClass || _class.type == noHeadClass)
3814             {
3815                Expression newExp { };
3816                *newExp = *sourceExp;
3817                if(sourceExp.destType) sourceExp.destType.refCount++;
3818                if(sourceExp.expType)  sourceExp.expType.refCount++;
3819                sourceExp.type = castExp;
3820                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3821                sourceExp.cast.exp = newExp;
3822                FreeType(sourceExp.expType);
3823                sourceExp.expType = null;
3824                ProcessExpressionType(sourceExp);
3825
3826                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3827                if(!inCompiler)
3828                {
3829                   FreeType(sourceExp.expType);
3830                   sourceExp.expType = dest;
3831                }
3832
3833                FreeType(source);
3834                if(inCompiler) FreeType(dest);
3835
3836                if(backupSourceExpType) FreeType(backupSourceExpType);
3837                return true;
3838             }
3839
3840             if(!_class.dataType)
3841                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3842             FreeType(dest);
3843             dest = _class.dataType;
3844             dest.refCount++;
3845          }
3846
3847          // Accept lower precision types for units, since we want to keep the unit type
3848          if(dest.kind == doubleType &&
3849             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3850              source.kind == charType || source.kind == _BoolType))
3851          {
3852             specs = MkListOne(MkSpecifier(DOUBLE));
3853          }
3854          else if(dest.kind == floatType &&
3855             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3856             source.kind == _BoolType || source.kind == doubleType))
3857          {
3858             specs = MkListOne(MkSpecifier(FLOAT));
3859          }
3860          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3861             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3862          {
3863             specs = MkList();
3864             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3865             ListAdd(specs, MkSpecifier(INT64));
3866          }
3867          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
3868             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3869          {
3870             specs = MkList();
3871             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3872             ListAdd(specs, MkSpecifier(INT));
3873          }
3874          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
3875             source.kind == floatType || source.kind == doubleType))
3876          {
3877             specs = MkList();
3878             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3879             ListAdd(specs, MkSpecifier(SHORT));
3880          }
3881          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
3882             source.kind == floatType || source.kind == doubleType))
3883          {
3884             specs = MkList();
3885             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3886             ListAdd(specs, MkSpecifier(CHAR));
3887          }
3888          else
3889          {
3890             FreeType(source);
3891             FreeType(dest);
3892             if(backupSourceExpType)
3893             {
3894                // Failed to convert: revert previous exp type
3895                if(sourceExp.expType) FreeType(sourceExp.expType);
3896                sourceExp.expType = backupSourceExpType;
3897             }
3898             return false;
3899          }
3900       }
3901       else if(dest.kind == doubleType &&
3902          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
3903           source.kind == _BoolType || source.kind == charType))
3904       {
3905          specs = MkListOne(MkSpecifier(DOUBLE));
3906       }
3907       else if(dest.kind == floatType &&
3908          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3909       {
3910          specs = MkListOne(MkSpecifier(FLOAT));
3911       }
3912       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3913          (value == 1 || value == 0))
3914       {
3915          specs = MkList();
3916          ListAdd(specs, MkSpecifier(BOOL));
3917       }
3918       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3919          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
3920       {
3921          specs = MkList();
3922          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3923          ListAdd(specs, MkSpecifier(CHAR));
3924       }
3925       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
3926          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
3927       {
3928          specs = MkList();
3929          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3930          ListAdd(specs, MkSpecifier(SHORT));
3931       }
3932       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
3933       {
3934          specs = MkList();
3935          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3936          ListAdd(specs, MkSpecifier(INT));
3937       }
3938       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
3939       {
3940          specs = MkList();
3941          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3942          ListAdd(specs, MkSpecifier(INT64));
3943       }
3944       else if(dest.kind == enumType &&
3945          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3946       {
3947          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
3948       }
3949       else
3950       {
3951          FreeType(source);
3952          FreeType(dest);
3953          if(backupSourceExpType)
3954          {
3955             // Failed to convert: revert previous exp type
3956             if(sourceExp.expType) FreeType(sourceExp.expType);
3957             sourceExp.expType = backupSourceExpType;
3958          }
3959          return false;
3960       }
3961
3962       if(!flag && !sourceExp.opDestType)
3963       {
3964          Expression newExp { };
3965          *newExp = *sourceExp;
3966          newExp.prev = null;
3967          newExp.next = null;
3968          if(sourceExp.destType) sourceExp.destType.refCount++;
3969          if(sourceExp.expType)  sourceExp.expType.refCount++;
3970
3971          sourceExp.type = castExp;
3972          if(realDest.kind == classType)
3973          {
3974             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
3975             FreeList(specs, FreeSpecifier);
3976          }
3977          else
3978             sourceExp.cast.typeName = MkTypeName(specs, null);
3979          if(newExp.type == opExp)
3980          {
3981             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
3982          }
3983          else
3984             sourceExp.cast.exp = newExp;
3985
3986          FreeType(sourceExp.expType);
3987          sourceExp.expType = null;
3988          ProcessExpressionType(sourceExp);
3989       }
3990       else
3991          FreeList(specs, FreeSpecifier);
3992
3993       FreeType(dest);
3994       FreeType(source);
3995       if(backupSourceExpType) FreeType(backupSourceExpType);
3996
3997       return true;
3998    }
3999    else
4000    {
4001       if(computedExp != sourceExp)
4002       {
4003          FreeExpression(computedExp);
4004          computedExp = sourceExp;
4005       }
4006
4007       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4008       if(sourceExp.type == identifierExp)
4009       {
4010          Identifier id = sourceExp.identifier;
4011          if(dest.kind == classType)
4012          {
4013             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4014             {
4015                Class _class = dest._class.registered;
4016                Class enumClass = eSystem_FindClass(privateModule, "enum");
4017                if(enumClass)
4018                {
4019                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4020                   {
4021                      NamedLink64 value;
4022                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4023                      for(value = e.values.first; value; value = value.next)
4024                      {
4025                         if(!strcmp(value.name, id.string))
4026                            break;
4027                      }
4028                      if(value)
4029                      {
4030                         FreeType(sourceExp.expType);
4031
4032                         sourceExp.isConstant = true;
4033                         sourceExp.expType = MkClassType(_class.fullName);
4034                         if(inCompiler || inPreCompiler || inDebugger)
4035                         {
4036                            FreeExpContents(sourceExp);
4037
4038                            sourceExp.type = constantExp;
4039                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4040                               sourceExp.constant = PrintInt64(value.data);
4041                            else
4042                               sourceExp.constant = PrintUInt64(value.data);
4043                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4044                         }
4045                         FreeType(dest);
4046                         return true;
4047                      }
4048                   }
4049                }
4050             }
4051          }
4052
4053          // Loop through all enum classes
4054          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4055          {
4056             FreeType(dest);
4057             return true;
4058          }
4059       }
4060       FreeType(dest);
4061    }
4062    return false;
4063 }
4064
4065 #define TERTIARY(o, name, m, t, p) \
4066    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4067    {                                                              \
4068       exp.type = constantExp;                                    \
4069       exp.string = p(op1.m ? op2.m : op3.m);                     \
4070       if(!exp.expType) \
4071          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4072       return true;                                                \
4073    }
4074
4075 #define BINARY(o, name, m, t, p) \
4076    static bool name(Expression exp, Operand op1, Operand op2)   \
4077    {                                                              \
4078       t value2 = op2.m;                                           \
4079       exp.type = constantExp;                                    \
4080       exp.string = p((t)(op1.m o value2));                     \
4081       if(!exp.expType) \
4082          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4083       return true;                                                \
4084    }
4085
4086 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4087    static bool name(Expression exp, Operand op1, Operand op2)   \
4088    {                                                              \
4089       t value2 = op2.m;                                           \
4090       exp.type = constantExp;                                    \
4091       exp.string = p(value2 ? ((t)(op1.m o value2)) : 0);             \
4092       if(!exp.expType) \
4093          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4094       return true;                                                \
4095    }
4096
4097 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4098    static bool name(Expression exp, Operand op1, Operand op2)   \
4099    {                                                              \
4100       t value2 = op2.m;                                           \
4101       exp.type = constantExp;                                    \
4102       exp.string = p((t)(op1.m o value2));             \
4103       if(!exp.expType) \
4104          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4105       return true;                                                \
4106    }
4107
4108 #define UNARY(o, name, m, t, p) \
4109    static bool name(Expression exp, Operand op1)                \
4110    {                                                              \
4111       exp.type = constantExp;                                    \
4112       exp.string = p((t)(o op1.m));                                   \
4113       if(!exp.expType) \
4114          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4115       return true;                                                \
4116    }
4117
4118 #define OPERATOR_ALL(macro, o, name) \
4119    macro(o, Int##name, i, int, PrintInt) \
4120    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4121    macro(o, Int64##name, i64, int64, PrintInt64) \
4122    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4123    macro(o, Short##name, s, short, PrintShort) \
4124    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4125    macro(o, Char##name, c, char, PrintChar) \
4126    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4127    macro(o, Float##name, f, float, PrintFloat) \
4128    macro(o, Double##name, d, double, PrintDouble)
4129
4130 #define OPERATOR_INTTYPES(macro, o, name) \
4131    macro(o, Int##name, i, int, PrintInt) \
4132    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4133    macro(o, Int64##name, i64, int64, PrintInt64) \
4134    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4135    macro(o, Short##name, s, short, PrintShort) \
4136    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4137    macro(o, Char##name, c, char, PrintChar) \
4138    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4139
4140 #define OPERATOR_REALTYPES(macro, o, name) \
4141    macro(o, Float##name, f, float, PrintFloat) \
4142    macro(o, Double##name, d, double, PrintDouble)
4143
4144 // binary arithmetic
4145 OPERATOR_ALL(BINARY, +, Add)
4146 OPERATOR_ALL(BINARY, -, Sub)
4147 OPERATOR_ALL(BINARY, *, Mul)
4148 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4149 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4150 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4151
4152 // unary arithmetic
4153 OPERATOR_ALL(UNARY, -, Neg)
4154
4155 // unary arithmetic increment and decrement
4156 OPERATOR_ALL(UNARY, ++, Inc)
4157 OPERATOR_ALL(UNARY, --, Dec)
4158
4159 // binary arithmetic assignment
4160 OPERATOR_ALL(BINARY, =, Asign)
4161 OPERATOR_ALL(BINARY, +=, AddAsign)
4162 OPERATOR_ALL(BINARY, -=, SubAsign)
4163 OPERATOR_ALL(BINARY, *=, MulAsign)
4164 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4165 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4166 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4167
4168 // binary bitwise
4169 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4170 OPERATOR_INTTYPES(BINARY, |, BitOr)
4171 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4172 OPERATOR_INTTYPES(BINARY, <<, LShift)
4173 OPERATOR_INTTYPES(BINARY, >>, RShift)
4174
4175 // unary bitwise
4176 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4177
4178 // binary bitwise assignment
4179 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4180 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4181 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4182 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4183 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4184
4185 // unary logical negation
4186 OPERATOR_INTTYPES(UNARY, !, Not)
4187
4188 // binary logical equality
4189 OPERATOR_ALL(BINARY, ==, Equ)
4190 OPERATOR_ALL(BINARY, !=, Nqu)
4191
4192 // binary logical
4193 OPERATOR_ALL(BINARY, &&, And)
4194 OPERATOR_ALL(BINARY, ||, Or)
4195
4196 // binary logical relational
4197 OPERATOR_ALL(BINARY, >, Grt)
4198 OPERATOR_ALL(BINARY, <, Sma)
4199 OPERATOR_ALL(BINARY, >=, GrtEqu)
4200 OPERATOR_ALL(BINARY, <=, SmaEqu)
4201
4202 // tertiary condition operator
4203 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4204
4205 //Add, Sub, Mul, Div, Mod,     , Neg,     Inc, Dec,    Asign, AddAsign, SubAsign, MulAsign, DivAsign, ModAsign,     BitAnd, BitOr, BitXor, LShift, RShift, BitNot,     AndAsign, OrAsign, XorAsign, LShiftAsign, RShiftAsign,     Not,     Equ, Nqu,     And, Or,     Grt, Sma, GrtEqu, SmaEqu
4206 #define OPERATOR_TABLE_ALL(name, type) \
4207     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4208                           type##Neg, \
4209                           type##Inc, type##Dec, \
4210                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4211                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4212                           type##BitNot, \
4213                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4214                           type##Not, \
4215                           type##Equ, type##Nqu, \
4216                           type##And, type##Or, \
4217                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4218                         }; \
4219
4220 #define OPERATOR_TABLE_INTTYPES(name, type) \
4221     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4222                           type##Neg, \
4223                           type##Inc, type##Dec, \
4224                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4225                           null, null, null, null, null, \
4226                           null, \
4227                           null, null, null, null, null, \
4228                           null, \
4229                           type##Equ, type##Nqu, \
4230                           type##And, type##Or, \
4231                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4232                         }; \
4233
4234 OPERATOR_TABLE_ALL(int, Int)
4235 OPERATOR_TABLE_ALL(uint, UInt)
4236 OPERATOR_TABLE_ALL(int64, Int64)
4237 OPERATOR_TABLE_ALL(uint64, UInt64)
4238 OPERATOR_TABLE_ALL(short, Short)
4239 OPERATOR_TABLE_ALL(ushort, UShort)
4240 OPERATOR_TABLE_INTTYPES(float, Float)
4241 OPERATOR_TABLE_INTTYPES(double, Double)
4242 OPERATOR_TABLE_ALL(char, Char)
4243 OPERATOR_TABLE_ALL(uchar, UChar)
4244
4245 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4246 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4247 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4248 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4249 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4250 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4251 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4252 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4253
4254 public void ReadString(char * output,  char * string)
4255 {
4256    int len = strlen(string);
4257    int c,d = 0;
4258    bool quoted = false, escaped = false;
4259    for(c = 0; c<len; c++)
4260    {
4261       char ch = string[c];
4262       if(escaped)
4263       {
4264          switch(ch)
4265          {
4266             case 'n': output[d] = '\n'; break;
4267             case 't': output[d] = '\t'; break;
4268             case 'a': output[d] = '\a'; break;
4269             case 'b': output[d] = '\b'; break;
4270             case 'f': output[d] = '\f'; break;
4271             case 'r': output[d] = '\r'; break;
4272             case 'v': output[d] = '\v'; break;
4273             case '\\': output[d] = '\\'; break;
4274             case '\"': output[d] = '\"'; break;
4275             case '\'': output[d] = '\''; break;
4276             default: output[d] = ch;
4277          }
4278          d++;
4279          escaped = false;
4280       }
4281       else
4282       {
4283          if(ch == '\"')
4284             quoted ^= true;
4285          else if(quoted)
4286          {
4287             if(ch == '\\')
4288                escaped = true;
4289             else
4290                output[d++] = ch;
4291          }
4292       }
4293    }
4294    output[d] = '\0';
4295 }
4296
4297 // String Unescape Copy
4298
4299 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4300 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4301 public int UnescapeString(char * d, char * s, int len)
4302 {
4303    int j = 0, k = 0;
4304    char ch;
4305    while(j < len && (ch = s[j]))
4306    {
4307       switch(ch)
4308       {
4309          case '\\':
4310             switch((ch = s[++j]))
4311             {
4312                case 'n': d[k] = '\n'; break;
4313                case 't': d[k] = '\t'; break;
4314                case 'a': d[k] = '\a'; break;
4315                case 'b': d[k] = '\b'; break;
4316                case 'f': d[k] = '\f'; break;
4317                case 'r': d[k] = '\r'; break;
4318                case 'v': d[k] = '\v'; break;
4319                case '\\': d[k] = '\\'; break;
4320                case '\"': d[k] = '\"'; break;
4321                case '\'': d[k] = '\''; break;
4322                default: d[k] = '\\'; d[k] = ch;
4323             }
4324             break;
4325          default:
4326             d[k] = ch;
4327       }
4328       j++, k++;
4329    }
4330    d[k] = '\0';
4331    return k;
4332 }
4333
4334 public char * OffsetEscapedString(char * s, int len, int offset)
4335 {
4336    char ch;
4337    int j = 0, k = 0;
4338    while(j < len && k < offset && (ch = s[j]))
4339    {
4340       if(ch == '\\') ++j;
4341       j++, k++;
4342    }
4343    return (k == offset) ? s + j : null;
4344 }
4345
4346 public Operand GetOperand(Expression exp)
4347 {
4348    Operand op { };
4349    Type type = exp.expType;
4350    if(type)
4351    {
4352       while(type.kind == classType &&
4353          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4354       {
4355          if(!type._class.registered.dataType)
4356             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4357          type = type._class.registered.dataType;
4358
4359       }
4360       if(exp.type == stringExp && op.kind == pointerType)
4361       {
4362          op.ui64 = (uint64)(uintptr)exp.string;
4363          op.kind = pointerType;
4364          op.ops = uint64Ops;
4365       }
4366       else if(exp.isConstant && exp.type == constantExp)
4367       {
4368          op.kind = type.kind;
4369          op.type = type;
4370
4371          switch(op.kind)
4372          {
4373             case _BoolType:
4374             case charType:
4375             {
4376                if(exp.constant[0] == '\'')
4377                {
4378                   op.c = exp.constant[1];
4379                   op.ops = charOps;
4380                }
4381                else if(type.isSigned)
4382                {
4383                   op.c = (char)strtol(exp.constant, null, 0);
4384                   op.ops = charOps;
4385                }
4386                else
4387                {
4388                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4389                   op.ops = ucharOps;
4390                }
4391                break;
4392             }
4393             case shortType:
4394                if(exp.constant[0] == '\'')
4395                {
4396                   op.s = exp.constant[1];
4397                   op.ops = shortOps;
4398                }
4399                else if(type.isSigned)
4400                {
4401                   op.s = (short)strtol(exp.constant, null, 0);
4402                   op.ops = shortOps;
4403                }
4404                else
4405                {
4406                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4407                   op.ops = ushortOps;
4408                }
4409                break;
4410             case intType:
4411             case longType:
4412                if(exp.constant[0] == '\'')
4413                {
4414                   op.i = exp.constant[1];
4415                   op.ops = intOps;
4416                }
4417                else if(type.isSigned)
4418                {
4419                   op.i = (int)strtol(exp.constant, null, 0);
4420                   op.ops = intOps;
4421                }
4422                else
4423                {
4424                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4425                   op.ops = uintOps;
4426                }
4427                op.kind = intType;
4428                break;
4429             case int64Type:
4430                if(type.isSigned)
4431                {
4432                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4433                   op.ops = int64Ops;
4434                }
4435                else
4436                {
4437                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4438                   op.ops = uint64Ops;
4439                }
4440                op.kind = int64Type;
4441                break;
4442             case intPtrType:
4443                if(type.isSigned)
4444                {
4445                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4446                   op.ops = int64Ops;
4447                }
4448                else
4449                {
4450                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4451                   op.ops = uint64Ops;
4452                }
4453                op.kind = int64Type;
4454                break;
4455             case intSizeType:
4456                if(type.isSigned)
4457                {
4458                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4459                   op.ops = int64Ops;
4460                }
4461                else
4462                {
4463                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4464                   op.ops = uint64Ops;
4465                }
4466                op.kind = int64Type;
4467                break;
4468             case floatType:
4469                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4470                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4471                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4472                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4473                else
4474                   op.f = (float)strtod(exp.constant, null);
4475                op.ops = floatOps;
4476                break;
4477             case doubleType:
4478                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4479                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4480                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4481                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4482                else
4483                   op.d = (double)strtod(exp.constant, null);
4484                op.ops = doubleOps;
4485                break;
4486             //case classType:    For when we have operator overloading...
4487             // Pointer additions
4488             //case functionType:
4489             case arrayType:
4490             case pointerType:
4491             case classType:
4492                op.ui64 = _strtoui64(exp.constant, null, 0);
4493                op.kind = pointerType;
4494                op.ops = uint64Ops;
4495                // op.ptrSize =
4496                break;
4497          }
4498       }
4499    }
4500    return op;
4501 }
4502
4503 static int64 GetEnumValue(Class _class, void * ptr)
4504 {
4505    int64 v = 0;
4506    switch(_class.typeSize)
4507    {
4508       case 8:
4509          if(!strcmp(_class.dataTypeString, "uint64"))
4510             v = (int64)*(uint64 *)ptr;
4511          else
4512             v = (int64)*(int64 *)ptr;
4513          break;
4514       case 4:
4515          if(!strcmp(_class.dataTypeString, "uint"))
4516             v = (int64)*(uint *)ptr;
4517          else
4518             v = (int64)*(int *)ptr;
4519          break;
4520       case 2:
4521          if(!strcmp(_class.dataTypeString, "uint16"))
4522             v = (int64)*(uint16 *)ptr;
4523          else
4524             v = (int64)*(short *)ptr;
4525          break;
4526       case 1:
4527          if(!strcmp(_class.dataTypeString, "byte"))
4528             v = (int64)*(byte *)ptr;
4529          else
4530             v = (int64)*(char *)ptr;
4531          break;
4532    }
4533    return v;
4534 }
4535
4536 static __attribute__((unused)) void UnusedFunction()
4537 {
4538    int a;
4539    a.OnGetString(0,0,0);
4540 }
4541 default:
4542 extern int __ecereVMethodID_class_OnGetString;
4543 public:
4544
4545 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4546 {
4547    DataMember dataMember;
4548    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4549    {
4550       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4551          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4552       else
4553       {
4554          Expression exp { };
4555          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4556          Type type;
4557          void * ptr = inst.data + dataMember.offset + offset;
4558          char * result = null;
4559          exp.loc = member.loc = inst.loc;
4560          ((Identifier)member.identifiers->first).loc = inst.loc;
4561
4562          if(!dataMember.dataType)
4563             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4564          type = dataMember.dataType;
4565          if(type.kind == classType)
4566          {
4567             Class _class = type._class.registered;
4568             if(_class.type == enumClass)
4569             {
4570                Class enumClass = eSystem_FindClass(privateModule, "enum");
4571                if(enumClass)
4572                {
4573                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4574                   NamedLink64 item;
4575                   for(item = e.values.first; item; item = item.next)
4576                   {
4577                      if(item.data == GetEnumValue(_class, ptr))
4578                      {
4579                         result = item.name;
4580                         break;
4581                      }
4582                   }
4583                   if(result)
4584                   {
4585                      exp.identifier = MkIdentifier(result);
4586                      exp.type = identifierExp;
4587                      exp.destType = MkClassType(_class.fullName);
4588                      ProcessExpressionType(exp);
4589                   }
4590                }
4591             }
4592             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4593             {
4594                if(!_class.dataType)
4595                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4596                type = _class.dataType;
4597             }
4598          }
4599          if(!result)
4600          {
4601             switch(type.kind)
4602             {
4603                case floatType:
4604                {
4605                   FreeExpContents(exp);
4606
4607                   exp.constant = PrintFloat(*(float*)ptr);
4608                   exp.type = constantExp;
4609                   break;
4610                }
4611                case doubleType:
4612                {
4613                   FreeExpContents(exp);
4614
4615                   exp.constant = PrintDouble(*(double*)ptr);
4616                   exp.type = constantExp;
4617                   break;
4618                }
4619                case intType:
4620                {
4621                   FreeExpContents(exp);
4622
4623                   exp.constant = PrintInt(*(int*)ptr);
4624                   exp.type = constantExp;
4625                   break;
4626                }
4627                case int64Type:
4628                {
4629                   FreeExpContents(exp);
4630
4631                   exp.constant = PrintInt64(*(int64*)ptr);
4632                   exp.type = constantExp;
4633                   break;
4634                }
4635                case intPtrType:
4636                {
4637                   FreeExpContents(exp);
4638                   // TODO: This should probably use proper type
4639                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4640                   exp.type = constantExp;
4641                   break;
4642                }
4643                case intSizeType:
4644                {
4645                   FreeExpContents(exp);
4646                   // TODO: This should probably use proper type
4647                   exp.constant = PrintInt64((int64)*(intsize*)ptr);
4648                   exp.type = constantExp;
4649                   break;
4650                }
4651                default:
4652                   Compiler_Error($"Unhandled type populating instance\n");
4653             }
4654          }
4655          ListAdd(memberList, member);
4656       }
4657
4658       if(parentDataMember.type == unionMember)
4659          break;
4660    }
4661 }
4662
4663 void PopulateInstance(Instantiation inst)
4664 {
4665    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4666    Class _class = classSym.registered;
4667    DataMember dataMember;
4668    OldList * memberList = MkList();
4669    // Added this check and ->Add to prevent memory leaks on bad code
4670    if(!inst.members)
4671       inst.members = MkListOne(MkMembersInitList(memberList));
4672    else
4673       inst.members->Add(MkMembersInitList(memberList));
4674    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4675    {
4676       if(!dataMember.isProperty)
4677       {
4678          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4679             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4680          else
4681          {
4682             Expression exp { };
4683             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4684             Type type;
4685             void * ptr = inst.data + dataMember.offset;
4686             char * result = null;
4687
4688             exp.loc = member.loc = inst.loc;
4689             ((Identifier)member.identifiers->first).loc = inst.loc;
4690
4691             if(!dataMember.dataType)
4692                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4693             type = dataMember.dataType;
4694             if(type.kind == classType)
4695             {
4696                Class _class = type._class.registered;
4697                if(_class.type == enumClass)
4698                {
4699                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4700                   if(enumClass)
4701                   {
4702                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4703                      NamedLink64 item;
4704                      for(item = e.values.first; item; item = item.next)
4705                      {
4706                         if(item.data == GetEnumValue(_class, ptr))
4707                         {
4708                            result = item.name;
4709                            break;
4710                         }
4711                      }
4712                   }
4713                   if(result)
4714                   {
4715                      exp.identifier = MkIdentifier(result);
4716                      exp.type = identifierExp;
4717                      exp.destType = MkClassType(_class.fullName);
4718                      ProcessExpressionType(exp);
4719                   }
4720                }
4721                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4722                {
4723                   if(!_class.dataType)
4724                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4725                   type = _class.dataType;
4726                }
4727             }
4728             if(!result)
4729             {
4730                switch(type.kind)
4731                {
4732                   case floatType:
4733                   {
4734                      exp.constant = PrintFloat(*(float*)ptr);
4735                      exp.type = constantExp;
4736                      break;
4737                   }
4738                   case doubleType:
4739                   {
4740                      exp.constant = PrintDouble(*(double*)ptr);
4741                      exp.type = constantExp;
4742                      break;
4743                   }
4744                   case intType:
4745                   {
4746                      exp.constant = PrintInt(*(int*)ptr);
4747                      exp.type = constantExp;
4748                      break;
4749                   }
4750                   case int64Type:
4751                   {
4752                      exp.constant = PrintInt64(*(int64*)ptr);
4753                      exp.type = constantExp;
4754                      break;
4755                   }
4756                   case intPtrType:
4757                   {
4758                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4759                      exp.type = constantExp;
4760                      break;
4761                   }
4762                   default:
4763                      Compiler_Error($"Unhandled type populating instance\n");
4764                }
4765             }
4766             ListAdd(memberList, member);
4767          }
4768       }
4769    }
4770 }
4771
4772 void ComputeInstantiation(Expression exp)
4773 {
4774    Instantiation inst = exp.instance;
4775    MembersInit members;
4776    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4777    Class _class = classSym ? classSym.registered : null;
4778    DataMember curMember = null;
4779    Class curClass = null;
4780    DataMember subMemberStack[256];
4781    int subMemberStackPos = 0;
4782    uint64 bits = 0;
4783
4784    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4785    {
4786       // Don't recompute the instantiation...
4787       // Non Simple classes will have become constants by now
4788       if(inst.data)
4789          return;
4790
4791       if(_class.type == normalClass || _class.type == noHeadClass)
4792       {
4793          inst.data = (byte *)eInstance_New(_class);
4794          if(_class.type == normalClass)
4795             ((Instance)inst.data)._refCount++;
4796       }
4797       else
4798          inst.data = new0 byte[_class.structSize];
4799    }
4800
4801    if(inst.members)
4802    {
4803       for(members = inst.members->first; members; members = members.next)
4804       {
4805          switch(members.type)
4806          {
4807             case dataMembersInit:
4808             {
4809                if(members.dataMembers)
4810                {
4811                   MemberInit member;
4812                   for(member = members.dataMembers->first; member; member = member.next)
4813                   {
4814                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4815                      bool found = false;
4816
4817                      Property prop = null;
4818                      DataMember dataMember = null;
4819                      uint dataMemberOffset;
4820
4821                      if(!ident)
4822                      {
4823                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4824                         if(curMember)
4825                         {
4826                            if(curMember.isProperty)
4827                               prop = (Property)curMember;
4828                            else
4829                            {
4830                               dataMember = curMember;
4831
4832                               // CHANGED THIS HERE
4833                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4834
4835                               // 2013/17/29 -- It seems that this was missing here!
4836                               if(_class.type == normalClass)
4837                                  dataMemberOffset += _class.base.structSize;
4838                               // dataMemberOffset = dataMember.offset;
4839                            }
4840                            found = true;
4841                         }
4842                      }
4843                      else
4844                      {
4845                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4846                         if(prop)
4847                         {
4848                            found = true;
4849                            if(prop.memberAccess == publicAccess)
4850                            {
4851                               curMember = (DataMember)prop;
4852                               curClass = prop._class;
4853                            }
4854                         }
4855                         else
4856                         {
4857                            DataMember _subMemberStack[256];
4858                            int _subMemberStackPos = 0;
4859
4860                            // FILL MEMBER STACK
4861                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4862
4863                            if(dataMember)
4864                            {
4865                               found = true;
4866                               if(dataMember.memberAccess == publicAccess)
4867                               {
4868                                  curMember = dataMember;
4869                                  curClass = dataMember._class;
4870                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
4871                                  subMemberStackPos = _subMemberStackPos;
4872                               }
4873                            }
4874                         }
4875                      }
4876
4877                      if(found && member.initializer && member.initializer.type == expInitializer)
4878                      {
4879                         Expression value = member.initializer.exp;
4880                         Type type = null;
4881                         bool deepMember = false;
4882                         if(prop)
4883                         {
4884                            type = prop.dataType;
4885                         }
4886                         else if(dataMember)
4887                         {
4888                            if(!dataMember.dataType)
4889                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4890
4891                            type = dataMember.dataType;
4892                         }
4893
4894                         if(ident && ident.next)
4895                         {
4896                            deepMember = true;
4897
4898                            // for(; ident && type; ident = ident.next)
4899                            for(ident = ident.next; ident && type; ident = ident.next)
4900                            {
4901                               if(type.kind == classType)
4902                               {
4903                                  prop = eClass_FindProperty(type._class.registered,
4904                                     ident.string, privateModule);
4905                                  if(prop)
4906                                     type = prop.dataType;
4907                                  else
4908                                  {
4909                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
4910                                        ident.string, &dataMemberOffset, privateModule, null, null);
4911                                     if(dataMember)
4912                                        type = dataMember.dataType;
4913                                  }
4914                               }
4915                               else if(type.kind == structType || type.kind == unionType)
4916                               {
4917                                  Type memberType;
4918                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
4919                                  {
4920                                     if(!strcmp(memberType.name, ident.string))
4921                                     {
4922                                        type = memberType;
4923                                        break;
4924                                     }
4925                                  }
4926                               }
4927                            }
4928                         }
4929                         if(value)
4930                         {
4931                            FreeType(value.destType);
4932                            value.destType = type;
4933                            if(type) type.refCount++;
4934                            ComputeExpression(value);
4935                         }
4936                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
4937                         {
4938                            if(type.kind == classType)
4939                            {
4940                               Class _class = type._class.registered;
4941                               if(_class && (_class.type == bitClass || _class.type == unitClass || _class.type == enumClass))
4942                               {
4943                                  if(!_class.dataType)
4944                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4945                                  type = _class.dataType;
4946                               }
4947                            }
4948
4949                            if(dataMember)
4950                            {
4951                               void * ptr = inst.data + dataMemberOffset;
4952
4953                               if(value.type == constantExp)
4954                               {
4955                                  switch(type.kind)
4956                                  {
4957                                     case intType:
4958                                     {
4959                                        GetInt(value, (int*)ptr);
4960                                        break;
4961                                     }
4962                                     case int64Type:
4963                                     {
4964                                        GetInt64(value, (int64*)ptr);
4965                                        break;
4966                                     }
4967                                     case intPtrType:
4968                                     {
4969                                        GetIntPtr(value, (intptr*)ptr);
4970                                        break;
4971                                     }
4972                                     case intSizeType:
4973                                     {
4974                                        GetIntSize(value, (intsize*)ptr);
4975                                        break;
4976                                     }
4977                                     case floatType:
4978                                     {
4979                                        GetFloat(value, (float*)ptr);
4980                                        break;
4981                                     }
4982                                     case doubleType:
4983                                     {
4984                                        GetDouble(value, (double *)ptr);
4985                                        break;
4986                                     }
4987                                  }
4988                               }
4989                               else if(value.type == instanceExp)
4990                               {
4991                                  if(type.kind == classType)
4992                                  {
4993                                     Class _class = type._class.registered;
4994                                     if(_class.type == structClass)
4995                                     {
4996                                        ComputeTypeSize(type);
4997                                        if(value.instance.data)
4998                                           memcpy(ptr, value.instance.data, type.size);
4999                                     }
5000                                  }
5001                               }
5002                            }
5003                            else if(prop && prop.Set != (void *)(intptr)1)
5004                            {
5005                               if(value.type == instanceExp && value.instance.data)
5006                               {
5007                                  if(type.kind == classType)
5008                                  {
5009                                     Class _class = type._class.registered;
5010                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5011                                     {
5012                                        void (*Set)(void *, void *) = (void *)prop.Set;
5013                                        Set(inst.data, value.instance.data);
5014                                        PopulateInstance(inst);
5015                                     }
5016                                  }
5017                               }
5018                               else if(value.type == constantExp)
5019                               {
5020                                  switch(type.kind)
5021                                  {
5022                                     case doubleType:
5023                                     {
5024                                        void (*Set)(void *, double) = (void *)prop.Set;
5025                                        Set(inst.data, strtod(value.constant, null) );
5026                                        break;
5027                                     }
5028                                     case floatType:
5029                                     {
5030                                        void (*Set)(void *, float) = (void *)prop.Set;
5031                                        Set(inst.data, (float)(strtod(value.constant, null)));
5032                                        break;
5033                                     }
5034                                     case intType:
5035                                     {
5036                                        void (*Set)(void *, int) = (void *)prop.Set;
5037                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5038                                        break;
5039                                     }
5040                                     case int64Type:
5041                                     {
5042                                        void (*Set)(void *, int64) = (void *)prop.Set;
5043                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5044                                        break;
5045                                     }
5046                                     case intPtrType:
5047                                     {
5048                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5049                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5050                                        break;
5051                                     }
5052                                     case intSizeType:
5053                                     {
5054                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5055                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5056                                        break;
5057                                     }
5058                                  }
5059                               }
5060                               else if(value.type == stringExp)
5061                               {
5062                                  char temp[1024];
5063                                  ReadString(temp, value.string);
5064                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5065                               }
5066                            }
5067                         }
5068                         else if(!deepMember && type && _class.type == unitClass)
5069                         {
5070                            if(prop)
5071                            {
5072                               // Only support converting units to units for now...
5073                               if(value.type == constantExp)
5074                               {
5075                                  if(type.kind == classType)
5076                                  {
5077                                     Class _class = type._class.registered;
5078                                     if(_class.type == unitClass)
5079                                     {
5080                                        if(!_class.dataType)
5081                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5082                                        type = _class.dataType;
5083                                     }
5084                                  }
5085                                  // TODO: Assuming same base type for units...
5086                                  switch(type.kind)
5087                                  {
5088                                     case floatType:
5089                                     {
5090                                        float fValue;
5091                                        float (*Set)(float) = (void *)prop.Set;
5092                                        GetFloat(member.initializer.exp, &fValue);
5093                                        exp.constant = PrintFloat(Set(fValue));
5094                                        exp.type = constantExp;
5095                                        break;
5096                                     }
5097                                     case doubleType:
5098                                     {
5099                                        double dValue;
5100                                        double (*Set)(double) = (void *)prop.Set;
5101                                        GetDouble(member.initializer.exp, &dValue);
5102                                        exp.constant = PrintDouble(Set(dValue));
5103                                        exp.type = constantExp;
5104                                        break;
5105                                     }
5106                                  }
5107                               }
5108                            }
5109                         }
5110                         else if(!deepMember && type && _class.type == bitClass)
5111                         {
5112                            if(prop)
5113                            {
5114                               if(value.type == instanceExp && value.instance.data)
5115                               {
5116                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5117                                  bits = Set(value.instance.data);
5118                               }
5119                               else if(value.type == constantExp)
5120                               {
5121                               }
5122                            }
5123                            else if(dataMember)
5124                            {
5125                               BitMember bitMember = (BitMember) dataMember;
5126                               Type type;
5127                               uint64 part = 0;
5128                               bits = (bits & ~bitMember.mask);
5129                               if(!bitMember.dataType)
5130                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5131                               type = bitMember.dataType;
5132                               if(type.kind == classType && type._class && type._class.registered)
5133                               {
5134                                  if(!type._class.registered.dataType)
5135                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5136                                  type = type._class.registered.dataType;
5137                               }
5138                               switch(type.kind)
5139                               {
5140                                  case _BoolType:
5141                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5142                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5143                                  case intType:
5144                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5145                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5146                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5147                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5148                               }
5149                               bits |= part << bitMember.pos;
5150                            }
5151                         }
5152                      }
5153                      else
5154                      {
5155                         if(_class && _class.type == unitClass)
5156                         {
5157                            ComputeExpression(member.initializer.exp);
5158                            exp.constant = member.initializer.exp.constant;
5159                            exp.type = constantExp;
5160
5161                            member.initializer.exp.constant = null;
5162                         }
5163                      }
5164                   }
5165                }
5166                break;
5167             }
5168          }
5169       }
5170    }
5171    if(_class && _class.type == bitClass)
5172    {
5173       exp.constant = PrintHexUInt(bits);
5174       exp.type = constantExp;
5175    }
5176    if(exp.type != instanceExp)
5177    {
5178       FreeInstance(inst);
5179    }
5180 }
5181
5182 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5183 {
5184    bool result = false;
5185    switch(kind)
5186    {
5187       case shortType:
5188          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5189             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5190          break;
5191       case intType:
5192       case longType:
5193          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5194             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5195          break;
5196       case int64Type:
5197          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5198             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5199             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5200          break;
5201       case floatType:
5202          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5203             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5204             result = GetOpFloat(op, &op.f);
5205          break;
5206       case doubleType:
5207          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5208             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5209             result = GetOpDouble(op, &op.d);
5210          break;
5211       case pointerType:
5212          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5213             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5214             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5215          break;
5216       case enumType:
5217          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5218             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5219             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5220          break;
5221       case intPtrType:
5222          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5223             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5224          break;
5225       case intSizeType:
5226          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5227             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5228          break;
5229    }
5230    return result;
5231 }
5232
5233 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5234 {
5235    if(exp.op.op == SIZEOF)
5236    {
5237       FreeExpContents(exp);
5238       exp.type = constantExp;
5239       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5240    }
5241    else
5242    {
5243       if(!exp.op.exp1)
5244       {
5245          switch(exp.op.op)
5246          {
5247             // unary arithmetic
5248             case '+':
5249             {
5250                // Provide default unary +
5251                Expression exp2 = exp.op.exp2;
5252                exp.op.exp2 = null;
5253                FreeExpContents(exp);
5254                FreeType(exp.expType);
5255                FreeType(exp.destType);
5256                *exp = *exp2;
5257                delete exp2;
5258                break;
5259             }
5260             case '-':
5261                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5262                break;
5263             // unary arithmetic increment and decrement
5264                   //OPERATOR_ALL(UNARY, ++, Inc)
5265                   //OPERATOR_ALL(UNARY, --, Dec)
5266             // unary bitwise
5267             case '~':
5268                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5269                break;
5270             // unary logical negation
5271             case '!':
5272                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5273                break;
5274          }
5275       }
5276       else
5277       {
5278          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5279          {
5280             if(Promote(op2, op1.kind, op1.type.isSigned))
5281                op2.kind = op1.kind, op2.ops = op1.ops;
5282             else if(Promote(op1, op2.kind, op2.type.isSigned))
5283                op1.kind = op2.kind, op1.ops = op2.ops;
5284          }
5285          switch(exp.op.op)
5286          {
5287             // binary arithmetic
5288             case '+':
5289                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5290                break;
5291             case '-':
5292                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5293                break;
5294             case '*':
5295                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5296                break;
5297             case '/':
5298                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5299                break;
5300             case '%':
5301                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5302                break;
5303             // binary arithmetic assignment
5304                   //OPERATOR_ALL(BINARY, =, Asign)
5305                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5306                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5307                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5308                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5309                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5310             // binary bitwise
5311             case '&':
5312                if(exp.op.exp2)
5313                {
5314                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5315                }
5316                break;
5317             case '|':
5318                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5319                break;
5320             case '^':
5321                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5322                break;
5323             case LEFT_OP:
5324                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5325                break;
5326             case RIGHT_OP:
5327                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5328                break;
5329             // binary bitwise assignment
5330                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5331                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5332                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5333                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5334                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5335             // binary logical equality
5336             case EQ_OP:
5337                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5338                break;
5339             case NE_OP:
5340                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5341                break;
5342             // binary logical
5343             case AND_OP:
5344                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5345                break;
5346             case OR_OP:
5347                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5348                break;
5349             // binary logical relational
5350             case '>':
5351                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5352                break;
5353             case '<':
5354                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5355                break;
5356             case GE_OP:
5357                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5358                break;
5359             case LE_OP:
5360                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5361                break;
5362          }
5363       }
5364    }
5365 }
5366
5367 void ComputeExpression(Expression exp)
5368 {
5369 #ifdef _DEBUG
5370    char expString[10240];
5371    expString[0] = '\0';
5372    PrintExpression(exp, expString);
5373 #endif
5374
5375    switch(exp.type)
5376    {
5377       case identifierExp:
5378       {
5379          Identifier id = exp.identifier;
5380          if(id && exp.isConstant && !inCompiler && !inPreCompiler && !inDebugger)
5381          {
5382             Class c = (exp.expType && exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
5383             if(c && c.type == enumClass)
5384             {
5385                Class enumClass = eSystem_FindClass(privateModule, "enum");
5386                if(enumClass)
5387                {
5388                   NamedLink64 value;
5389                   EnumClassData e = ACCESS_CLASSDATA(c, enumClass);
5390                   for(value = e.values.first; value; value = value.next)
5391                   {
5392                      if(!strcmp(value.name, id.string))
5393                         break;
5394                   }
5395                   if(value)
5396                   {
5397                      const String dts = c.dataTypeString;
5398                      FreeExpContents(exp);
5399                      exp.type = constantExp;
5400                      exp.constant = (dts && (!strcmp(dts, "int") || !strcmp(dts, "int64") || !strcmp(dts, "short") || !strcmp(dts, "char"))) ? PrintInt64(value.data) : PrintUInt64(value.data);
5401                   }
5402                }
5403             }
5404          }
5405          break;
5406       }
5407       case instanceExp:
5408       {
5409          ComputeInstantiation(exp);
5410          break;
5411       }
5412       /*
5413       case constantExp:
5414          break;
5415       */
5416       case opExp:
5417       {
5418          Expression exp1, exp2 = null;
5419          Operand op1 { };
5420          Operand op2 { };
5421
5422          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5423          if(exp.op.exp2)
5424          {
5425             Expression e = exp.op.exp2;
5426
5427             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5428             {
5429                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5430                {
5431                   if(e.type == extensionCompoundExp)
5432                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5433                   else
5434                      e = e.list->last;
5435                }
5436             }
5437             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5438             {
5439                if(e.type == stringExp && e.string)
5440                {
5441                   char * string = e.string;
5442                   int len = strlen(string);
5443                   char * tmp = new char[len-2+1];
5444                   len = UnescapeString(tmp, string + 1, len - 2);
5445                   delete tmp;
5446                   FreeExpContents(exp);
5447                   exp.type = constantExp;
5448                   exp.constant = PrintUInt(len + 1);
5449                }
5450                else
5451                {
5452                   Type type = e.expType;
5453                   type.refCount++;
5454                   FreeExpContents(exp);
5455                   exp.type = constantExp;
5456                   exp.constant = PrintUInt(ComputeTypeSize(type));
5457                   FreeType(type);
5458                }
5459                break;
5460             }
5461             else
5462                ComputeExpression(exp.op.exp2);
5463          }
5464          if(exp.op.exp1)
5465          {
5466             ComputeExpression(exp.op.exp1);
5467             exp1 = exp.op.exp1;
5468             exp2 = exp.op.exp2;
5469             op1 = GetOperand(exp1);
5470             if(op1.type) op1.type.refCount++;
5471             if(exp2)
5472             {
5473                op2 = GetOperand(exp2);
5474                if(op2.type) op2.type.refCount++;
5475             }
5476          }
5477          else
5478          {
5479             exp1 = exp.op.exp2;
5480             op1 = GetOperand(exp1);
5481             if(op1.type) op1.type.refCount++;
5482          }
5483
5484          CallOperator(exp, exp1, exp2, op1, op2);
5485          /*
5486          switch(exp.op.op)
5487          {
5488             // Unary operators
5489             case '&':
5490                // Also binary
5491                if(exp.op.exp1 && exp.op.exp2)
5492                {
5493                   // Binary And
5494                   if(op1.ops.BitAnd)
5495                   {
5496                      FreeExpContents(exp);
5497                      op1.ops.BitAnd(exp, op1, op2);
5498                   }
5499                }
5500                break;
5501             case '*':
5502                if(exp.op.exp1)
5503                {
5504                   if(op1.ops.Mul)
5505                   {
5506                      FreeExpContents(exp);
5507                      op1.ops.Mul(exp, op1, op2);
5508                   }
5509                }
5510                break;
5511             case '+':
5512                if(exp.op.exp1)
5513                {
5514                   if(op1.ops.Add)
5515                   {
5516                      FreeExpContents(exp);
5517                      op1.ops.Add(exp, op1, op2);
5518                   }
5519                }
5520                else
5521                {
5522                   // Provide default unary +
5523                   Expression exp2 = exp.op.exp2;
5524                   exp.op.exp2 = null;
5525                   FreeExpContents(exp);
5526                   FreeType(exp.expType);
5527                   FreeType(exp.destType);
5528
5529                   *exp = *exp2;
5530                   delete exp2;
5531                }
5532                break;
5533             case '-':
5534                if(exp.op.exp1)
5535                {
5536                   if(op1.ops.Sub)
5537                   {
5538                      FreeExpContents(exp);
5539                      op1.ops.Sub(exp, op1, op2);
5540                   }
5541                }
5542                else
5543                {
5544                   if(op1.ops.Neg)
5545                   {
5546                      FreeExpContents(exp);
5547                      op1.ops.Neg(exp, op1);
5548                   }
5549                }
5550                break;
5551             case '~':
5552                if(op1.ops.BitNot)
5553                {
5554                   FreeExpContents(exp);
5555                   op1.ops.BitNot(exp, op1);
5556                }
5557                break;
5558             case '!':
5559                if(op1.ops.Not)
5560                {
5561                   FreeExpContents(exp);
5562                   op1.ops.Not(exp, op1);
5563                }
5564                break;
5565             // Binary only operators
5566             case '/':
5567                if(op1.ops.Div)
5568                {
5569                   FreeExpContents(exp);
5570                   op1.ops.Div(exp, op1, op2);
5571                }
5572                break;
5573             case '%':
5574                if(op1.ops.Mod)
5575                {
5576                   FreeExpContents(exp);
5577                   op1.ops.Mod(exp, op1, op2);
5578                }
5579                break;
5580             case LEFT_OP:
5581                break;
5582             case RIGHT_OP:
5583                break;
5584             case '<':
5585                if(exp.op.exp1)
5586                {
5587                   if(op1.ops.Sma)
5588                   {
5589                      FreeExpContents(exp);
5590                      op1.ops.Sma(exp, op1, op2);
5591                   }
5592                }
5593                break;
5594             case '>':
5595                if(exp.op.exp1)
5596                {
5597                   if(op1.ops.Grt)
5598                   {
5599                      FreeExpContents(exp);
5600                      op1.ops.Grt(exp, op1, op2);
5601                   }
5602                }
5603                break;
5604             case LE_OP:
5605                if(exp.op.exp1)
5606                {
5607                   if(op1.ops.SmaEqu)
5608                   {
5609                      FreeExpContents(exp);
5610                      op1.ops.SmaEqu(exp, op1, op2);
5611                   }
5612                }
5613                break;
5614             case GE_OP:
5615                if(exp.op.exp1)
5616                {
5617                   if(op1.ops.GrtEqu)
5618                   {
5619                      FreeExpContents(exp);
5620                      op1.ops.GrtEqu(exp, op1, op2);
5621                   }
5622                }
5623                break;
5624             case EQ_OP:
5625                if(exp.op.exp1)
5626                {
5627                   if(op1.ops.Equ)
5628                   {
5629                      FreeExpContents(exp);
5630                      op1.ops.Equ(exp, op1, op2);
5631                   }
5632                }
5633                break;
5634             case NE_OP:
5635                if(exp.op.exp1)
5636                {
5637                   if(op1.ops.Nqu)
5638                   {
5639                      FreeExpContents(exp);
5640                      op1.ops.Nqu(exp, op1, op2);
5641                   }
5642                }
5643                break;
5644             case '|':
5645                if(op1.ops.BitOr)
5646                {
5647                   FreeExpContents(exp);
5648                   op1.ops.BitOr(exp, op1, op2);
5649                }
5650                break;
5651             case '^':
5652                if(op1.ops.BitXor)
5653                {
5654                   FreeExpContents(exp);
5655                   op1.ops.BitXor(exp, op1, op2);
5656                }
5657                break;
5658             case AND_OP:
5659                break;
5660             case OR_OP:
5661                break;
5662             case SIZEOF:
5663                FreeExpContents(exp);
5664                exp.type = constantExp;
5665                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5666                break;
5667          }
5668          */
5669          if(op1.type) FreeType(op1.type);
5670          if(op2.type) FreeType(op2.type);
5671          break;
5672       }
5673       case bracketsExp:
5674       case extensionExpressionExp:
5675       {
5676          Expression e, n;
5677          for(e = exp.list->first; e; e = n)
5678          {
5679             n = e.next;
5680             if(!n)
5681             {
5682                OldList * list = exp.list;
5683                Expression prev = exp.prev;
5684                Expression next = exp.next;
5685                ComputeExpression(e);
5686                //FreeExpContents(exp);
5687                FreeType(exp.expType);
5688                FreeType(exp.destType);
5689                *exp = *e;
5690                exp.prev = prev;
5691                exp.next = next;
5692                delete e;
5693                delete list;
5694             }
5695             else
5696             {
5697                FreeExpression(e);
5698             }
5699          }
5700          break;
5701       }
5702       /*
5703
5704       case ExpIndex:
5705       {
5706          Expression e;
5707          exp.isConstant = true;
5708
5709          ComputeExpression(exp.index.exp);
5710          if(!exp.index.exp.isConstant)
5711             exp.isConstant = false;
5712
5713          for(e = exp.index.index->first; e; e = e.next)
5714          {
5715             ComputeExpression(e);
5716             if(!e.next)
5717             {
5718                // Check if this type is int
5719             }
5720             if(!e.isConstant)
5721                exp.isConstant = false;
5722          }
5723          exp.expType = Dereference(exp.index.exp.expType);
5724          break;
5725       }
5726       */
5727       case memberExp:
5728       {
5729          Expression memberExp = exp.member.exp;
5730          Identifier memberID = exp.member.member;
5731
5732          Type type;
5733          ComputeExpression(exp.member.exp);
5734          type = exp.member.exp.expType;
5735          if(type)
5736          {
5737             Class _class = (exp.member.member && exp.member.member.classSym) ? exp.member.member.classSym.registered : (((type.kind == classType || type.kind == subClassType) && type._class) ? type._class.registered : null);
5738             Property prop = null;
5739             DataMember member = null;
5740             Class convertTo = null;
5741             if(type.kind == subClassType && exp.member.exp.type == classExp)
5742                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5743
5744             if(!_class)
5745             {
5746                char string[256];
5747                Symbol classSym;
5748                string[0] = '\0';
5749                PrintTypeNoConst(type, string, false, true);
5750                classSym = FindClass(string);
5751                _class = classSym ? classSym.registered : null;
5752             }
5753
5754             if(exp.member.member)
5755             {
5756                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5757                if(!prop)
5758                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5759             }
5760             if(!prop && !member && _class && exp.member.member)
5761             {
5762                Symbol classSym = FindClass(exp.member.member.string);
5763                convertTo = _class;
5764                _class = classSym ? classSym.registered : null;
5765                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5766             }
5767
5768             if(prop)
5769             {
5770                if(prop.compiled)
5771                {
5772                   Type type = prop.dataType;
5773                   // TODO: Assuming same base type for units...
5774                   if(_class.type == unitClass)
5775                   {
5776                      if(type.kind == classType)
5777                      {
5778                         Class _class = type._class.registered;
5779                         if(_class.type == unitClass)
5780                         {
5781                            if(!_class.dataType)
5782                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5783                            type = _class.dataType;
5784                         }
5785                      }
5786                      switch(type.kind)
5787                      {
5788                         case floatType:
5789                         {
5790                            float value;
5791                            float (*Get)(float) = (void *)prop.Get;
5792                            GetFloat(exp.member.exp, &value);
5793                            exp.constant = PrintFloat(Get ? Get(value) : value);
5794                            exp.type = constantExp;
5795                            break;
5796                         }
5797                         case doubleType:
5798                         {
5799                            double value;
5800                            double (*Get)(double);
5801                            GetDouble(exp.member.exp, &value);
5802
5803                            if(convertTo)
5804                               Get = (void *)prop.Set;
5805                            else
5806                               Get = (void *)prop.Get;
5807                            exp.constant = PrintDouble(Get ? Get(value) : value);
5808                            exp.type = constantExp;
5809                            break;
5810                         }
5811                      }
5812                   }
5813                   else
5814                   {
5815                      if(convertTo)
5816                      {
5817                         Expression value = exp.member.exp;
5818                         Type type;
5819                         if(!prop.dataType)
5820                            ProcessPropertyType(prop);
5821
5822                         type = prop.dataType;
5823                         if(!type)
5824                         {
5825                             // printf("Investigate this\n");
5826                         }
5827                         else if(_class.type == structClass)
5828                         {
5829                            switch(type.kind)
5830                            {
5831                               case classType:
5832                               {
5833                                  Class propertyClass = type._class.registered;
5834                                  if(propertyClass.type == structClass && value.type == instanceExp)
5835                                  {
5836                                     void (*Set)(void *, void *) = (void *)prop.Set;
5837                                     exp.instance = Instantiation { };
5838                                     exp.instance.data = new0 byte[_class.structSize];
5839                                     exp.instance._class = MkSpecifierName(_class.fullName);
5840                                     exp.instance.loc = exp.loc;
5841                                     exp.type = instanceExp;
5842                                     Set(exp.instance.data, value.instance.data);
5843                                     PopulateInstance(exp.instance);
5844                                  }
5845                                  break;
5846                               }
5847                               case intType:
5848                               {
5849                                  int intValue;
5850                                  void (*Set)(void *, int) = (void *)prop.Set;
5851
5852                                  exp.instance = Instantiation { };
5853                                  exp.instance.data = new0 byte[_class.structSize];
5854                                  exp.instance._class = MkSpecifierName(_class.fullName);
5855                                  exp.instance.loc = exp.loc;
5856                                  exp.type = instanceExp;
5857
5858                                  GetInt(value, &intValue);
5859
5860                                  Set(exp.instance.data, intValue);
5861                                  PopulateInstance(exp.instance);
5862                                  break;
5863                               }
5864                               case int64Type:
5865                               {
5866                                  int64 intValue;
5867                                  void (*Set)(void *, int64) = (void *)prop.Set;
5868
5869                                  exp.instance = Instantiation { };
5870                                  exp.instance.data = new0 byte[_class.structSize];
5871                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5872                                  exp.instance.loc = exp.loc;
5873                                  exp.type = instanceExp;
5874
5875                                  GetInt64(value, &intValue);
5876
5877                                  Set(exp.instance.data, intValue);
5878                                  PopulateInstance(exp.instance);
5879                                  break;
5880                               }
5881                               case intPtrType:
5882                               {
5883                                  // TOFIX:
5884                                  intptr intValue;
5885                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5886
5887                                  exp.instance = Instantiation { };
5888                                  exp.instance.data = new0 byte[_class.structSize];
5889                                  exp.instance._class = MkSpecifierName(_class.fullName);
5890                                  exp.instance.loc = exp.loc;
5891                                  exp.type = instanceExp;
5892
5893                                  GetIntPtr(value, &intValue);
5894
5895                                  Set(exp.instance.data, intValue);
5896                                  PopulateInstance(exp.instance);
5897                                  break;
5898                               }
5899                               case intSizeType:
5900                               {
5901                                  // TOFIX:
5902                                  intsize intValue;
5903                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5904
5905                                  exp.instance = Instantiation { };
5906                                  exp.instance.data = new0 byte[_class.structSize];
5907                                  exp.instance._class = MkSpecifierName(_class.fullName);
5908                                  exp.instance.loc = exp.loc;
5909                                  exp.type = instanceExp;
5910
5911                                  GetIntSize(value, &intValue);
5912
5913                                  Set(exp.instance.data, intValue);
5914                                  PopulateInstance(exp.instance);
5915                                  break;
5916                               }
5917                               case floatType:
5918                               {
5919                                  float floatValue;
5920                                  void (*Set)(void *, float) = (void *)prop.Set;
5921
5922                                  exp.instance = Instantiation { };
5923                                  exp.instance.data = new0 byte[_class.structSize];
5924                                  exp.instance._class = MkSpecifierName(_class.fullName);
5925                                  exp.instance.loc = exp.loc;
5926                                  exp.type = instanceExp;
5927
5928                                  GetFloat(value, &floatValue);
5929
5930                                  Set(exp.instance.data, floatValue);
5931                                  PopulateInstance(exp.instance);
5932                                  break;
5933                               }
5934                               case doubleType:
5935                               {
5936                                  double doubleValue;
5937                                  void (*Set)(void *, double) = (void *)prop.Set;
5938
5939                                  exp.instance = Instantiation { };
5940                                  exp.instance.data = new0 byte[_class.structSize];
5941                                  exp.instance._class = MkSpecifierName(_class.fullName);
5942                                  exp.instance.loc = exp.loc;
5943                                  exp.type = instanceExp;
5944
5945                                  GetDouble(value, &doubleValue);
5946
5947                                  Set(exp.instance.data, doubleValue);
5948                                  PopulateInstance(exp.instance);
5949                                  break;
5950                               }
5951                            }
5952                         }
5953                         else if(_class.type == bitClass)
5954                         {
5955                            switch(type.kind)
5956                            {
5957                               case classType:
5958                               {
5959                                  Class propertyClass = type._class.registered;
5960                                  if(propertyClass.type == structClass && value.instance.data)
5961                                  {
5962                                     unsigned int (*Set)(void *) = (void *)prop.Set;
5963                                     unsigned int bits = Set(value.instance.data);
5964                                     exp.constant = PrintHexUInt(bits);
5965                                     exp.type = constantExp;
5966                                     break;
5967                                  }
5968                                  else if(_class.type == bitClass)
5969                                  {
5970                                     unsigned int value;
5971                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
5972                                     unsigned int bits;
5973
5974                                     GetUInt(exp.member.exp, &value);
5975                                     bits = Set(value);
5976                                     exp.constant = PrintHexUInt(bits);
5977                                     exp.type = constantExp;
5978                                  }
5979                               }
5980                            }
5981                         }
5982                      }
5983                      else
5984                      {
5985                         if(_class.type == bitClass)
5986                         {
5987                            unsigned int value;
5988                            GetUInt(exp.member.exp, &value);
5989
5990                            switch(type.kind)
5991                            {
5992                               case classType:
5993                               {
5994                                  Class _class = type._class.registered;
5995                                  if(_class.type == structClass)
5996                                  {
5997                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
5998
5999                                     exp.instance = Instantiation { };
6000                                     exp.instance.data = new0 byte[_class.structSize];
6001                                     exp.instance._class = MkSpecifierName(_class.fullName);
6002                                     exp.instance.loc = exp.loc;
6003                                     //exp.instance.fullSet = true;
6004                                     exp.type = instanceExp;
6005                                     Get(value, exp.instance.data);
6006                                     PopulateInstance(exp.instance);
6007                                  }
6008                                  else if(_class.type == bitClass)
6009                                  {
6010                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6011                                     uint64 bits = Get(value);
6012                                     exp.constant = PrintHexUInt64(bits);
6013                                     exp.type = constantExp;
6014                                  }
6015                                  break;
6016                               }
6017                            }
6018                         }
6019                         else if(_class.type == structClass)
6020                         {
6021                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6022                            switch(type.kind)
6023                            {
6024                               case classType:
6025                               {
6026                                  Class _class = type._class.registered;
6027                                  if(_class.type == structClass && value)
6028                                  {
6029                                     void (*Get)(void *, void *) = (void *)prop.Get;
6030
6031                                     exp.instance = Instantiation { };
6032                                     exp.instance.data = new0 byte[_class.structSize];
6033                                     exp.instance._class = MkSpecifierName(_class.fullName);
6034                                     exp.instance.loc = exp.loc;
6035                                     //exp.instance.fullSet = true;
6036                                     exp.type = instanceExp;
6037                                     Get(value, exp.instance.data);
6038                                     PopulateInstance(exp.instance);
6039                                  }
6040                                  break;
6041                               }
6042                            }
6043                         }
6044                         /*else
6045                         {
6046                            char * value = exp.member.exp.instance.data;
6047                            switch(type.kind)
6048                            {
6049                               case classType:
6050                               {
6051                                  Class _class = type._class.registered;
6052                                  if(_class.type == normalClass)
6053                                  {
6054                                     void *(*Get)(void *) = (void *)prop.Get;
6055
6056                                     exp.instance = Instantiation { };
6057                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6058                                     exp.type = instanceExp;
6059                                     exp.instance.data = Get(value, exp.instance.data);
6060                                  }
6061                                  break;
6062                               }
6063                            }
6064                         }
6065                         */
6066                      }
6067                   }
6068                }
6069                else
6070                {
6071                   exp.isConstant = false;
6072                }
6073             }
6074             else if(member)
6075             {
6076             }
6077          }
6078
6079          if(exp.type != ExpressionType::memberExp)
6080          {
6081             FreeExpression(memberExp);
6082             FreeIdentifier(memberID);
6083          }
6084          break;
6085       }
6086       case typeSizeExp:
6087       {
6088          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6089          FreeExpContents(exp);
6090          exp.constant = PrintUInt(ComputeTypeSize(type));
6091          exp.type = constantExp;
6092          FreeType(type);
6093          break;
6094       }
6095       case classSizeExp:
6096       {
6097          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6098          if(classSym && classSym.registered)
6099          {
6100             if(classSym.registered.fixed)
6101             {
6102                FreeSpecifier(exp._class);
6103                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6104                exp.type = constantExp;
6105             }
6106             else
6107             {
6108                char className[1024];
6109                strcpy(className, "__ecereClass_");
6110                FullClassNameCat(className, classSym.string, true);
6111
6112                DeclareClass(curExternal, classSym, className);
6113
6114                FreeExpContents(exp);
6115                exp.type = pointerExp;
6116                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6117                exp.member.member = MkIdentifier("structSize");
6118             }
6119          }
6120          break;
6121       }
6122       case castExp:
6123       //case constantExp:
6124       {
6125          Type type;
6126          Expression e = exp;
6127          if(exp.type == castExp)
6128          {
6129             if(exp.cast.exp)
6130                ComputeExpression(exp.cast.exp);
6131             e = exp.cast.exp;
6132          }
6133          if(e && exp.expType)
6134          {
6135             /*if(exp.destType)
6136                type = exp.destType;
6137             else*/
6138                type = exp.expType;
6139             if(type.kind == classType)
6140             {
6141                Class _class = type._class.registered;
6142                if(_class && (_class.type == unitClass || _class.type == bitClass))
6143                {
6144                   if(!_class.dataType)
6145                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6146                   type = _class.dataType;
6147                }
6148             }
6149
6150             switch(type.kind)
6151             {
6152                case _BoolType:
6153                case charType:
6154                   if(type.isSigned)
6155                   {
6156                      char value = 0;
6157                      if(GetChar(e, &value))
6158                      {
6159                         FreeExpContents(exp);
6160                         exp.constant = PrintChar(value);
6161                         exp.type = constantExp;
6162                      }
6163                   }
6164                   else
6165                   {
6166                      unsigned char value = 0;
6167                      if(GetUChar(e, &value))
6168                      {
6169                         FreeExpContents(exp);
6170                         exp.constant = PrintUChar(value);
6171                         exp.type = constantExp;
6172                      }
6173                   }
6174                   break;
6175                case shortType:
6176                   if(type.isSigned)
6177                   {
6178                      short value = 0;
6179                      if(GetShort(e, &value))
6180                      {
6181                         FreeExpContents(exp);
6182                         exp.constant = PrintShort(value);
6183                         exp.type = constantExp;
6184                      }
6185                   }
6186                   else
6187                   {
6188                      unsigned short value = 0;
6189                      if(GetUShort(e, &value))
6190                      {
6191                         FreeExpContents(exp);
6192                         exp.constant = PrintUShort(value);
6193                         exp.type = constantExp;
6194                      }
6195                   }
6196                   break;
6197                case intType:
6198                   if(type.isSigned)
6199                   {
6200                      int value = 0;
6201                      if(GetInt(e, &value))
6202                      {
6203                         FreeExpContents(exp);
6204                         exp.constant = PrintInt(value);
6205                         exp.type = constantExp;
6206                      }
6207                   }
6208                   else
6209                   {
6210                      unsigned int value = 0;
6211                      if(GetUInt(e, &value))
6212                      {
6213                         FreeExpContents(exp);
6214                         exp.constant = PrintUInt(value);
6215                         exp.type = constantExp;
6216                      }
6217                   }
6218                   break;
6219                case int64Type:
6220                   if(type.isSigned)
6221                   {
6222                      int64 value = 0;
6223                      if(GetInt64(e, &value))
6224                      {
6225                         FreeExpContents(exp);
6226                         exp.constant = PrintInt64(value);
6227                         exp.type = constantExp;
6228                      }
6229                   }
6230                   else
6231                   {
6232                      uint64 value = 0;
6233                      if(GetUInt64(e, &value))
6234                      {
6235                         FreeExpContents(exp);
6236                         exp.constant = PrintUInt64(value);
6237                         exp.type = constantExp;
6238                      }
6239                   }
6240                   break;
6241                case intPtrType:
6242                   if(type.isSigned)
6243                   {
6244                      intptr value = 0;
6245                      if(GetIntPtr(e, &value))
6246                      {
6247                         FreeExpContents(exp);
6248                         exp.constant = PrintInt64((int64)value);
6249                         exp.type = constantExp;
6250                      }
6251                   }
6252                   else
6253                   {
6254                      uintptr value = 0;
6255                      if(GetUIntPtr(e, &value))
6256                      {
6257                         FreeExpContents(exp);
6258                         exp.constant = PrintUInt64((uint64)value);
6259                         exp.type = constantExp;
6260                      }
6261                   }
6262                   break;
6263                case intSizeType:
6264                   if(type.isSigned)
6265                   {
6266                      intsize value = 0;
6267                      if(GetIntSize(e, &value))
6268                      {
6269                         FreeExpContents(exp);
6270                         exp.constant = PrintInt64((int64)value);
6271                         exp.type = constantExp;
6272                      }
6273                   }
6274                   else
6275                   {
6276                      uintsize value = 0;
6277                      if(GetUIntSize(e, &value))
6278                      {
6279                         FreeExpContents(exp);
6280                         exp.constant = PrintUInt64((uint64)value);
6281                         exp.type = constantExp;
6282                      }
6283                   }
6284                   break;
6285                case floatType:
6286                {
6287                   float value = 0;
6288                   if(GetFloat(e, &value))
6289                   {
6290                      FreeExpContents(exp);
6291                      exp.constant = PrintFloat(value);
6292                      exp.type = constantExp;
6293                   }
6294                   break;
6295                }
6296                case doubleType:
6297                {
6298                   double value = 0;
6299                   if(GetDouble(e, &value))
6300                   {
6301                      FreeExpContents(exp);
6302                      exp.constant = PrintDouble(value);
6303                      exp.type = constantExp;
6304                   }
6305                   break;
6306                }
6307             }
6308          }
6309          break;
6310       }
6311       case conditionExp:
6312       {
6313          Operand op1 { };
6314          Operand op2 { };
6315          Operand op3 { };
6316
6317          if(exp.cond.exp)
6318             // Caring only about last expression for now...
6319             ComputeExpression(exp.cond.exp->last);
6320          if(exp.cond.elseExp)
6321             ComputeExpression(exp.cond.elseExp);
6322          if(exp.cond.cond)
6323             ComputeExpression(exp.cond.cond);
6324
6325          op1 = GetOperand(exp.cond.cond);
6326          if(op1.type) op1.type.refCount++;
6327          op2 = GetOperand(exp.cond.exp->last);
6328          if(op2.type) op2.type.refCount++;
6329          op3 = GetOperand(exp.cond.elseExp);
6330          if(op3.type) op3.type.refCount++;
6331
6332          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6333          if(op1.type) FreeType(op1.type);
6334          if(op2.type) FreeType(op2.type);
6335          if(op3.type) FreeType(op3.type);
6336          break;
6337       }
6338    }
6339 }
6340
6341 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6342 {
6343    bool result = true;
6344    if(destType)
6345    {
6346       OldList converts { };
6347       Conversion convert;
6348
6349       if(destType.kind == voidType)
6350          return false;
6351
6352       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6353          result = false;
6354       if(converts.count)
6355       {
6356          // for(convert = converts.last; convert; convert = convert.prev)
6357          for(convert = converts.first; convert; convert = convert.next)
6358          {
6359             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6360             if(!empty)
6361             {
6362                Expression newExp { };
6363                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6364
6365                // TODO: Check this...
6366                *newExp = *exp;
6367                newExp.prev = null;
6368                newExp.next = null;
6369                newExp.destType = null;
6370
6371                if(convert.isGet)
6372                {
6373                   // [exp].ColorRGB
6374                   exp.type = memberExp;
6375                   exp.addedThis = true;
6376                   exp.member.exp = newExp;
6377                   FreeType(exp.member.exp.expType);
6378
6379                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6380                   exp.member.exp.expType.classObjectType = objectType;
6381                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6382                   exp.member.memberType = propertyMember;
6383                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6384                   // TESTING THIS... for (int)degrees
6385                   exp.needCast = true;
6386                   if(exp.expType) exp.expType.refCount++;
6387                   ApplyAnyObjectLogic(exp.member.exp);
6388                }
6389                else
6390                {
6391
6392                   /*if(exp.isConstant)
6393                   {
6394                      // Color { ColorRGB = [exp] };
6395                      exp.type = instanceExp;
6396                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6397                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6398                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6399                   }
6400                   else*/
6401                   {
6402                      // If not constant, don't turn it yet into an instantiation
6403                      // (Go through the deep members system first)
6404                      exp.type = memberExp;
6405                      exp.addedThis = true;
6406                      exp.member.exp = newExp;
6407
6408                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6409                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6410                         newExp.expType._class.registered.type == noHeadClass)
6411                      {
6412                         newExp.byReference = true;
6413                      }
6414
6415                      FreeType(exp.member.exp.expType);
6416                      /*exp.member.exp.expType = convert.convert.dataType;
6417                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6418                      exp.member.exp.expType = null;
6419                      if(convert.convert.dataType)
6420                      {
6421                         exp.member.exp.expType = { };
6422                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6423                         exp.member.exp.expType.refCount = 1;
6424                         exp.member.exp.expType.classObjectType = objectType;
6425                         ApplyAnyObjectLogic(exp.member.exp);
6426                      }
6427
6428                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6429                      exp.member.memberType = reverseConversionMember;
6430                      exp.expType = convert.resultType ? convert.resultType :
6431                         MkClassType(convert.convert._class.fullName);
6432                      exp.needCast = true;
6433                      if(convert.resultType) convert.resultType.refCount++;
6434                   }
6435                }
6436             }
6437             else
6438             {
6439                FreeType(exp.expType);
6440                if(convert.isGet)
6441                {
6442                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6443                   if(exp.destType.casted)
6444                      exp.needCast = true;
6445                   if(exp.expType) exp.expType.refCount++;
6446                }
6447                else
6448                {
6449                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6450                   if(exp.destType.casted)
6451                      exp.needCast = true;
6452                   if(convert.resultType)
6453                      convert.resultType.refCount++;
6454                }
6455             }
6456          }
6457          if(exp.isConstant && inCompiler)
6458             ComputeExpression(exp);
6459
6460          converts.Free(FreeConvert);
6461       }
6462
6463       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6464       {
6465          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6466       }
6467       if(!result && exp.expType && exp.destType)
6468       {
6469          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6470              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6471             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6472             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6473             result = true;
6474       }
6475    }
6476    // if(result) CheckTemplateTypes(exp);
6477    return result;
6478 }
6479
6480 void CheckTemplateTypes(Expression exp)
6481 {
6482    /*
6483    bool et = exp.expType ? exp.expType.passAsTemplate : false;
6484    bool dt = exp.destType ? exp.destType.passAsTemplate : false;
6485    */
6486    Expression nbExp = GetNonBracketsExp(exp);
6487    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6488       (nbExp == exp || nbExp.type != castExp))
6489    {
6490       Expression newExp { };
6491       Context context;
6492       TypeKind kind = exp.expType.kind;
6493       *newExp = *exp;
6494       if(exp.destType) exp.destType.refCount++;
6495       if(exp.expType)  exp.expType.refCount++;
6496       newExp.prev = null;
6497       newExp.next = null;
6498
6499       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6500       {
6501          Class c = exp.expType._class.registered;
6502          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6503          {
6504             if(!c.dataType)
6505                c.dataType = ProcessTypeString(c.dataTypeString, false);
6506             kind = c.dataType.kind;
6507          }
6508       }
6509
6510       switch(kind)
6511       {
6512          case doubleType:
6513             if(exp.destType.classObjectType)
6514             {
6515                // We need to pass the address, just pass it along (Undo what was done above)
6516                if(exp.destType) exp.destType.refCount--;
6517                if(exp.expType)  exp.expType.refCount--;
6518                delete newExp;
6519             }
6520             else
6521             {
6522                // If we're looking for value:
6523                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6524                OldList * specs;
6525                OldList * unionDefs = MkList();
6526                OldList * statements = MkList();
6527                context = PushContext();
6528                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6529                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6530                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6531                exp.type = extensionCompoundExp;
6532                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6533                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6534                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6535                exp.compound.compound.context = context;
6536                PopContext(context);
6537             }
6538             break;
6539          default:
6540             exp.type = castExp;
6541             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6542             if((exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass) || exp.expType.isPointerType)
6543                exp.cast.exp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), MkExpBrackets(MkListOne(newExp)));
6544             else
6545                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6546             exp.needCast = true;
6547             break;
6548       }
6549    }
6550    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6551    {
6552       Expression newExp { };
6553       Context context;
6554       TypeKind kind = exp.expType.kind;
6555       *newExp = *exp;
6556       if(exp.destType) exp.destType.refCount++;
6557       if(exp.expType)  exp.expType.refCount++;
6558       newExp.prev = null;
6559       newExp.next = null;
6560
6561       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6562       {
6563          Class c = exp.expType._class.registered;
6564          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6565          {
6566             if(!c.dataType)
6567                c.dataType = ProcessTypeString(c.dataTypeString, false);
6568             kind = c.dataType.kind;
6569          }
6570       }
6571
6572       switch(kind)
6573       {
6574          case doubleType:
6575             if(exp.destType.classObjectType)
6576             {
6577                // We need to pass the address, just pass it along (Undo what was done above)
6578                if(exp.destType) exp.destType.refCount--;
6579                if(exp.expType)  exp.expType.refCount--;
6580                delete newExp;
6581             }
6582             else
6583             {
6584                // If we're looking for value:
6585                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6586                OldList * specs;
6587                OldList * unionDefs = MkList();
6588                OldList * statements = MkList();
6589                context = PushContext();
6590                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6591                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6592                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6593                exp.type = extensionCompoundExp;
6594                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6595                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6596                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6597                exp.compound.compound.context = context;
6598                PopContext(context);
6599             }
6600             break;
6601          case classType:
6602          {
6603             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6604             {
6605                exp.type = bracketsExp;
6606
6607                newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6608                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6609                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6610                ProcessExpressionType(exp.list->first);
6611                break;
6612             }
6613             else
6614             {
6615                exp.type = bracketsExp;
6616                if(exp.expType.isPointerType)
6617                {
6618                   exp.needTemplateCast = 2;
6619                   newExp.needCast = true;
6620                   newExp.needTemplateCast = 2;
6621                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6622                }
6623
6624                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6625                exp.needTemplateCast = 2;
6626                newExp.needCast = true;
6627                newExp.needTemplateCast = 2;
6628                ProcessExpressionType(exp.list->first);
6629                break;
6630             }
6631          }
6632          default:
6633          {
6634             if(exp.expType.kind == templateType)
6635             {
6636                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6637                if(type)
6638                {
6639                   FreeType(exp.destType);
6640                   FreeType(exp.expType);
6641                   delete newExp;
6642                   break;
6643                }
6644             }
6645             /*if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6646             {
6647                // When was this required?    Removed to address using templated values to pass to printf()
6648                exp.type = opExp;
6649                exp.op.op = '*';
6650                exp.op.exp1 = null;
6651                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6652                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6653             }
6654             else*/
6655             {
6656                char typeString[1024];
6657                Declarator decl;
6658                OldList * specs = MkList();
6659                typeString[0] = '\0';
6660                PrintType(exp.expType, typeString, false, false);
6661                decl = SpecDeclFromString(typeString, specs, null);
6662
6663                exp.type = castExp;
6664                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6665                exp.cast.typeName = MkTypeName(specs, decl);
6666                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6667                exp.cast.exp.needCast = true;
6668                exp.needTemplateCast = 2;
6669                newExp.needTemplateCast = 2;
6670             }
6671             break;
6672          }
6673       }
6674    }
6675 }
6676 // TODO: The Symbol tree should be reorganized by namespaces
6677 // Name Space:
6678 //    - Tree of all symbols within (stored without namespace)
6679 //    - Tree of sub-namespaces
6680
6681 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6682 {
6683    int nsLen = strlen(nameSpace);
6684    Symbol symbol;
6685    // Start at the name space prefix
6686    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6687    {
6688       char * s = symbol.string;
6689       if(!strncmp(s, nameSpace, nsLen))
6690       {
6691          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6692          int c;
6693          char * namePart;
6694          for(c = strlen(s)-1; c >= 0; c--)
6695             if(s[c] == ':')
6696                break;
6697
6698          namePart = s+c+1;
6699          if(!strcmp(namePart, name))
6700          {
6701             // TODO: Error on ambiguity
6702             return symbol;
6703          }
6704       }
6705       else
6706          break;
6707    }
6708    return null;
6709 }
6710
6711 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6712 {
6713    int c;
6714    char nameSpace[1024];
6715    const char * namePart;
6716    bool gotColon = false;
6717
6718    nameSpace[0] = '\0';
6719    for(c = strlen(name)-1; c >= 0; c--)
6720       if(name[c] == ':')
6721       {
6722          gotColon = true;
6723          break;
6724       }
6725
6726    namePart = name+c+1;
6727    while(c >= 0 && name[c] == ':') c--;
6728    if(c >= 0)
6729    {
6730       // Try an exact match first
6731       Symbol symbol = (Symbol)tree.FindString(name);
6732       if(symbol)
6733          return symbol;
6734
6735       // Namespace specified
6736       memcpy(nameSpace, name, c + 1);
6737       nameSpace[c+1] = 0;
6738
6739       return ScanWithNameSpace(tree, nameSpace, namePart);
6740    }
6741    else if(gotColon)
6742    {
6743       // Looking for a global symbol, e.g. ::Sleep()
6744       Symbol symbol = (Symbol)tree.FindString(namePart);
6745       return symbol;
6746    }
6747    else
6748    {
6749       // Name only (no namespace specified)
6750       Symbol symbol = (Symbol)tree.FindString(namePart);
6751       if(symbol)
6752          return symbol;
6753       return ScanWithNameSpace(tree, "", namePart);
6754    }
6755    return null;
6756 }
6757
6758 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6759 {
6760 #ifdef _DEBUG
6761    //Time startTime = GetTime();
6762 #endif
6763    // Optimize this later? Do this before/less?
6764    Context ctx;
6765    Symbol symbol = null;
6766
6767    // First, check if the identifier is declared inside the function
6768    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6769
6770    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6771    {
6772       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6773       {
6774          symbol = null;
6775          if(thisNameSpace)
6776          {
6777             char curName[1024];
6778             strcpy(curName, thisNameSpace);
6779             strcat(curName, "::");
6780             strcat(curName, name);
6781             // Try to resolve in current namespace first
6782             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6783          }
6784          if(!symbol)
6785             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6786       }
6787       else
6788          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6789
6790       if(symbol || ctx == endContext) break;
6791    }
6792    if(inCompiler && symbol && ctx == globalContext && symbol.pointerExternal && curExternal && symbol.pointerExternal != curExternal)
6793       curExternal.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
6794 #ifdef _DEBUG
6795    //findSymbolTotalTime += GetTime() - startTime;
6796 #endif
6797    return symbol;
6798 }
6799
6800 static void GetTypeSpecs(Type type, OldList * specs)
6801 {
6802    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6803    switch(type.kind)
6804    {
6805       case classType:
6806       {
6807          if(type._class.registered)
6808          {
6809             if(!type._class.registered.dataType)
6810                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6811             GetTypeSpecs(type._class.registered.dataType, specs);
6812          }
6813          break;
6814       }
6815       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6816       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6817       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6818       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6819       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6820       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6821       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6822       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6823       case intType:
6824       default:
6825          ListAdd(specs, MkSpecifier(INT)); break;
6826    }
6827 }
6828
6829 static void PrintArraySize(Type arrayType, char * string)
6830 {
6831    char size[256];
6832    size[0] = '\0';
6833    strcat(size, "[");
6834    if(arrayType.enumClass)
6835       strcat(size, arrayType.enumClass.string);
6836    else if(arrayType.arraySizeExp)
6837       PrintExpression(arrayType.arraySizeExp, size);
6838    strcat(size, "]");
6839    strcat(string, size);
6840 }
6841
6842 // WARNING : This function expects a null terminated string since it recursively concatenate...
6843 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6844 {
6845    if(type)
6846    {
6847       if(printConst && type.constant)
6848          strcat(string, "const ");
6849       switch(type.kind)
6850       {
6851          case classType:
6852          {
6853             Symbol c = type._class;
6854             bool isObjectBaseClass = !c || !c.string || !strcmp(c.string, "class");
6855             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6856             //       look into merging with thisclass ?
6857             if(type.classObjectType == typedObject && isObjectBaseClass)
6858                strcat(string, "typed_object");
6859             else if(type.classObjectType == anyObject && isObjectBaseClass)
6860                strcat(string, "any_object");
6861             else
6862             {
6863                if(c && c.string)
6864                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6865             }
6866             if(type.byReference)
6867                strcat(string, " &");
6868             break;
6869          }
6870          case voidType: strcat(string, "void"); break;
6871          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6872          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6873          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6874          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6875          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6876          case _BoolType: strcat(string, "_Bool"); break;
6877          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6878          case floatType: strcat(string, "float"); break;
6879          case doubleType: strcat(string, "double"); break;
6880          case structType:
6881             if(type.enumName)
6882             {
6883                strcat(string, "struct ");
6884                strcat(string, type.enumName);
6885             }
6886             else if(type.typeName)
6887                strcat(string, type.typeName);
6888             else
6889             {
6890                Type member;
6891                strcat(string, "struct { ");
6892                for(member = type.members.first; member; member = member.next)
6893                {
6894                   PrintType(member, string, true, fullName);
6895                   strcat(string,"; ");
6896                }
6897                strcat(string,"}");
6898             }
6899             break;
6900          case unionType:
6901             if(type.enumName)
6902             {
6903                strcat(string, "union ");
6904                strcat(string, type.enumName);
6905             }
6906             else if(type.typeName)
6907                strcat(string, type.typeName);
6908             else
6909             {
6910                strcat(string, "union ");
6911                strcat(string,"(unnamed)");
6912             }
6913             break;
6914          case enumType:
6915             if(type.enumName)
6916             {
6917                strcat(string, "enum ");
6918                strcat(string, type.enumName);
6919             }
6920             else if(type.typeName)
6921                strcat(string, type.typeName);
6922             else
6923                strcat(string, "int"); // "enum");
6924             break;
6925          case ellipsisType:
6926             strcat(string, "...");
6927             break;
6928          case subClassType:
6929             strcat(string, "subclass(");
6930             strcat(string, type._class ? type._class.string : "int");
6931             strcat(string, ")");
6932             break;
6933          case templateType:
6934             strcat(string, type.templateParameter.identifier.string);
6935             break;
6936          case thisClassType:
6937             strcat(string, "thisclass");
6938             break;
6939          case vaListType:
6940             strcat(string, "__builtin_va_list");
6941             break;
6942       }
6943    }
6944 }
6945
6946 static void PrintName(Type type, char * string, bool fullName)
6947 {
6948    if(type.name && type.name[0])
6949    {
6950       if(fullName)
6951          strcat(string, type.name);
6952       else
6953       {
6954          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
6955          if(name) name += 2; else name = type.name;
6956          strcat(string, name);
6957       }
6958    }
6959 }
6960
6961 static void PrintAttribs(Type type, char * string)
6962 {
6963    if(type)
6964    {
6965       if(type.dllExport)   strcat(string, "dllexport ");
6966       if(type.attrStdcall) strcat(string, "stdcall ");
6967    }
6968 }
6969
6970 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
6971 {
6972    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
6973    {
6974       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
6975          PrintAttribs(type, string);
6976       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
6977          strcat(string, " const");
6978       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
6979       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
6980          strcat(string, " (");
6981       if(type.kind == pointerType)
6982       {
6983          if(type.type.kind == functionType || type.type.kind == methodType)
6984             PrintAttribs(type.type, string);
6985       }
6986       if(type.kind == pointerType)
6987       {
6988          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
6989             strcat(string, "*");
6990          else
6991             strcat(string, " *");
6992       }
6993       if(printConst && type.constant && type.kind == pointerType)
6994          strcat(string, " const");
6995    }
6996    else
6997       PrintTypeSpecs(type, string, fullName, printConst);
6998 }
6999
7000 static void PostPrintType(Type type, char * string, bool fullName)
7001 {
7002    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7003       strcat(string, ")");
7004    if(type.kind == arrayType)
7005       PrintArraySize(type, string);
7006    else if(type.kind == functionType)
7007    {
7008       Type param;
7009       strcat(string, "(");
7010       for(param = type.params.first; param; param = param.next)
7011       {
7012          PrintType(param, string, true, fullName);
7013          if(param.next) strcat(string, ", ");
7014       }
7015       strcat(string, ")");
7016    }
7017    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7018       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7019 }
7020
7021 // *****
7022 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7023 // *****
7024 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7025 {
7026    PrePrintType(type, string, fullName, null, printConst);
7027
7028    if(type.thisClass || (printName && type.name && type.name[0]))
7029       strcat(string, " ");
7030    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7031    {
7032       Symbol _class = type.thisClass;
7033       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7034       {
7035          if(type.classObjectType == classPointer)
7036             strcat(string, "class");
7037          else
7038             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7039       }
7040       else if(_class && _class.string)
7041       {
7042          String s = _class.string;
7043          if(fullName)
7044             strcat(string, s);
7045          else
7046          {
7047             char * name = RSearchString(s, "::", strlen(s), true, false);
7048             if(name) name += 2; else name = s;
7049             strcat(string, name);
7050          }
7051       }
7052       strcat(string, "::");
7053    }
7054
7055    if(printName && type.name)
7056       PrintName(type, string, fullName);
7057    PostPrintType(type, string, fullName);
7058    if(type.bitFieldCount)
7059    {
7060       char count[100];
7061       sprintf(count, ":%d", type.bitFieldCount);
7062       strcat(string, count);
7063    }
7064 }
7065
7066 void PrintType(Type type, char * string, bool printName, bool fullName)
7067 {
7068    _PrintType(type, string, printName, fullName, true);
7069 }
7070
7071 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7072 {
7073    _PrintType(type, string, printName, fullName, false);
7074 }
7075
7076 static Type FindMember(Type type, char * string)
7077 {
7078    Type memberType;
7079    for(memberType = type.members.first; memberType; memberType = memberType.next)
7080    {
7081       if(!memberType.name)
7082       {
7083          Type subType = FindMember(memberType, string);
7084          if(subType)
7085             return subType;
7086       }
7087       else if(!strcmp(memberType.name, string))
7088          return memberType;
7089    }
7090    return null;
7091 }
7092
7093 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7094 {
7095    Type memberType;
7096    for(memberType = type.members.first; memberType; memberType = memberType.next)
7097    {
7098       if(!memberType.name)
7099       {
7100          Type subType = FindMember(memberType, string);
7101          if(subType)
7102          {
7103             *offset += memberType.offset;
7104             return subType;
7105          }
7106       }
7107       else if(!strcmp(memberType.name, string))
7108       {
7109          *offset += memberType.offset;
7110          return memberType;
7111       }
7112    }
7113    return null;
7114 }
7115
7116 public bool GetParseError() { return parseError; }
7117
7118 Expression ParseExpressionString(char * expression)
7119 {
7120    parseError = false;
7121
7122    fileInput = TempFile { };
7123    fileInput.Write(expression, 1, strlen(expression));
7124    fileInput.Seek(0, start);
7125
7126    echoOn = false;
7127    parsedExpression = null;
7128    resetScanner();
7129    expression_yyparse();
7130    delete fileInput;
7131
7132    return parsedExpression;
7133 }
7134
7135 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7136 {
7137    Identifier id = exp.identifier;
7138    Method method = null;
7139    Property prop = null;
7140    DataMember member = null;
7141    ClassProperty classProp = null;
7142
7143    if(_class && _class.type == enumClass)
7144    {
7145       NamedLink64 value = null;
7146       Class enumClass = eSystem_FindClass(privateModule, "enum");
7147       if(enumClass)
7148       {
7149          Class baseClass;
7150          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7151          {
7152             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7153             for(value = e.values.first; value; value = value.next)
7154             {
7155                if(!strcmp(value.name, id.string))
7156                   break;
7157             }
7158             if(value)
7159             {
7160                exp.isConstant = true;
7161                if(inCompiler || inPreCompiler || inDebugger)
7162                {
7163                   char constant[256];
7164                   FreeExpContents(exp);
7165
7166                   exp.type = constantExp;
7167                   if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7168                      sprintf(constant, FORMAT64D, value.data);
7169                   else
7170                      sprintf(constant, FORMAT64HEX, value.data);
7171                   exp.constant = CopyString(constant);
7172                }
7173                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7174                exp.expType = MkClassType(baseClass.fullName);
7175                break;
7176             }
7177          }
7178       }
7179       if(value)
7180          return true;
7181    }
7182    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7183    {
7184       ProcessMethodType(method);
7185       exp.expType = Type
7186       {
7187          refCount = 1;
7188          kind = methodType;
7189          method = method;
7190          // Crash here?
7191          // TOCHECK: Put it back to what it was...
7192          // methodClass = _class;
7193          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7194       };
7195       //id._class = null;
7196       return true;
7197    }
7198    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7199    {
7200       if(!prop.dataType)
7201          ProcessPropertyType(prop);
7202       exp.expType = prop.dataType;
7203       if(prop.dataType) prop.dataType.refCount++;
7204       return true;
7205    }
7206    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7207    {
7208       if(!member.dataType)
7209          member.dataType = ProcessTypeString(member.dataTypeString, false);
7210       exp.expType = member.dataType;
7211       if(member.dataType) member.dataType.refCount++;
7212       return true;
7213    }
7214    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7215    {
7216       if(!classProp.dataType)
7217          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7218
7219       if(classProp.constant)
7220       {
7221          FreeExpContents(exp);
7222
7223          exp.isConstant = true;
7224          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7225          {
7226             //char constant[256];
7227             exp.type = stringExp;
7228             exp.constant = QMkString((char *)(uintptr)classProp.Get(_class));
7229          }
7230          else
7231          {
7232             char constant[256];
7233             exp.type = constantExp;
7234             sprintf(constant, "%d", (int)classProp.Get(_class));
7235             exp.constant = CopyString(constant);
7236          }
7237       }
7238       else
7239       {
7240          // TO IMPLEMENT...
7241       }
7242
7243       exp.expType = classProp.dataType;
7244       if(classProp.dataType) classProp.dataType.refCount++;
7245       return true;
7246    }
7247    return false;
7248 }
7249
7250 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7251 {
7252    BinaryTree * tree = &nameSpace.functions;
7253    GlobalData data = (GlobalData)tree->FindString(name);
7254    NameSpace * child;
7255    if(!data)
7256    {
7257       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7258       {
7259          data = ScanGlobalData(child, name);
7260          if(data)
7261             break;
7262       }
7263    }
7264    return data;
7265 }
7266
7267 static GlobalData FindGlobalData(char * name)
7268 {
7269    int start = 0, c;
7270    NameSpace * nameSpace;
7271    nameSpace = globalData;
7272    for(c = 0; name[c]; c++)
7273    {
7274       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7275       {
7276          NameSpace * newSpace;
7277          char * spaceName = new char[c - start + 1];
7278          strncpy(spaceName, name + start, c - start);
7279          spaceName[c-start] = '\0';
7280          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7281          delete spaceName;
7282          if(!newSpace)
7283             return null;
7284          nameSpace = newSpace;
7285          if(name[c] == ':') c++;
7286          start = c+1;
7287       }
7288    }
7289    if(c - start)
7290    {
7291       return ScanGlobalData(nameSpace, name + start);
7292    }
7293    return null;
7294 }
7295
7296 static int definedExpStackPos;
7297 static void * definedExpStack[512];
7298
7299 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7300 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7301 {
7302    Expression prev = checkedExp.prev, next = checkedExp.next;
7303
7304    FreeExpContents(checkedExp);
7305    FreeType(checkedExp.expType);
7306    FreeType(checkedExp.destType);
7307
7308    *checkedExp = *newExp;
7309
7310    delete newExp;
7311
7312    checkedExp.prev = prev;
7313    checkedExp.next = next;
7314 }
7315
7316 void ApplyAnyObjectLogic(Expression e)
7317 {
7318    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7319 #ifdef _DEBUG
7320    char debugExpString[4096];
7321    debugExpString[0] = '\0';
7322    PrintExpression(e, debugExpString);
7323 #endif
7324
7325    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7326    {
7327       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7328       //ellipsisDestType = destType;
7329       if(e && e.expType)
7330       {
7331          Type type = e.expType;
7332          Class _class = null;
7333          //Type destType = e.destType;
7334
7335          if(type.kind == classType && type._class && type._class.registered)
7336          {
7337             _class = type._class.registered;
7338          }
7339          else if(type.kind == subClassType)
7340          {
7341             _class = FindClass("ecere::com::Class").registered;
7342          }
7343          else
7344          {
7345             char string[1024] = "";
7346             Symbol classSym;
7347
7348             PrintTypeNoConst(type, string, false, true);
7349             classSym = FindClass(string);
7350             if(classSym) _class = classSym.registered;
7351          }
7352
7353          if((_class && (_class.type == enumClass || _class.type == unitClass || _class.type == bitClass || _class.type == systemClass) && strcmp(_class.fullName, "class") && strcmp(_class.fullName, "uintptr") && strcmp(_class.fullName, "intptr")) || // Patched so that class isn't considered SYSTEM...
7354             (!e.expType.classObjectType && (((type.kind != pointerType && type.kind != intPtrType && type.kind != subClassType && (type.kind != classType || !type._class || !type._class.registered || type._class.registered.type == structClass))) ||
7355             destType.byReference)))
7356          {
7357             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7358             {
7359                Expression checkedExp = e, newExp;
7360
7361                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7362                {
7363                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7364                   {
7365                      if(checkedExp.type == extensionCompoundExp)
7366                      {
7367                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7368                      }
7369                      else
7370                         checkedExp = checkedExp.list->last;
7371                   }
7372                   else if(checkedExp.type == castExp)
7373                      checkedExp = checkedExp.cast.exp;
7374                }
7375
7376                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7377                {
7378                   newExp = checkedExp.op.exp2;
7379                   checkedExp.op.exp2 = null;
7380                   FreeExpContents(checkedExp);
7381
7382                   if(e.expType && e.expType.passAsTemplate)
7383                   {
7384                      char size[100];
7385                      ComputeTypeSize(e.expType);
7386                      sprintf(size, "%d", e.expType.size);   // Potential 32/64 Bootstrap issue
7387                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7388                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7389                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7390                   }
7391
7392                   ReplaceExpContents(checkedExp, newExp);
7393                   e.byReference = true;
7394                }
7395                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7396                {
7397                   Expression checkedExp; //, newExp;
7398
7399                   {
7400                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7401                      bool hasAddress =
7402                         e.type == identifierExp ||
7403                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7404                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7405                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7406                         e.type == indexExp;
7407
7408                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7409                      {
7410                         Context context = PushContext();
7411                         Declarator decl;
7412                         OldList * specs = MkList();
7413                         char typeString[1024];
7414                         Expression newExp { };
7415
7416                         typeString[0] = '\0';
7417                         *newExp = *e;
7418
7419                         //if(e.destType) e.destType.refCount++;
7420                         // if(exp.expType) exp.expType.refCount++;
7421                         newExp.prev = null;
7422                         newExp.next = null;
7423                         newExp.expType = null;
7424
7425                         PrintTypeNoConst(e.expType, typeString, false, true);
7426                         decl = SpecDeclFromString(typeString, specs, null);
7427                         newExp.destType = ProcessType(specs, decl);
7428
7429                         curContext = context;
7430
7431                         // We need a current compound for this
7432                         if(curCompound)
7433                         {
7434                            char name[100];
7435                            OldList * stmts = MkList();
7436                            e.type = extensionCompoundExp;
7437                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7438                            if(!curCompound.compound.declarations)
7439                               curCompound.compound.declarations = MkList();
7440                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7441                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7442                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7443                            e.compound = MkCompoundStmt(null, stmts);
7444                         }
7445                         else
7446                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7447
7448                         /*
7449                         e.compound = MkCompoundStmt(
7450                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7451                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7452
7453                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7454                         */
7455
7456                         {
7457                            Type type = e.destType;
7458                            e.destType = { };
7459                            CopyTypeInto(e.destType, type);
7460                            e.destType.refCount = 1;
7461                            e.destType.classObjectType = none;
7462                            FreeType(type);
7463                         }
7464
7465                         e.compound.compound.context = context;
7466                         PopContext(context);
7467                         curContext = context.parent;
7468                      }
7469                   }
7470
7471                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7472                   checkedExp = e;
7473                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7474                   {
7475                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7476                      {
7477                         if(checkedExp.type == extensionCompoundExp)
7478                         {
7479                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7480                         }
7481                         else
7482                            checkedExp = checkedExp.list->last;
7483                      }
7484                      else if(checkedExp.type == castExp)
7485                         checkedExp = checkedExp.cast.exp;
7486                   }
7487                   {
7488                      Expression operand { };
7489                      operand = *checkedExp;
7490                      checkedExp.Clear();
7491                      checkedExp.destType = ProcessTypeString("void *", false);
7492                      checkedExp.expType = checkedExp.destType;
7493                      checkedExp.destType.refCount++;
7494
7495                      checkedExp.type = opExp;
7496                      checkedExp.op.op = '&';
7497                      checkedExp.op.exp1 = null;
7498                      checkedExp.op.exp2 = operand;
7499
7500                      //newExp = MkExpOp(null, '&', checkedExp);
7501                   }
7502                   //ReplaceExpContents(checkedExp, newExp);
7503                }
7504             }
7505          }
7506       }
7507    }
7508    {
7509       // If expression type is a simple class, make it an address
7510       // FixReference(e, true);
7511    }
7512 //#if 0
7513    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7514       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7515          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7516    {
7517       if(e.expType.classObjectType && destType && destType.classObjectType) //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class"))
7518       {
7519          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7520       }
7521       else
7522       {
7523          Expression thisExp { };
7524
7525          *thisExp = *e;
7526          thisExp.prev = null;
7527          thisExp.next = null;
7528          e.Clear();
7529
7530          e.type = bracketsExp;
7531          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7532          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7533             ((Expression)e.list->first).byReference = true;
7534
7535          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7536          {
7537             e.expType = thisExp.expType;
7538             e.expType.refCount++;
7539          }
7540          else*/
7541          {
7542             e.expType = { };
7543             CopyTypeInto(e.expType, thisExp.expType);
7544             e.expType.byReference = false;
7545             e.expType.refCount = 1;
7546
7547             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7548                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7549             {
7550                e.expType.classObjectType = none;
7551             }
7552          }
7553       }
7554    }
7555 // TOFIX: Try this for a nice IDE crash!
7556 //#endif
7557    // The other way around
7558    else
7559 //#endif
7560    if(destType && e.expType &&
7561          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7562          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7563          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7564    {
7565       if(destType.kind == ellipsisType)
7566       {
7567          Compiler_Error($"Unspecified type\n");
7568       }
7569       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7570       {
7571          bool byReference = e.expType.byReference;
7572          Expression thisExp { };
7573          Declarator decl;
7574          OldList * specs = MkList();
7575          char typeString[1024]; // Watch buffer overruns
7576          Type type;
7577          ClassObjectType backupClassObjectType;
7578          bool backupByReference;
7579
7580          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7581             type = e.expType;
7582          else
7583             type = destType;
7584
7585          backupClassObjectType = type.classObjectType;
7586          backupByReference = type.byReference;
7587
7588          type.classObjectType = none;
7589          type.byReference = false;
7590
7591          typeString[0] = '\0';
7592          PrintType(type, typeString, false, true);
7593          decl = SpecDeclFromString(typeString, specs, null);
7594
7595          type.classObjectType = backupClassObjectType;
7596          type.byReference = backupByReference;
7597
7598          *thisExp = *e;
7599          thisExp.prev = null;
7600          thisExp.next = null;
7601          e.Clear();
7602
7603          if( ( type.kind == classType && type._class && type._class.registered &&
7604                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7605                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7606              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7607              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7608          {
7609             bool passAsTemplate = thisExp.destType.passAsTemplate;
7610             Type t;
7611
7612             destType.refCount++;
7613
7614             e.type = opExp;
7615             e.op.op = '*';
7616             e.op.exp1 = null;
7617             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7618
7619             t = { };
7620             CopyTypeInto(t, thisExp.destType);
7621             t.passAsTemplate = false;
7622             FreeType(thisExp.destType);
7623             thisExp.destType = t;
7624
7625             t = { };
7626             CopyTypeInto(t, destType);
7627             t.passAsTemplate = passAsTemplate;
7628             FreeType(destType);
7629             destType = t;
7630             destType.refCount = 0;
7631
7632             e.expType = { };
7633             CopyTypeInto(e.expType, type);
7634             if(type.passAsTemplate)
7635             {
7636                e.expType.classObjectType = none;
7637                e.expType.passAsTemplate = false;
7638             }
7639             e.expType.byReference = false;
7640             e.expType.refCount = 1;
7641          }
7642          else
7643          {
7644             e.type = castExp;
7645             e.cast.typeName = MkTypeName(specs, decl);
7646             e.cast.exp = thisExp;
7647             e.byReference = true;
7648             e.expType = type;
7649             type.refCount++;
7650          }
7651
7652          if(e.destType)
7653             FreeType(e.destType);
7654
7655          e.destType = destType;
7656          destType.refCount++;
7657       }
7658    }
7659 }
7660
7661 void ApplyLocation(Expression exp, Location loc)
7662 {
7663    exp.loc = loc;
7664    switch(exp.type)
7665    {
7666       case opExp:
7667          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7668          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7669          break;
7670       case bracketsExp:
7671          if(exp.list)
7672          {
7673             Expression e;
7674             for(e = exp.list->first; e; e = e.next)
7675                ApplyLocation(e, loc);
7676          }
7677          break;
7678       case indexExp:
7679          if(exp.index.index)
7680          {
7681             Expression e;
7682             for(e = exp.index.index->first; e; e = e.next)
7683                ApplyLocation(e, loc);
7684          }
7685          if(exp.index.exp)
7686             ApplyLocation(exp.index.exp, loc);
7687          break;
7688       case callExp:
7689          if(exp.call.arguments)
7690          {
7691             Expression arg;
7692             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7693                ApplyLocation(arg, loc);
7694          }
7695          if(exp.call.exp)
7696             ApplyLocation(exp.call.exp, loc);
7697          break;
7698       case memberExp:
7699       case pointerExp:
7700          if(exp.member.exp)
7701             ApplyLocation(exp.member.exp, loc);
7702          break;
7703       case castExp:
7704          if(exp.cast.exp)
7705             ApplyLocation(exp.cast.exp, loc);
7706          break;
7707       case conditionExp:
7708          if(exp.cond.exp)
7709          {
7710             Expression e;
7711             for(e = exp.cond.exp->first; e; e = e.next)
7712                ApplyLocation(e, loc);
7713          }
7714          if(exp.cond.cond)
7715             ApplyLocation(exp.cond.cond, loc);
7716          if(exp.cond.elseExp)
7717             ApplyLocation(exp.cond.elseExp, loc);
7718          break;
7719       case vaArgExp:
7720          if(exp.vaArg.exp)
7721             ApplyLocation(exp.vaArg.exp, loc);
7722          break;
7723       default:
7724          break;
7725    }
7726 }
7727
7728 void ProcessExpressionType(Expression exp)
7729 {
7730    bool unresolved = false;
7731    Location oldyylloc = yylloc;
7732    bool notByReference = false;
7733 #ifdef _DEBUG
7734    char debugExpString[4096];
7735    debugExpString[0] = '\0';
7736    PrintExpression(exp, debugExpString);
7737 #endif
7738    if(!exp || exp.expType)
7739       return;
7740
7741    //eSystem_Logf("%s\n", expString);
7742
7743    // Testing this here
7744    yylloc = exp.loc;
7745    switch(exp.type)
7746    {
7747       case identifierExp:
7748       {
7749          Identifier id = exp.identifier;
7750          if(!id || !topContext) return;
7751
7752          // DOING THIS LATER NOW...
7753          if(id._class && id._class.name)
7754          {
7755             id.classSym = id._class.symbol; // FindClass(id._class.name);
7756             /* TODO: Name Space Fix ups
7757             if(!id.classSym)
7758                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7759             */
7760          }
7761
7762          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7763          {
7764             exp.expType = ProcessTypeString("Module", true);
7765             break;
7766          }
7767          else */
7768          if(!strcmp(id.string, "__runtimePlatform"))
7769          {
7770             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7771             break;
7772          }
7773          else if(strstr(id.string, "__ecereClass") == id.string)
7774          {
7775             exp.expType = ProcessTypeString("ecere::com::Class", true);
7776             break;
7777          }
7778          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7779          {
7780             // Added this here as well
7781             ReplaceClassMembers(exp, thisClass);
7782             if(exp.type != identifierExp)
7783             {
7784                ProcessExpressionType(exp);
7785                break;
7786             }
7787
7788             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7789                break;
7790          }
7791          else
7792          {
7793             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7794             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7795             if(!symbol/* && exp.destType*/)
7796             {
7797                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7798                   break;
7799                else
7800                {
7801                   if(thisClass)
7802                   {
7803                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7804                      if(exp.type != identifierExp)
7805                      {
7806                         ProcessExpressionType(exp);
7807                         break;
7808                      }
7809                   }
7810                   // Static methods called from inside the _class
7811                   else if(currentClass && !id._class)
7812                   {
7813                      if(ResolveIdWithClass(exp, currentClass, true))
7814                         break;
7815                   }
7816                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7817                }
7818             }
7819
7820             // If we manage to resolve this symbol
7821             if(symbol)
7822             {
7823                Type type = symbol.type;
7824                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7825
7826                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7827                {
7828                   Context context = SetupTemplatesContext(_class);
7829                   type = ReplaceThisClassType(_class);
7830                   FinishTemplatesContext(context);
7831                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7832                }
7833
7834                FreeSpecifier(id._class);
7835                id._class = null;
7836                delete id.string;
7837                id.string = CopyString(symbol.string);
7838
7839                id.classSym = null;
7840                exp.expType = type;
7841                if(type)
7842                   type.refCount++;
7843
7844                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7845                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7846                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7847                   // Add missing cases here... enum Classes...
7848                   exp.isConstant = true;
7849
7850                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7851                if(symbol.isParam || !strcmp(id.string, "this"))
7852                {
7853                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7854                      exp.byReference = true;
7855
7856                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7857                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7858                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7859                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7860                   {
7861                      Identifier id = exp.identifier;
7862                      exp.type = bracketsExp;
7863                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7864                   }*/
7865                }
7866
7867                if(symbol.isIterator)
7868                {
7869                   if(symbol.isIterator == 3)
7870                   {
7871                      exp.type = bracketsExp;
7872                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7873                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7874                      exp.expType = null;
7875                      ProcessExpressionType(exp);
7876                   }
7877                   else if(symbol.isIterator != 4)
7878                   {
7879                      exp.type = memberExp;
7880                      exp.member.exp = MkExpIdentifier(exp.identifier);
7881                      exp.member.exp.expType = exp.expType;
7882                      /*if(symbol.isIterator == 6)
7883                         exp.member.member = MkIdentifier("key");
7884                      else*/
7885                         exp.member.member = MkIdentifier("data");
7886                      exp.expType = null;
7887                      ProcessExpressionType(exp);
7888                   }
7889                }
7890                break;
7891             }
7892             else
7893             {
7894                DefinedExpression definedExp = null;
7895                if(thisNameSpace && !(id._class && !id._class.name))
7896                {
7897                   char name[1024];
7898                   strcpy(name, thisNameSpace);
7899                   strcat(name, "::");
7900                   strcat(name, id.string);
7901                   definedExp = eSystem_FindDefine(privateModule, name);
7902                }
7903                if(!definedExp)
7904                   definedExp = eSystem_FindDefine(privateModule, id.string);
7905                if(definedExp)
7906                {
7907                   int c;
7908                   for(c = 0; c<definedExpStackPos; c++)
7909                      if(definedExpStack[c] == definedExp)
7910                         break;
7911                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7912                   {
7913                      Location backupYylloc = yylloc;
7914                      File backInput = fileInput;
7915                      definedExpStack[definedExpStackPos++] = definedExp;
7916
7917                      fileInput = TempFile { };
7918                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7919                      fileInput.Seek(0, start);
7920
7921                      echoOn = false;
7922                      parsedExpression = null;
7923                      resetScanner();
7924                      expression_yyparse();
7925                      delete fileInput;
7926                      if(backInput)
7927                         fileInput = backInput;
7928
7929                      yylloc = backupYylloc;
7930
7931                      if(parsedExpression)
7932                      {
7933                         FreeIdentifier(id);
7934                         exp.type = bracketsExp;
7935                         exp.list = MkListOne(parsedExpression);
7936                         ApplyLocation(parsedExpression, yylloc);
7937                         ProcessExpressionType(exp);
7938                         definedExpStackPos--;
7939                         return;
7940                      }
7941                      definedExpStackPos--;
7942                   }
7943                   else
7944                   {
7945                      if(inCompiler)
7946                      {
7947                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7948                      }
7949                   }
7950                }
7951                else
7952                {
7953                   GlobalData data = null;
7954                   if(thisNameSpace && !(id._class && !id._class.name))
7955                   {
7956                      char name[1024];
7957                      strcpy(name, thisNameSpace);
7958                      strcat(name, "::");
7959                      strcat(name, id.string);
7960                      data = FindGlobalData(name);
7961                   }
7962                   if(!data)
7963                      data = FindGlobalData(id.string);
7964                   if(data)
7965                   {
7966                      DeclareGlobalData(curExternal, data);
7967                      exp.expType = data.dataType;
7968                      if(data.dataType) data.dataType.refCount++;
7969
7970                      delete id.string;
7971                      id.string = CopyString(data.fullName);
7972                      FreeSpecifier(id._class);
7973                      id._class = null;
7974
7975                      break;
7976                   }
7977                   else
7978                   {
7979                      GlobalFunction function = null;
7980                      if(thisNameSpace && !(id._class && !id._class.name))
7981                      {
7982                         char name[1024];
7983                         strcpy(name, thisNameSpace);
7984                         strcat(name, "::");
7985                         strcat(name, id.string);
7986                         function = eSystem_FindFunction(privateModule, name);
7987                      }
7988                      if(!function)
7989                         function = eSystem_FindFunction(privateModule, id.string);
7990                      if(function)
7991                      {
7992                         char name[1024];
7993                         delete id.string;
7994                         id.string = CopyString(function.name);
7995                         name[0] = 0;
7996
7997                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
7998                            strcpy(name, "__ecereFunction_");
7999                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8000                         if(DeclareFunction(curExternal, function, name))
8001                         {
8002                            delete id.string;
8003                            id.string = CopyString(name);
8004                         }
8005                         exp.expType = function.dataType;
8006                         if(function.dataType) function.dataType.refCount++;
8007
8008                         FreeSpecifier(id._class);
8009                         id._class = null;
8010
8011                         break;
8012                      }
8013                   }
8014                }
8015             }
8016          }
8017          unresolved = true;
8018          break;
8019       }
8020       case instanceExp:
8021       {
8022          // Class _class;
8023          // Symbol classSym;
8024
8025          if(!exp.instance._class)
8026          {
8027             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8028             {
8029                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8030             }
8031          }
8032
8033          //classSym = FindClass(exp.instance._class.fullName);
8034          //_class = classSym ? classSym.registered : null;
8035
8036          ProcessInstantiationType(exp.instance);
8037
8038          exp.isConstant = exp.instance.isConstant;
8039
8040          /*
8041          if(_class.type == unitClass && _class.base.type != systemClass)
8042          {
8043             {
8044                Type destType = exp.destType;
8045
8046                exp.destType = MkClassType(_class.base.fullName);
8047                exp.expType = MkClassType(_class.fullName);
8048                CheckExpressionType(exp, exp.destType, true);
8049
8050                exp.destType = destType;
8051             }
8052             exp.expType = MkClassType(_class.fullName);
8053          }
8054          else*/
8055          if(exp.instance._class)
8056          {
8057             exp.expType = MkClassType(exp.instance._class.name);
8058             /*if(exp.expType._class && exp.expType._class.registered &&
8059                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8060                exp.expType.byReference = true;*/
8061          }
8062          break;
8063       }
8064       case constantExp:
8065       {
8066          if(!exp.expType)
8067          {
8068             char * constant = exp.constant;
8069             Type type
8070             {
8071                refCount = 1;
8072                constant = true;
8073             };
8074             exp.expType = type;
8075
8076             if(constant[0] == '\'')
8077             {
8078                if((int)((byte *)constant)[1] > 127)
8079                {
8080                   int nb;
8081                   unichar ch = UTF8GetChar(constant + 1, &nb);
8082                   if(nb < 2) ch = constant[1];
8083                   delete constant;
8084                   exp.constant = PrintUInt(ch);
8085                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8086                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8087                   type._class = FindClass("unichar");
8088
8089                   type.isSigned = false;
8090                }
8091                else
8092                {
8093                   type.kind = charType;
8094                   type.isSigned = true;
8095                }
8096             }
8097             else
8098             {
8099                char * dot = strchr(constant, '.');
8100                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8101                char * exponent;
8102                if(isHex)
8103                {
8104                   exponent = strchr(constant, 'p');
8105                   if(!exponent) exponent = strchr(constant, 'P');
8106                }
8107                else
8108                {
8109                   exponent = strchr(constant, 'e');
8110                   if(!exponent) exponent = strchr(constant, 'E');
8111                }
8112
8113                if(dot || exponent)
8114                {
8115                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8116                      type.kind = floatType;
8117                   else
8118                      type.kind = doubleType;
8119                   type.isSigned = true;
8120                }
8121                else
8122                {
8123                   bool isSigned = constant[0] == '-';
8124                   char * endP = null;
8125                   int64 i64 = strtoll(constant, &endP, 0);
8126                   uint64 ui64 = strtoull(constant, &endP, 0);
8127                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8128                   bool forceUnsigned = endP && (!strcmp(endP, "U") || !strcmp(endP, "u") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8129                   if(isSigned)
8130                   {
8131                      if(i64 < MININT)
8132                         is64Bit = true;
8133                   }
8134                   else
8135                   {
8136                      if(ui64 > MAXINT)
8137                      {
8138                         if(ui64 > MAXDWORD)
8139                         {
8140                            is64Bit = true;
8141                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8142                               isSigned = true;
8143                         }
8144                      }
8145                      else if(constant[0] != '0' || !constant[1])
8146                         isSigned = true;
8147                   }
8148                   if(forceUnsigned)
8149                      isSigned = false;
8150                   type.kind = is64Bit ? int64Type : intType;
8151                   type.isSigned = isSigned;
8152                }
8153             }
8154             exp.isConstant = true;
8155             if(exp.destType && exp.destType.kind == doubleType)
8156                type.kind = doubleType;
8157             else if(exp.destType && exp.destType.kind == floatType)
8158                type.kind = floatType;
8159             else if(exp.destType && exp.destType.kind == int64Type)
8160                type.kind = int64Type;
8161          }
8162          break;
8163       }
8164       case stringExp:
8165       {
8166          exp.isConstant = true;      // Why wasn't this constant?
8167          exp.expType = Type
8168          {
8169             refCount = 1;
8170             kind = pointerType;
8171             type = Type
8172             {
8173                refCount = 1;
8174                kind = exp.wideString ? shortType : charType;
8175                constant = true;
8176                isSigned = exp.wideString ? false : true;
8177             }
8178          };
8179          break;
8180       }
8181       case newExp:
8182       case new0Exp:
8183          ProcessExpressionType(exp._new.size);
8184          exp.expType = Type
8185          {
8186             refCount = 1;
8187             kind = pointerType;
8188             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8189          };
8190          DeclareType(curExternal, exp.expType.type, true, false);
8191          break;
8192       case renewExp:
8193       case renew0Exp:
8194          ProcessExpressionType(exp._renew.size);
8195          ProcessExpressionType(exp._renew.exp);
8196          exp.expType = Type
8197          {
8198             refCount = 1;
8199             kind = pointerType;
8200             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8201          };
8202          DeclareType(curExternal, exp.expType.type, true, false);
8203          break;
8204       case opExp:
8205       {
8206          bool assign = false, boolResult = false, boolOps = false;
8207          Type type1 = null, type2 = null;
8208          bool useDestType = false, useSideType = false;
8209          Location oldyylloc = yylloc;
8210          bool useSideUnit = false;
8211          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8212
8213          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8214          Type dummy
8215          {
8216             count = 1;
8217             refCount = 1;
8218          };
8219
8220          switch(exp.op.op)
8221          {
8222             // Assignment Operators
8223             case '=':
8224             case MUL_ASSIGN:
8225             case DIV_ASSIGN:
8226             case MOD_ASSIGN:
8227             case ADD_ASSIGN:
8228             case SUB_ASSIGN:
8229             case LEFT_ASSIGN:
8230             case RIGHT_ASSIGN:
8231             case AND_ASSIGN:
8232             case XOR_ASSIGN:
8233             case OR_ASSIGN:
8234                assign = true;
8235                break;
8236             // boolean Operators
8237             case '!':
8238                // Expect boolean operators
8239                //boolOps = true;
8240                //boolResult = true;
8241                break;
8242             case AND_OP:
8243             case OR_OP:
8244                // Expect boolean operands
8245                boolOps = true;
8246                boolResult = true;
8247                break;
8248             // Comparisons
8249             case EQ_OP:
8250             case '<':
8251             case '>':
8252             case LE_OP:
8253             case GE_OP:
8254             case NE_OP:
8255                // Gives boolean result
8256                boolResult = true;
8257                useSideType = true;
8258                break;
8259             case '+':
8260             case '-':
8261                useSideUnit = true;
8262                useSideType = true;
8263                useDestType = true;
8264                break;
8265
8266             case LEFT_OP:
8267             case RIGHT_OP:
8268                // useSideType = true;
8269                // useDestType = true;
8270                break;
8271
8272             case '|':
8273             case '^':
8274                useSideType = true;
8275                useDestType = true;
8276                break;
8277
8278             case '/':
8279             case '%':
8280                useSideType = true;
8281                useDestType = true;
8282                break;
8283             case '&':
8284             case '*':
8285                if(exp.op.exp1)
8286                {
8287                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8288                   useSideType = true;
8289                   useDestType = true;
8290                }
8291                break;
8292
8293             /*// Implement speed etc.
8294             case '*':
8295             case '/':
8296                break;
8297             */
8298          }
8299          if(exp.op.op == '&')
8300          {
8301             // Added this here earlier for Iterator address as key
8302             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8303             {
8304                Identifier id = exp.op.exp2.identifier;
8305                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8306                if(symbol && symbol.isIterator == 2)
8307                {
8308                   exp.type = memberExp;
8309                   exp.member.exp = exp.op.exp2;
8310                   exp.member.member = MkIdentifier("key");
8311                   exp.expType = null;
8312                   exp.op.exp2.expType = symbol.type;
8313                   symbol.type.refCount++;
8314                   ProcessExpressionType(exp);
8315                   FreeType(dummy);
8316                   break;
8317                }
8318                // exp.op.exp2.usage.usageRef = true;
8319             }
8320          }
8321
8322          //dummy.kind = TypeDummy;
8323          if(exp.op.exp1)
8324          {
8325             // Added this check here to use the dest type only for units derived from the base unit
8326             // So that untyped units will use the side unit as opposed to the untyped destination unit
8327             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8328             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8329                useDestType = false;
8330
8331             if(destClass && useDestType &&
8332               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8333
8334               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8335             {
8336                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8337                exp.op.exp1.destType = exp.destType;
8338                exp.op.exp1.opDestType = true;
8339                if(exp.destType)
8340                   exp.destType.refCount++;
8341             }
8342             else if(!assign)
8343             {
8344                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8345                exp.op.exp1.destType = dummy;
8346                dummy.refCount++;
8347             }
8348
8349             // TESTING THIS HERE...
8350             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8351                ProcessExpressionType(exp.op.exp1);
8352             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8353
8354             exp.op.exp1.opDestType = false;
8355
8356             // Fix for unit and ++ / --
8357             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8358                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8359             {
8360                exp.op.exp2 = MkExpConstant("1");
8361                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8362                assign = true;
8363             }
8364
8365             if(exp.op.exp1.destType == dummy)
8366             {
8367                FreeType(dummy);
8368                exp.op.exp1.destType = null;
8369             }
8370
8371             if(exp.op.exp2)
8372             {
8373                if(exp.op.exp1.expType && (exp.op.exp1.expType.kind == charType || exp.op.exp1.expType.kind == shortType))
8374                {
8375                   Type type { kind = intType, isSigned = true, refCount = 1, signedBeforePromotion = exp.op.exp1.expType.isSigned, bitMemberSize = exp.op.exp1.expType.bitMemberSize, promotedFrom = exp.op.exp1.expType.kind };
8376                   FreeType(exp.op.exp1.expType);
8377                   exp.op.exp1.expType = type;
8378                }
8379             }
8380
8381             type1 = exp.op.exp1.expType;
8382          }
8383
8384          if(exp.op.exp2)
8385          {
8386             char expString[10240];
8387             expString[0] = '\0';
8388             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8389             {
8390                if(exp.op.exp1)
8391                {
8392                   exp.op.exp2.destType = exp.op.exp1.expType;
8393                   if(exp.op.exp1.expType)
8394                      exp.op.exp1.expType.refCount++;
8395                }
8396                else
8397                {
8398                   exp.op.exp2.destType = exp.destType;
8399                   if(!exp.op.exp1 || (exp.op.op != '&' && exp.op.op != '^'))
8400                      exp.op.exp2.opDestType = true;
8401                   if(exp.destType)
8402                      exp.destType.refCount++;
8403                }
8404
8405                if(type1) type1.refCount++;
8406                exp.expType = type1;
8407             }
8408             else if(assign)
8409             {
8410                if(inCompiler)
8411                   PrintExpression(exp.op.exp2, expString);
8412
8413                if(type1 && type1.kind == pointerType)
8414                {
8415                   if(exp.op.op == MUL_ASSIGN || exp.op.op == DIV_ASSIGN ||exp.op.op == MOD_ASSIGN ||exp.op.op == LEFT_ASSIGN ||exp.op.op == RIGHT_ASSIGN ||
8416                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8417                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8418                   else if(exp.op.op == '=')
8419                   {
8420                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8421                      exp.op.exp2.destType = type1;
8422                      if(type1)
8423                         type1.refCount++;
8424                   }
8425                }
8426                else
8427                {
8428                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8429                   if(exp.op.op == MUL_ASSIGN || exp.op.op == DIV_ASSIGN ||exp.op.op == MOD_ASSIGN ||exp.op.op == LEFT_ASSIGN ||exp.op.op == RIGHT_ASSIGN/* ||
8430                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8431                   else
8432                   {
8433                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8434                      exp.op.exp2.destType = type1;
8435                      if(type1)
8436                         type1.refCount++;
8437                   }
8438                }
8439                if(type1) type1.refCount++;
8440                exp.expType = type1;
8441             }
8442             else if(destClass &&
8443                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8444                   (destClass.type == enumClass && useDestType)))
8445             {
8446                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8447                exp.op.exp2.destType = exp.destType;
8448                if(exp.op.op != '&' && exp.op.op != '^')
8449                   exp.op.exp2.opDestType = true;
8450                if(exp.destType)
8451                   exp.destType.refCount++;
8452             }
8453             else
8454             {
8455                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8456                exp.op.exp2.destType = dummy;
8457                dummy.refCount++;
8458             }
8459
8460             // TESTING THIS HERE... (DANGEROUS)
8461             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8462                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8463             {
8464                FreeType(exp.op.exp2.destType);
8465                exp.op.exp2.destType = type1;
8466                type1.refCount++;
8467             }
8468             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8469             // Cannot lose the cast on a sizeof
8470             if(exp.op.op == SIZEOF)
8471             {
8472                Expression e = exp.op.exp2;
8473                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8474                {
8475                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8476                   {
8477                      if(e.type == extensionCompoundExp)
8478                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8479                      else
8480                         e = e.list->last;
8481                   }
8482                }
8483                if(e.type == castExp && e.cast.exp)
8484                   e.cast.exp.needCast = true;
8485             }
8486             ProcessExpressionType(exp.op.exp2);
8487             exp.op.exp2.opDestType = false;
8488             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8489
8490             if(exp.op.exp1 || exp.op.op == '~')
8491             {
8492                if(exp.op.exp2.expType && (exp.op.exp2.expType.kind == charType || exp.op.exp2.expType.kind == shortType))
8493                {
8494                   Type type { kind = intType, isSigned = true, refCount = 1, signedBeforePromotion = exp.op.exp2.expType.isSigned, bitMemberSize = exp.op.exp2.expType.bitMemberSize, promotedFrom = exp.op.exp2.expType.kind };
8495                   FreeType(exp.op.exp2.expType);
8496                   exp.op.exp2.expType = type;
8497                }
8498             }
8499
8500             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8501             {
8502                if(exp.op.exp2.expType.kind == intSizeType || exp.op.exp2.expType.kind == intPtrType || exp.op.exp2.expType.kind == int64Type || exp.op.exp2.expType.kind == intType || exp.op.exp2.expType.kind == shortType || exp.op.exp2.expType.kind == charType)
8503                {
8504                   if(exp.op.op != '=' && type1.type.kind == voidType)
8505                      Compiler_Error($"void *: unknown size\n");
8506                }
8507                else if(exp.op.exp2.expType.kind == pointerType || exp.op.exp2.expType.kind == arrayType || exp.op.exp2.expType.kind == functionType || exp.op.exp2.expType.kind == methodType||
8508                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8509                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8510                               exp.op.exp2.expType._class.registered.type == structClass ||
8511                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8512                {
8513                   if(exp.op.op == ADD_ASSIGN)
8514                      Compiler_Error($"cannot add two pointers\n");
8515                }
8516                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8517                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8518                {
8519                   if(exp.op.op == ADD_ASSIGN)
8520                      Compiler_Error($"cannot add two pointers\n");
8521                }
8522                else if(inCompiler)
8523                {
8524                   char type1String[1024];
8525                   char type2String[1024];
8526                   type1String[0] = '\0';
8527                   type2String[0] = '\0';
8528
8529                   PrintType(exp.op.exp2.expType, type1String, false, true);
8530                   PrintType(type1, type2String, false, true);
8531                   ChangeCh(expString, '\n', ' ');
8532                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8533                }
8534             }
8535
8536             if(exp.op.exp2.destType == dummy)
8537             {
8538                FreeType(dummy);
8539                exp.op.exp2.destType = null;
8540             }
8541
8542             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8543             {
8544                type2 = { };
8545                type2.refCount = 1;
8546                CopyTypeInto(type2, exp.op.exp2.expType);
8547                type2.isSigned = true;
8548             }
8549             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8550             {
8551                type2 = { kind = intType };
8552                type2.refCount = 1;
8553                type2.isSigned = true;
8554             }
8555             else
8556             {
8557                type2 = exp.op.exp2.expType;
8558                if(type2) type2.refCount++;
8559             }
8560          }
8561
8562          dummy.kind = voidType;
8563
8564          if(exp.op.op == SIZEOF)
8565          {
8566             exp.expType = Type
8567             {
8568                refCount = 1;
8569                kind = intSizeType;
8570             };
8571             exp.isConstant = true;
8572          }
8573          // Get type of dereferenced pointer
8574          else if(exp.op.op == '*' && !exp.op.exp1)
8575          {
8576             exp.expType = Dereference(type2);
8577             if(type2 && type2.kind == classType)
8578                notByReference = true;
8579          }
8580          else if(exp.op.op == '&' && !exp.op.exp1)
8581             exp.expType = Reference(type2);
8582          else if(exp.op.op == LEFT_OP || exp.op.op == RIGHT_OP)
8583          {
8584             if(exp.op.exp1.expType)
8585             {
8586                exp.expType = exp.op.exp1.expType;
8587                exp.expType.refCount++;
8588             }
8589          }
8590          else if(!assign)
8591          {
8592             if(boolOps)
8593             {
8594                if(exp.op.exp1)
8595                {
8596                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8597                   exp.op.exp1.destType = MkClassType("bool");
8598                   exp.op.exp1.destType.truth = true;
8599                   if(!exp.op.exp1.expType)
8600                      ProcessExpressionType(exp.op.exp1);
8601                   else
8602                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8603                   FreeType(exp.op.exp1.expType);
8604                   exp.op.exp1.expType = MkClassType("bool");
8605                   exp.op.exp1.expType.truth = true;
8606                }
8607                if(exp.op.exp2)
8608                {
8609                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8610                   exp.op.exp2.destType = MkClassType("bool");
8611                   exp.op.exp2.destType.truth = true;
8612                   if(!exp.op.exp2.expType)
8613                      ProcessExpressionType(exp.op.exp2);
8614                   else
8615                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8616                   FreeType(exp.op.exp2.expType);
8617                   exp.op.exp2.expType = MkClassType("bool");
8618                   exp.op.exp2.expType.truth = true;
8619                }
8620             }
8621             else if(exp.op.exp1 && exp.op.exp2 &&
8622                ((useSideType /*&&
8623                      (useSideUnit ||
8624                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8625                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8626                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8627                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8628             {
8629                if(type1 && type2 &&
8630                   // If either both are class or both are not class
8631                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8632                {
8633                   // Added this check for enum subtraction to result in an int type:
8634                   if(exp.op.op == '-' &&
8635                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8636                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8637                   {
8638                      Type intType;
8639                      if(!type1._class.registered.dataType)
8640                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8641                      if(!type2._class.registered.dataType)
8642                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8643
8644                      intType = ProcessTypeString(
8645                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8646
8647                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8648                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8649                      exp.op.exp1.destType = intType;
8650                      exp.op.exp2.destType = intType;
8651                      intType.refCount++;
8652                   }
8653                   else
8654                   {
8655                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8656                      exp.op.exp2.destType = type1;
8657                      type1.refCount++;
8658                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8659                      exp.op.exp1.destType = type2;
8660                      type2.refCount++;
8661                   }
8662
8663                   // Warning here for adding Radians + Degrees with no destination type
8664                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8665                      type1._class.registered && type1._class.registered.type == unitClass &&
8666                      type2._class.registered && type2._class.registered.type == unitClass &&
8667                      type1._class.registered != type2._class.registered)
8668                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8669                         type1._class.string, type2._class.string, type1._class.string);
8670
8671                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8672                   {
8673                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8674                      if(argExp)
8675                      {
8676                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8677
8678                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8679                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8680                            exp.op.exp1)));
8681
8682                         ProcessExpressionType(exp.op.exp1);
8683
8684                         if(type2.kind != pointerType)
8685                         {
8686                            ProcessExpressionType(classExp);
8687
8688                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8689
8690                            if(!exp.op.exp2.expType)
8691                            {
8692                               if(type2)
8693                                  FreeType(type2);
8694                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8695                               type2.refCount++;
8696                            }
8697
8698                            ProcessExpressionType(exp.op.exp2);
8699                         }
8700                      }
8701                   }
8702
8703                   if(!boolResult && ((type1.kind == pointerType || type1.kind == arrayType || (type1.kind == classType && !strcmp(type1._class.string, "String"))) && (type2.kind == intSizeType || type2.kind == intPtrType || type2.kind == int64Type || type2.kind == intType || type2.kind == shortType || type2.kind == charType)))
8704                   {
8705                      if(type1.kind != classType && type1.type.kind == voidType)
8706                         Compiler_Error($"void *: unknown size\n");
8707                      exp.expType = type1;
8708                      if(type1) type1.refCount++;
8709                   }
8710                   else if(!boolResult && ((type2.kind == pointerType || type2.kind == arrayType || (type2.kind == classType && !strcmp(type2._class.string, "String"))) && (type1.kind == intSizeType || type1.kind == intPtrType || type1.kind == int64Type || type1.kind == intType || type1.kind == shortType || type1.kind == charType)))
8711                   {
8712                      if(type2.kind != classType && type2.type.kind == voidType)
8713                         Compiler_Error($"void *: unknown size\n");
8714                      exp.expType = type2;
8715                      if(type2) type2.refCount++;
8716                   }
8717                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8718                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8719                   {
8720                      Compiler_Warning($"different levels of indirection\n");
8721                   }
8722                   else
8723                   {
8724                      bool success = false;
8725                      if(type1.kind == pointerType && type2.kind == pointerType)
8726                      {
8727                         if(exp.op.op == '+')
8728                            Compiler_Error($"cannot add two pointers\n");
8729                         else if(exp.op.op == '-')
8730                         {
8731                            // Pointer Subtraction gives integer
8732                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8733                            {
8734                               exp.expType = Type
8735                               {
8736                                  kind = intType;
8737                                  refCount = 1;
8738                               };
8739                               success = true;
8740
8741                               if(type1.type.kind == templateType)
8742                               {
8743                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8744                                  if(argExp)
8745                                  {
8746                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8747
8748                                     ProcessExpressionType(classExp);
8749
8750                                     exp.type = bracketsExp;
8751                                     exp.list = MkListOne(MkExpOp(
8752                                        MkExpBrackets(MkListOne(MkExpOp(
8753                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8754                                              , exp.op.op,
8755                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8756                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8757
8758                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8759                                     FreeType(dummy);
8760                                     return;
8761                                  }
8762                               }
8763                            }
8764                         }
8765                      }
8766
8767                      if(!success && exp.op.exp1.type == constantExp)
8768                      {
8769                         // If first expression is constant, try to match that first
8770                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8771                         {
8772                            if(exp.expType) FreeType(exp.expType);
8773                            exp.expType = exp.op.exp1.destType;
8774                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8775                            success = true;
8776                         }
8777                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8778                         {
8779                            if(exp.expType) FreeType(exp.expType);
8780                            exp.expType = exp.op.exp2.destType;
8781                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8782                            success = true;
8783                         }
8784                      }
8785                      else if(!success)
8786                      {
8787                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8788                         {
8789                            if(exp.expType) FreeType(exp.expType);
8790                            exp.expType = exp.op.exp2.destType;
8791                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8792                            success = true;
8793                         }
8794                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8795                         {
8796                            if(exp.expType) FreeType(exp.expType);
8797                            exp.expType = exp.op.exp1.destType;
8798                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8799                            success = true;
8800                         }
8801                      }
8802                      if(!success)
8803                      {
8804                         char expString1[10240];
8805                         char expString2[10240];
8806                         char type1[1024];
8807                         char type2[1024];
8808                         expString1[0] = '\0';
8809                         expString2[0] = '\0';
8810                         type1[0] = '\0';
8811                         type2[0] = '\0';
8812                         if(inCompiler)
8813                         {
8814                            PrintExpression(exp.op.exp1, expString1);
8815                            ChangeCh(expString1, '\n', ' ');
8816                            PrintExpression(exp.op.exp2, expString2);
8817                            ChangeCh(expString2, '\n', ' ');
8818                            PrintType(exp.op.exp1.expType, type1, false, true);
8819                            PrintType(exp.op.exp2.expType, type2, false, true);
8820                         }
8821
8822                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8823                      }
8824                   }
8825                }
8826                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8827                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8828                {
8829                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8830                   // Convert e.g. / 4 into / 4.0
8831                   exp.op.exp1.destType = type2._class.registered.dataType;
8832                   if(type2._class.registered.dataType)
8833                      type2._class.registered.dataType.refCount++;
8834                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8835                   exp.expType = type2;
8836                   if(type2) type2.refCount++;
8837                }
8838                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8839                {
8840                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8841                   // Convert e.g. / 4 into / 4.0
8842                   exp.op.exp2.destType = type1._class.registered.dataType;
8843                   if(type1._class.registered.dataType)
8844                      type1._class.registered.dataType.refCount++;
8845                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8846                   exp.expType = type1;
8847                   if(type1) type1.refCount++;
8848                }
8849                else if(type1)
8850                {
8851                   bool valid = false;
8852
8853                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8854                   {
8855                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8856
8857                      if(!type1._class.registered.dataType)
8858                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8859                      exp.op.exp2.destType = type1._class.registered.dataType;
8860                      exp.op.exp2.destType.refCount++;
8861
8862                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8863                      if(type2)
8864                         FreeType(type2);
8865                      type2 = exp.op.exp2.destType;
8866                      if(type2) type2.refCount++;
8867
8868                      exp.expType = type2;
8869                      type2.refCount++;
8870                   }
8871
8872                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8873                   {
8874                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8875
8876                      if(!type2._class.registered.dataType)
8877                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8878                      exp.op.exp1.destType = type2._class.registered.dataType;
8879                      exp.op.exp1.destType.refCount++;
8880
8881                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8882                      type1 = exp.op.exp1.destType;
8883                      exp.expType = type1;
8884                      type1.refCount++;
8885                   }
8886
8887                   // TESTING THIS NEW CODE
8888                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8889                   {
8890                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8891                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8892                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8893                      {
8894                         // Convert the enum to an int instead for these operators
8895                         if(op1IsEnum && exp.op.exp2.expType)
8896                         {
8897                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8898                            {
8899                               if(exp.expType) FreeType(exp.expType);
8900                               exp.expType = exp.op.exp2.expType;
8901                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8902                               valid = true;
8903                            }
8904                         }
8905                         else if(op2IsEnum && exp.op.exp1.expType)
8906                         {
8907                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8908                            {
8909                               if(exp.expType) FreeType(exp.expType);
8910                               exp.expType = exp.op.exp1.expType;
8911                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8912                               valid = true;
8913                            }
8914                         }
8915                      }
8916                      else
8917                      {
8918                         if(op1IsEnum && exp.op.exp2.expType)
8919                         {
8920                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8921                            {
8922                               if(exp.expType) FreeType(exp.expType);
8923                               exp.expType = exp.op.exp1.expType;
8924                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8925                               valid = true;
8926                            }
8927                         }
8928                         else if(op2IsEnum && exp.op.exp1.expType)
8929                         {
8930                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8931                            {
8932                               if(exp.expType) FreeType(exp.expType);
8933                               exp.expType = exp.op.exp2.expType;
8934                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8935                               valid = true;
8936                            }
8937                         }
8938                      }
8939                   }
8940
8941                   if(!valid)
8942                   {
8943                      // Added this first part of the if here to handle  5 + Degrees { 5 } with either a base unit dest or not a unit dest type
8944                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8945                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8946                      {
8947                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8948                         exp.op.exp1.destType = type2;
8949                         type2.refCount++;
8950
8951                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8952                         {
8953                            if(exp.expType) FreeType(exp.expType);
8954                            exp.expType = exp.op.exp1.destType;
8955                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8956                         }
8957                      }
8958                      else
8959                      {
8960                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8961                         exp.op.exp2.destType = type1;
8962                         type1.refCount++;
8963
8964                      /*
8965                      // Maybe this was meant to be an enum...
8966                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8967                      {
8968                         Type oldType = exp.op.exp2.expType;
8969                         exp.op.exp2.expType = null;
8970                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8971                            FreeType(oldType);
8972                         else
8973                            exp.op.exp2.expType = oldType;
8974                      }
8975                      */
8976
8977                      /*
8978                      // TESTING THIS HERE... LATEST ADDITION
8979                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8980                      {
8981                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8982                         exp.op.exp2.destType = type2._class.registered.dataType;
8983                         if(type2._class.registered.dataType)
8984                            type2._class.registered.dataType.refCount++;
8985                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8986
8987                         //exp.expType = type2._class.registered.dataType; //type2;
8988                         //if(type2) type2.refCount++;
8989                      }
8990
8991                      // TESTING THIS HERE... LATEST ADDITION
8992                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8993                      {
8994                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8995                         exp.op.exp1.destType = type1._class.registered.dataType;
8996                         if(type1._class.registered.dataType)
8997                            type1._class.registered.dataType.refCount++;
8998                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8999                         exp.expType = type1._class.registered.dataType; //type1;
9000                         if(type1) type1.refCount++;
9001                      }
9002                      */
9003
9004                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9005                         {
9006                            if(exp.expType) FreeType(exp.expType);
9007                            exp.expType = exp.op.exp2.destType;
9008                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9009                         }
9010                         else if(type1 && type2)
9011                         {
9012                            char expString1[10240];
9013                            char expString2[10240];
9014                            char type1String[1024];
9015                            char type2String[1024];
9016                            expString1[0] = '\0';
9017                            expString2[0] = '\0';
9018                            type1String[0] = '\0';
9019                            type2String[0] = '\0';
9020                            if(inCompiler)
9021                            {
9022                               PrintExpression(exp.op.exp1, expString1);
9023                               ChangeCh(expString1, '\n', ' ');
9024                               PrintExpression(exp.op.exp2, expString2);
9025                               ChangeCh(expString2, '\n', ' ');
9026                               PrintType(exp.op.exp1.expType, type1String, false, true);
9027                               PrintType(exp.op.exp2.expType, type2String, false, true);
9028                            }
9029
9030                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9031
9032                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9033                            {
9034                               exp.expType = exp.op.exp1.expType;
9035                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9036                            }
9037                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9038                            {
9039                               exp.expType = exp.op.exp2.expType;
9040                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9041                            }
9042                         }
9043                      }
9044                   }
9045                }
9046                else if(type2)
9047                {
9048                   // Maybe this was meant to be an enum...
9049                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9050                   {
9051                      Type oldType = exp.op.exp1.expType;
9052                      exp.op.exp1.expType = null;
9053                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9054                         FreeType(oldType);
9055                      else
9056                         exp.op.exp1.expType = oldType;
9057                   }
9058
9059                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9060                   exp.op.exp1.destType = type2;
9061                   type2.refCount++;
9062                   /*
9063                   // TESTING THIS HERE... LATEST ADDITION
9064                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9065                   {
9066                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9067                      exp.op.exp1.destType = type1._class.registered.dataType;
9068                      if(type1._class.registered.dataType)
9069                         type1._class.registered.dataType.refCount++;
9070                   }
9071
9072                   // TESTING THIS HERE... LATEST ADDITION
9073                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9074                   {
9075                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9076                      exp.op.exp2.destType = type2._class.registered.dataType;
9077                      if(type2._class.registered.dataType)
9078                         type2._class.registered.dataType.refCount++;
9079                   }
9080                   */
9081
9082                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9083                   {
9084                      if(exp.expType) FreeType(exp.expType);
9085                      exp.expType = exp.op.exp1.destType;
9086                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9087                   }
9088                }
9089             }
9090             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9091             {
9092                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9093                {
9094                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9095                   // Convert e.g. / 4 into / 4.0
9096                   exp.op.exp1.destType = type2._class.registered.dataType;
9097                   if(type2._class.registered.dataType)
9098                      type2._class.registered.dataType.refCount++;
9099                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9100                }
9101                if(exp.op.op == '!')
9102                {
9103                   exp.expType = MkClassType("bool");
9104                   exp.expType.truth = true;
9105                }
9106                else
9107                {
9108                   exp.expType = type2;
9109                   if(type2) type2.refCount++;
9110                }
9111             }
9112             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9113             {
9114                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9115                {
9116                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9117                   // Convert e.g. / 4 into / 4.0
9118                   exp.op.exp2.destType = type1._class.registered.dataType;
9119                   if(type1._class.registered.dataType)
9120                      type1._class.registered.dataType.refCount++;
9121                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9122                }
9123                exp.expType = type1;
9124                if(type1) type1.refCount++;
9125             }
9126          }
9127
9128          yylloc = exp.loc;
9129          if(exp.op.exp1 && !exp.op.exp1.expType)
9130          {
9131             char expString[10000];
9132             expString[0] = '\0';
9133             if(inCompiler)
9134             {
9135                PrintExpression(exp.op.exp1, expString);
9136                ChangeCh(expString, '\n', ' ');
9137             }
9138             if(expString[0])
9139                Compiler_Error($"couldn't determine type of %s\n", expString);
9140          }
9141          if(exp.op.exp2 && !exp.op.exp2.expType)
9142          {
9143             char expString[10240];
9144             expString[0] = '\0';
9145             if(inCompiler)
9146             {
9147                PrintExpression(exp.op.exp2, expString);
9148                ChangeCh(expString, '\n', ' ');
9149             }
9150             if(expString[0])
9151                Compiler_Error($"couldn't determine type of %s\n", expString);
9152          }
9153
9154          if(boolResult)
9155          {
9156             FreeType(exp.expType);
9157             exp.expType = MkClassType("bool");
9158             exp.expType.truth = true;
9159          }
9160
9161          if(exp.op.op != SIZEOF)
9162             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9163                (!exp.op.exp2 || exp.op.exp2.isConstant);
9164
9165          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9166          {
9167             DeclareType(curExternal, exp.op.exp2.expType, true, false);
9168          }
9169
9170          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9171             Compiler_Warning($"deleting const qualified object\n");
9172
9173          yylloc = oldyylloc;
9174
9175          FreeType(dummy);
9176          if(type2)
9177             FreeType(type2);
9178          break;
9179       }
9180       case bracketsExp:
9181       case extensionExpressionExp:
9182       {
9183          Expression e;
9184          exp.isConstant = true;
9185          for(e = exp.list->first; e; e = e.next)
9186          {
9187             //bool inced = false;
9188             if(!e.next)
9189             {
9190                FreeType(e.destType);
9191                e.opDestType = exp.opDestType;
9192                e.destType = exp.destType;
9193                if(e.destType) { exp.destType.refCount++; /*e.destType.count++; inced = true;*/ }
9194             }
9195             ProcessExpressionType(e);
9196             /*if(inced)
9197                exp.destType.count--;*/
9198             if(!exp.expType && !e.next)
9199             {
9200                exp.expType = e.expType;
9201                if(e.expType) e.expType.refCount++;
9202             }
9203             if(!e.isConstant)
9204                exp.isConstant = false;
9205          }
9206
9207          // In case a cast became a member...
9208          e = exp.list->first;
9209          if(!e.next && e.type == memberExp)
9210          {
9211             // Preserve prev, next
9212             Expression next = exp.next, prev = exp.prev;
9213
9214
9215             FreeType(exp.expType);
9216             FreeType(exp.destType);
9217             delete exp.list;
9218
9219             *exp = *e;
9220
9221             exp.prev = prev;
9222             exp.next = next;
9223
9224             delete e;
9225
9226             ProcessExpressionType(exp);
9227          }
9228          break;
9229       }
9230       case indexExp:
9231       {
9232          Expression e;
9233          exp.isConstant = true;
9234
9235          ProcessExpressionType(exp.index.exp);
9236          if(!exp.index.exp.isConstant)
9237             exp.isConstant = false;
9238
9239          if(exp.index.exp.expType)
9240          {
9241             Type source = exp.index.exp.expType;
9242             if(source.kind == classType && source._class && source._class.registered)
9243             {
9244                Class _class = source._class.registered;
9245                Class c = _class.templateClass ? _class.templateClass : _class;
9246                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9247                {
9248                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9249
9250                   if(exp.index.index && exp.index.index->last)
9251                   {
9252                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9253
9254                      if(type.kind == classType) type.constant = true;
9255                      else if(type.kind == pointerType)
9256                      {
9257                         Type t = type;
9258                         while(t.kind == pointerType) t = t.type;
9259                         t.constant = true;
9260                      }
9261
9262                      ((Expression)exp.index.index->last).destType = type;
9263                   }
9264                }
9265             }
9266          }
9267
9268          for(e = exp.index.index->first; e; e = e.next)
9269          {
9270             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9271             {
9272                if(e.destType) FreeType(e.destType);
9273                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9274             }
9275             ProcessExpressionType(e);
9276             if(!e.next)
9277             {
9278                // Check if this type is int
9279             }
9280             if(!e.isConstant)
9281                exp.isConstant = false;
9282          }
9283
9284          if(!exp.expType)
9285             exp.expType = Dereference(exp.index.exp.expType);
9286          if(exp.expType)
9287             DeclareType(curExternal, exp.expType, true, false);
9288          break;
9289       }
9290       case callExp:
9291       {
9292          Expression e;
9293          Type functionType;
9294          Type methodType = null;
9295          char name[1024];
9296          name[0] = '\0';
9297
9298          if(inCompiler)
9299          {
9300             PrintExpression(exp.call.exp,  name);
9301             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9302             {
9303                //exp.call.exp.expType = null;
9304                PrintExpression(exp.call.exp,  name);
9305             }
9306          }
9307          if(exp.call.exp.type == identifierExp)
9308          {
9309             Expression idExp = exp.call.exp;
9310             Identifier id = idExp.identifier;
9311             if(!strcmp(id.string, "__builtin_frame_address"))
9312             {
9313                exp.expType = ProcessTypeString("void *", true);
9314                if(exp.call.arguments && exp.call.arguments->first)
9315                   ProcessExpressionType(exp.call.arguments->first);
9316                break;
9317             }
9318             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9319             {
9320                exp.expType = ProcessTypeString("int", true);
9321                if(exp.call.arguments && exp.call.arguments->first)
9322                   ProcessExpressionType(exp.call.arguments->first);
9323                break;
9324             }
9325             else if(!strcmp(id.string, "Max") ||
9326                !strcmp(id.string, "Min") ||
9327                !strcmp(id.string, "Sgn") ||
9328                !strcmp(id.string, "Abs"))
9329             {
9330                Expression a = null;
9331                Expression b = null;
9332                Expression tempExp1 = null, tempExp2 = null;
9333                if((!strcmp(id.string, "Max") ||
9334                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9335                {
9336                   a = exp.call.arguments->first;
9337                   b = exp.call.arguments->last;
9338                   tempExp1 = a;
9339                   tempExp2 = b;
9340                }
9341                else if(exp.call.arguments->count == 1)
9342                {
9343                   a = exp.call.arguments->first;
9344                   tempExp1 = a;
9345                }
9346
9347                if(a)
9348                {
9349                   exp.call.arguments->Clear();
9350                   idExp.identifier = null;
9351
9352                   FreeExpContents(exp);
9353
9354                   ProcessExpressionType(a);
9355                   if(b)
9356                      ProcessExpressionType(b);
9357
9358                   exp.type = bracketsExp;
9359                   exp.list = MkList();
9360
9361                   if(a.expType && (!b || b.expType))
9362                   {
9363                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9364                      {
9365                         // Use the simpleStruct name/ids for now...
9366                         if(inCompiler)
9367                         {
9368                            OldList * specs = MkList();
9369                            OldList * decls = MkList();
9370                            Declaration decl;
9371                            char temp1[1024], temp2[1024];
9372
9373                            GetTypeSpecs(a.expType, specs);
9374
9375                            if(a && !a.isConstant && a.type != identifierExp)
9376                            {
9377                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9378                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9379                               tempExp1 = QMkExpId(temp1);
9380                               tempExp1.expType = a.expType;
9381                               if(a.expType)
9382                                  a.expType.refCount++;
9383                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9384                            }
9385                            if(b && !b.isConstant && b.type != identifierExp)
9386                            {
9387                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9388                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9389                               tempExp2 = QMkExpId(temp2);
9390                               tempExp2.expType = b.expType;
9391                               if(b.expType)
9392                                  b.expType.refCount++;
9393                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9394                            }
9395
9396                            decl = MkDeclaration(specs, decls);
9397                            if(!curCompound.compound.declarations)
9398                               curCompound.compound.declarations = MkList();
9399                            curCompound.compound.declarations->Insert(null, decl);
9400                         }
9401                      }
9402                   }
9403
9404                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9405                   {
9406                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9407                      ListAdd(exp.list,
9408                         MkExpCondition(MkExpBrackets(MkListOne(
9409                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9410                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9411                      exp.expType = a.expType;
9412                      if(a.expType)
9413                         a.expType.refCount++;
9414                   }
9415                   else if(!strcmp(id.string, "Abs"))
9416                   {
9417                      ListAdd(exp.list,
9418                         MkExpCondition(MkExpBrackets(MkListOne(
9419                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9420                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9421                      exp.expType = a.expType;
9422                      if(a.expType)
9423                         a.expType.refCount++;
9424                   }
9425                   else if(!strcmp(id.string, "Sgn"))
9426                   {
9427                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9428                      ListAdd(exp.list,
9429                         MkExpCondition(MkExpBrackets(MkListOne(
9430                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9431                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9432                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9433                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9434                      exp.expType = ProcessTypeString("int", false);
9435                   }
9436
9437                   FreeExpression(tempExp1);
9438                   if(tempExp2) FreeExpression(tempExp2);
9439
9440                   FreeIdentifier(id);
9441                   break;
9442                }
9443             }
9444          }
9445
9446          {
9447             Type dummy
9448             {
9449                count = 1;
9450                refCount = 1;
9451             };
9452             if(!exp.call.exp.destType)
9453             {
9454                exp.call.exp.destType = dummy;
9455                dummy.refCount++;
9456             }
9457             ProcessExpressionType(exp.call.exp);
9458             if(exp.call.exp.destType == dummy)
9459             {
9460                FreeType(dummy);
9461                exp.call.exp.destType = null;
9462             }
9463             FreeType(dummy);
9464          }
9465
9466          // Check argument types against parameter types
9467          functionType = exp.call.exp.expType;
9468
9469          if(functionType && functionType.kind == TypeKind::methodType)
9470          {
9471             methodType = functionType;
9472             functionType = methodType.method.dataType;
9473
9474             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9475             // TOCHECK: Instead of doing this here could this be done per param?
9476             if(exp.call.exp.expType.usedClass)
9477             {
9478                char typeString[1024];
9479                typeString[0] = '\0';
9480                {
9481                   Symbol back = functionType.thisClass;
9482                   // Do not output class specifier here (thisclass was added to this)
9483                   functionType.thisClass = null;
9484                   PrintType(functionType, typeString, true, true);
9485                   functionType.thisClass = back;
9486                }
9487                if(strstr(typeString, "thisclass"))
9488                {
9489                   OldList * specs = MkList();
9490                   Declarator decl;
9491                   {
9492                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9493
9494                      decl = SpecDeclFromString(typeString, specs, null);
9495
9496                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9497                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9498                         exp.call.exp.expType.usedClass))
9499                         thisClassParams = false;
9500
9501                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9502                      {
9503                         Class backupThisClass = thisClass;
9504                         thisClass = exp.call.exp.expType.usedClass;
9505                         ProcessDeclarator(decl, true);
9506                         thisClass = backupThisClass;
9507                      }
9508
9509                      thisClassParams = true;
9510
9511                      functionType = ProcessType(specs, decl);
9512                      functionType.refCount = 0;
9513                      FinishTemplatesContext(context);
9514
9515                      // Mark parameters that were 'thisclass'
9516                      {
9517                         Type p, op;
9518                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9519                         {
9520                            //p.wasThisClass = op.kind == thisClassType;
9521                            if(op.kind == thisClassType)
9522                               p.thisClassFrom = methodType.method._class;
9523                         }
9524                      }
9525                      if(methodType.method.dataType.returnType.kind == thisClassType)
9526                      {
9527                         // functionType.returnType.wasThisClass = true;
9528                         functionType.returnType.thisClassFrom = methodType.method._class;
9529                      }
9530                   }
9531
9532                   FreeList(specs, FreeSpecifier);
9533                   FreeDeclarator(decl);
9534                 }
9535             }
9536          }
9537          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9538          {
9539             Type type = functionType.type;
9540             if(!functionType.refCount)
9541             {
9542                functionType.type = null;
9543                FreeType(functionType);
9544             }
9545             //methodType = functionType;
9546             functionType = type;
9547          }
9548          if(functionType && functionType.kind != TypeKind::functionType)
9549          {
9550             Compiler_Error($"called object %s is not a function\n", name);
9551          }
9552          else if(functionType)
9553          {
9554             bool emptyParams = false, noParams = false;
9555             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9556             Type type = functionType.params.first;
9557             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9558             int extra = 0;
9559             Location oldyylloc = yylloc;
9560
9561             if(!type) emptyParams = true;
9562
9563             // WORKING ON THIS:
9564             if(functionType.extraParam && e && functionType.thisClass)
9565             {
9566                e.destType = MkClassType(functionType.thisClass.string);
9567                e = e.next;
9568             }
9569
9570             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9571             // Fixed #141 by adding '&& !functionType.extraParam'
9572             if(!functionType.staticMethod && !functionType.extraParam)
9573             {
9574                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9575                   memberExp.member.exp.expType._class)
9576                {
9577                   type = MkClassType(memberExp.member.exp.expType._class.string);
9578                   if(e)
9579                   {
9580                      e.destType = type;
9581                      e = e.next;
9582                      type = functionType.params.first;
9583                   }
9584                   else
9585                      type.refCount = 0;
9586                }
9587                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9588                {
9589                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9590                   type.byReference = functionType.byReference;
9591                   type.typedByReference = functionType.typedByReference;
9592                   if(e)
9593                   {
9594                      // Allow manually passing a class for typed object
9595                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9596                         e = e.next;
9597                      e.destType = type;
9598                      e = e.next;
9599                      type = functionType.params.first;
9600                   }
9601                   else
9602                      type.refCount = 0;
9603                   //extra = 1;
9604                }
9605             }
9606
9607             if(type && type.kind == voidType)
9608             {
9609                noParams = true;
9610                if(!type.refCount) FreeType(type);
9611                type = null;
9612             }
9613
9614             for( ; e; e = e.next)
9615             {
9616                if(!type && !emptyParams)
9617                {
9618                   yylloc = e.loc;
9619                   if(methodType && methodType.methodClass)
9620                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9621                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9622                         noParams ? 0 : functionType.params.count);
9623                   else
9624                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9625                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9626                         noParams ? 0 : functionType.params.count);
9627                   break;
9628                }
9629
9630                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9631                {
9632                   Type templatedType = null;
9633                   Class _class = methodType.usedClass;
9634                   ClassTemplateParameter curParam = null;
9635                   int id = 0;
9636                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9637                   {
9638                      Class sClass;
9639                      for(sClass = _class; sClass; sClass = sClass.base)
9640                      {
9641                         if(sClass.templateClass) sClass = sClass.templateClass;
9642                         id = 0;
9643                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9644                         {
9645                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9646                            {
9647                               Class nextClass;
9648                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9649                               {
9650                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9651                                  id += nextClass.templateParams.count;
9652                               }
9653                               break;
9654                            }
9655                            id++;
9656                         }
9657                         if(curParam) break;
9658                      }
9659                   }
9660                   if(curParam && _class.templateArgs[id].dataTypeString)
9661                   {
9662                      bool constant = type.constant;
9663                      ClassTemplateArgument arg = _class.templateArgs[id];
9664                      {
9665                         Context context = SetupTemplatesContext(_class);
9666
9667                         /*if(!arg.dataType)
9668                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9669                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9670                         FinishTemplatesContext(context);
9671                      }
9672
9673                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9674                      else if(templatedType.kind == pointerType)
9675                      {
9676                         Type t = templatedType.type;
9677                         while(t.kind == pointerType) t = t.type;
9678                         if(constant) t.constant = constant;
9679                      }
9680
9681                      e.destType = templatedType;
9682                      if(templatedType)
9683                      {
9684                         templatedType.passAsTemplate = true;
9685                         // templatedType.refCount++;
9686                      }
9687                   }
9688                   else
9689                   {
9690                      e.destType = type;
9691                      if(type) type.refCount++;
9692                   }
9693                }
9694                else
9695                {
9696                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9697                   {
9698                      e.destType = type.prev;
9699                      e.destType.refCount++;
9700                   }
9701                   else
9702                   {
9703                      e.destType = type;
9704                      if(type) type.refCount++;
9705                   }
9706                }
9707                // Don't reach the end for the ellipsis
9708                if(type && type.kind != ellipsisType)
9709                {
9710                   Type next = type.next;
9711                   if(!type.refCount) FreeType(type);
9712                   type = next;
9713                }
9714             }
9715
9716             if(type && type.kind != ellipsisType)
9717             {
9718                if(methodType && methodType.methodClass)
9719                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9720                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9721                      functionType.params.count + extra);
9722                else
9723                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9724                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9725                      functionType.params.count + extra);
9726             }
9727             yylloc = oldyylloc;
9728             if(type && !type.refCount) FreeType(type);
9729          }
9730          else
9731          {
9732             functionType = Type
9733             {
9734                refCount = 0;
9735                kind = TypeKind::functionType;
9736             };
9737
9738             if(exp.call.exp.type == identifierExp)
9739             {
9740                char * string = exp.call.exp.identifier.string;
9741                if(inCompiler)
9742                {
9743                   Symbol symbol;
9744                   Location oldyylloc = yylloc;
9745
9746                   yylloc = exp.call.exp.identifier.loc;
9747                   if(strstr(string, "__builtin_") == string)
9748                   {
9749                      if(exp.destType)
9750                      {
9751                         functionType.returnType = exp.destType;
9752                         exp.destType.refCount++;
9753                      }
9754                   }
9755                   else
9756                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9757                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9758                   globalContext.symbols.Add((BTNode)symbol);
9759                   if(strstr(symbol.string, "::"))
9760                      globalContext.hasNameSpace = true;
9761
9762                   yylloc = oldyylloc;
9763                }
9764             }
9765             else if(exp.call.exp.type == memberExp)
9766             {
9767                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9768                   exp.call.exp.member.member.string);*/
9769             }
9770             else
9771                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9772
9773             if(!functionType.returnType)
9774             {
9775                functionType.returnType = Type
9776                {
9777                   refCount = 1;
9778                   kind = intType;
9779                };
9780             }
9781          }
9782          if(functionType && functionType.kind == TypeKind::functionType)
9783          {
9784             exp.expType = functionType.returnType;
9785
9786             if(functionType.returnType)
9787                functionType.returnType.refCount++;
9788
9789             if(!functionType.refCount)
9790                FreeType(functionType);
9791          }
9792
9793          if(exp.call.arguments)
9794          {
9795             for(e = exp.call.arguments->first; e; e = e.next)
9796                ProcessExpressionType(e);
9797          }
9798          break;
9799       }
9800       case memberExp:
9801       {
9802          Type type;
9803          Location oldyylloc = yylloc;
9804          bool thisPtr;
9805          Expression checkExp = exp.member.exp;
9806          while(checkExp)
9807          {
9808             if(checkExp.type == castExp)
9809                checkExp = checkExp.cast.exp;
9810             else if(checkExp.type == bracketsExp)
9811                checkExp = checkExp.list ? checkExp.list->first : null;
9812             else
9813                break;
9814          }
9815
9816          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9817          exp.thisPtr = thisPtr;
9818
9819          // DOING THIS LATER NOW...
9820          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9821          {
9822             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9823             /* TODO: Name Space Fix ups
9824             if(!exp.member.member.classSym)
9825                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9826             */
9827          }
9828
9829          ProcessExpressionType(exp.member.exp);
9830          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9831             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9832          {
9833             exp.isConstant = false;
9834          }
9835          else
9836             exp.isConstant = exp.member.exp.isConstant;
9837          type = exp.member.exp.expType;
9838
9839          yylloc = exp.loc;
9840
9841          if(type && (type.kind == templateType))
9842          {
9843             Class _class = thisClass ? thisClass : currentClass;
9844             ClassTemplateParameter param = null;
9845             if(_class)
9846             {
9847                for(param = _class.templateParams.first; param; param = param.next)
9848                {
9849                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9850                      break;
9851                }
9852             }
9853             if(param && param.defaultArg.member)
9854             {
9855                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9856                if(argExp)
9857                {
9858                   Expression expMember = exp.member.exp;
9859                   Declarator decl;
9860                   OldList * specs = MkList();
9861                   char thisClassTypeString[1024];
9862
9863                   FreeIdentifier(exp.member.member);
9864
9865                   ProcessExpressionType(argExp);
9866
9867                   {
9868                      char * colon = strstr(param.defaultArg.memberString, "::");
9869                      if(colon)
9870                      {
9871                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9872                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9873                      }
9874                      else
9875                         strcpy(thisClassTypeString, _class.fullName);
9876                   }
9877
9878                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9879
9880                   exp.expType = ProcessType(specs, decl);
9881                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9882                   {
9883                      Class expClass = exp.expType._class.registered;
9884                      Class cClass = null;
9885                      int paramCount = 0;
9886                      int lastParam = -1;
9887
9888                      char templateString[1024];
9889                      ClassTemplateParameter param;
9890                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9891                      for(cClass = expClass; cClass; cClass = cClass.base)
9892                      {
9893                         int p = 0;
9894                         for(param = cClass.templateParams.first; param; param = param.next)
9895                         {
9896                            int id = p;
9897                            Class sClass;
9898                            ClassTemplateArgument arg;
9899                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9900                            arg = expClass.templateArgs[id];
9901
9902                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9903                            {
9904                               ClassTemplateParameter cParam;
9905                               //int p = numParams - sClass.templateParams.count;
9906                               int p = 0;
9907                               Class nextClass;
9908                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9909
9910                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9911                               {
9912                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9913                                  {
9914                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9915                                     {
9916                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9917                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9918                                        break;
9919                                     }
9920                                  }
9921                               }
9922                            }
9923
9924                            {
9925                               char argument[256];
9926                               argument[0] = '\0';
9927                               /*if(arg.name)
9928                               {
9929                                  strcat(argument, arg.name.string);
9930                                  strcat(argument, " = ");
9931                               }*/
9932                               switch(param.type)
9933                               {
9934                                  case expression:
9935                                  {
9936                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9937                                     char expString[1024];
9938                                     OldList * specs = MkList();
9939                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9940                                     Expression exp;
9941                                     char * string = PrintHexUInt64(arg.expression.ui64);
9942                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9943                                     delete string;
9944
9945                                     ProcessExpressionType(exp);
9946                                     ComputeExpression(exp);
9947                                     expString[0] = '\0';
9948                                     PrintExpression(exp, expString);
9949                                     strcat(argument, expString);
9950                                     // delete exp;
9951                                     FreeExpression(exp);
9952                                     break;
9953                                  }
9954                                  case identifier:
9955                                  {
9956                                     strcat(argument, arg.member.name);
9957                                     break;
9958                                  }
9959                                  case TemplateParameterType::type:
9960                                  {
9961                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9962                                     {
9963                                        if(!strcmp(arg.dataTypeString, "thisclass"))
9964                                           strcat(argument, thisClassTypeString);
9965                                        else
9966                                           strcat(argument, arg.dataTypeString);
9967                                     }
9968                                     break;
9969                                  }
9970                               }
9971                               if(argument[0])
9972                               {
9973                                  if(paramCount) strcat(templateString, ", ");
9974                                  if(lastParam != p - 1)
9975                                  {
9976                                     strcat(templateString, param.name);
9977                                     strcat(templateString, " = ");
9978                                  }
9979                                  strcat(templateString, argument);
9980                                  paramCount++;
9981                                  lastParam = p;
9982                               }
9983                               p++;
9984                            }
9985                         }
9986                      }
9987                      {
9988                         int len = strlen(templateString);
9989                         if(templateString[len-1] == '>') templateString[len++] = ' ';
9990                         templateString[len++] = '>';
9991                         templateString[len++] = '\0';
9992                      }
9993                      {
9994                         Context context = SetupTemplatesContext(_class);
9995                         FreeType(exp.expType);
9996                         exp.expType = ProcessTypeString(templateString, false);
9997                         FinishTemplatesContext(context);
9998                      }
9999                   }
10000
10001                   if(!expMember.expType.isPointerType)
10002                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10003                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10004                   exp.type = bracketsExp;
10005                   exp.list = MkListOne(MkExpOp(null, '*',
10006                   /*opExp;
10007                   exp.op.op = '*';
10008                   exp.op.exp1 = null;
10009                   exp.op.exp2 = */
10010                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10011                      MkExpBrackets(MkListOne(
10012                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10013                            expMember))),
10014                               '+',
10015                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10016                               '+',
10017                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10018
10019                            ));
10020                }
10021             }
10022             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10023                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10024             {
10025                type = ProcessTemplateParameterType(type.templateParameter);
10026             }
10027          }
10028          // TODO: *** This seems to be where we should add method support for all basic types ***
10029          if(type && (type.kind == templateType));
10030          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10031                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10032                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10033                           (type.kind == pointerType && type.type.kind == charType)))
10034          {
10035             Identifier id = exp.member.member;
10036             TypeKind typeKind = type.kind;
10037             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10038             if(typeKind == subClassType && exp.member.exp.type == classExp)
10039             {
10040                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10041                typeKind = classType;
10042             }
10043
10044             if(id)
10045             {
10046                if(typeKind == intType || typeKind == enumType)
10047                   _class = eSystem_FindClass(privateModule, "int");
10048                else if(!_class)
10049                {
10050                   if(type.kind == classType && type._class && type._class.registered)
10051                   {
10052                      _class = type._class.registered;
10053                   }
10054                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10055                   {
10056                      _class = FindClass("char *").registered;
10057                   }
10058                   else if(type.kind == pointerType)
10059                   {
10060                      _class = eSystem_FindClass(privateModule, "uintptr");
10061                      FreeType(exp.expType);
10062                      exp.expType = ProcessTypeString("uintptr", false);
10063                      exp.byReference = true;
10064                   }
10065                   else
10066                   {
10067                      char string[1024] = "";
10068                      Symbol classSym;
10069                      PrintTypeNoConst(type, string, false, true);
10070                      classSym = FindClass(string);
10071                      if(classSym) _class = classSym.registered;
10072                   }
10073                }
10074             }
10075
10076             if(_class && id)
10077             {
10078                /*bool thisPtr =
10079                   (exp.member.exp.type == identifierExp &&
10080                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10081                Property prop = null;
10082                Method method = null;
10083                DataMember member = null;
10084                Property revConvert = null;
10085                ClassProperty classProp = null;
10086
10087                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10088                   exp.member.memberType = propertyMember;
10089
10090                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10091                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10092
10093                if(typeKind != subClassType)
10094                {
10095                   // Prioritize data members over properties for "this"
10096                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10097                   {
10098                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10099                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10100                      {
10101                         prop = eClass_FindProperty(_class, id.string, privateModule);
10102                         if(prop)
10103                            member = null;
10104                      }
10105                      if(!member && !prop)
10106                         prop = eClass_FindProperty(_class, id.string, privateModule);
10107                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10108                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10109                         exp.member.thisPtr = true;
10110                   }
10111                   // Prioritize properties over data members otherwise
10112                   else
10113                   {
10114                      bool useMemberForNonConst = false;
10115                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10116                      if(!id.classSym)
10117                      {
10118                         prop = eClass_FindProperty(_class, id.string, null);
10119
10120                         useMemberForNonConst = prop && exp.destType &&
10121                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10122                               !strncmp(prop.dataTypeString, "const ", 6);
10123
10124                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10125                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10126                      }
10127
10128                      if((!prop || useMemberForNonConst) && !member)
10129                      {
10130                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10131                         if(!method)
10132                         {
10133                            prop = eClass_FindProperty(_class, id.string, privateModule);
10134
10135                            useMemberForNonConst |= prop && exp.destType &&
10136                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10137                                  !strncmp(prop.dataTypeString, "const ", 6);
10138
10139                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10140                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10141                         }
10142                      }
10143
10144                      if(member && prop)
10145                      {
10146                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10147                            prop = null;
10148                         else
10149                            member = null;
10150                      }
10151                   }
10152                }
10153                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10154                   method = eClass_FindMethod(_class, id.string, privateModule);
10155                if(!prop && !member && !method)
10156                {
10157                   if(typeKind == subClassType)
10158                   {
10159                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10160                      if(classProp)
10161                      {
10162                         exp.member.memberType = classPropertyMember;
10163                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10164                      }
10165                      else
10166                      {
10167                         // Assume this is a class_data member
10168                         char structName[1024];
10169                         Identifier id = exp.member.member;
10170                         Expression classExp = exp.member.exp;
10171                         type.refCount++;
10172
10173                         FreeType(classExp.expType);
10174                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10175
10176                         strcpy(structName, "__ecereClassData_");
10177                         FullClassNameCat(structName, type._class.string, false);
10178                         exp.type = pointerExp;
10179                         exp.member.member = id;
10180
10181                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10182                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10183                               MkExpBrackets(MkListOne(MkExpOp(
10184                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10185                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10186                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10187                                  )));
10188
10189                         FreeType(type);
10190
10191                         ProcessExpressionType(exp);
10192                         return;
10193                      }
10194                   }
10195                   else
10196                   {
10197                      // Check for reverse conversion
10198                      // (Convert in an instantiation later, so that we can use
10199                      //  deep properties system)
10200                      Symbol classSym = FindClass(id.string);
10201                      if(classSym)
10202                      {
10203                         Class convertClass = classSym.registered;
10204                         if(convertClass)
10205                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10206                      }
10207                   }
10208                }
10209
10210                //if(!exp.member.exp.destType)
10211                if(exp.member.exp.destType)
10212                   FreeType(exp.member.exp.destType);
10213                {
10214                   if(method && !method._class.symbol)
10215                      method._class.symbol = FindClass(method._class.fullName);
10216                   if(prop && !prop._class.symbol)
10217                      prop._class.symbol = FindClass(prop._class.fullName);
10218
10219                   exp.member.exp.destType = Type
10220                   {
10221                      refCount = 1;
10222                      kind = classType;
10223                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10224                      // wasThisClass = type ? type.wasThisClass : false;
10225                      thisClassFrom = type ? type.thisClassFrom : null;
10226                   };
10227                }
10228
10229                if(prop)
10230                {
10231                   exp.member.memberType = propertyMember;
10232                   if(!prop.dataType)
10233                      ProcessPropertyType(prop);
10234                   exp.expType = prop.dataType;
10235                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10236                   {
10237                      Type type { };
10238                      CopyTypeInto(type, exp.expType);
10239                      type.refCount = 1;
10240                      type.constant = true;
10241                      exp.expType = type;
10242                   }
10243                   else if(prop.dataType)
10244                      prop.dataType.refCount++;
10245                }
10246                else if(member)
10247                {
10248                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10249                   {
10250                      FreeExpContents(exp);
10251                      exp.type = identifierExp;
10252                      exp.identifier = MkIdentifier("class");
10253                      ProcessExpressionType(exp);
10254                      return;
10255                   }
10256
10257                   exp.member.memberType = dataMember;
10258                   DeclareStruct(curExternal, _class.fullName, false, true);
10259                   if(member._class != _class)
10260                      DeclareStruct(curExternal, member._class.fullName, false, true);
10261
10262                   if(!member.dataType)
10263                   {
10264                      Context context = SetupTemplatesContext(_class);
10265                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10266                      FinishTemplatesContext(context);
10267                   }
10268                   if(exp.member.exp.expType.kind == classType && exp.member.exp.expType._class && exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == bitClass)
10269                      member.dataType.bitMemberSize = ((BitMember)member).size;
10270                   exp.expType = member.dataType;
10271                   if(member.dataType) member.dataType.refCount++;
10272                }
10273                else if(revConvert)
10274                {
10275                   exp.member.memberType = reverseConversionMember;
10276                   exp.expType = MkClassType(revConvert._class.fullName);
10277                }
10278                else if(method)
10279                {
10280                   //if(inCompiler)
10281                   {
10282                      /*if(id._class)
10283                      {
10284                         exp.type = identifierExp;
10285                         exp.identifier = exp.member.member;
10286                      }
10287                      else*/
10288                         exp.member.memberType = methodMember;
10289                   }
10290                   if(!method.dataType)
10291                      ProcessMethodType(method);
10292                   exp.expType = Type
10293                   {
10294                      refCount = 1;
10295                      kind = methodType;
10296                      method = method;
10297                   };
10298
10299                   // Tricky spot here... To use instance versus class virtual table
10300                   // Put it back to what it was... What did we break?
10301
10302                   // Had to put it back for overriding Main of Thread global instance
10303
10304                   //exp.expType.methodClass = _class;
10305                   exp.expType.methodClass = (id && id._class) ? _class : null;
10306
10307                   // Need the actual class used for templated classes
10308                   exp.expType.usedClass = _class;
10309                }
10310                else if(!classProp)
10311                {
10312                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10313                   {
10314                      FreeExpContents(exp);
10315                      exp.type = identifierExp;
10316                      exp.identifier = MkIdentifier("class");
10317                      FreeType(exp.expType);
10318                      exp.expType = MkClassType("ecere::com::Class");
10319                      return;
10320                   }
10321                   yylloc = exp.member.member.loc;
10322                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10323                   if(inCompiler)
10324                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10325                }
10326
10327                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10328                {
10329                   Class tClass;
10330
10331                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10332                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10333
10334                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10335                   {
10336                      int id = 0;
10337                      ClassTemplateParameter curParam = null;
10338                      Class sClass;
10339
10340                      for(sClass = tClass; sClass; sClass = sClass.base)
10341                      {
10342                         id = 0;
10343                         if(sClass.templateClass) sClass = sClass.templateClass;
10344                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10345                         {
10346                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10347                            {
10348                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10349                                  id += sClass.templateParams.count;
10350                               break;
10351                            }
10352                            id++;
10353                         }
10354                         if(curParam) break;
10355                      }
10356
10357                      if(curParam && tClass.templateArgs[id].dataTypeString)
10358                      {
10359                         ClassTemplateArgument arg = tClass.templateArgs[id];
10360                         Context context = SetupTemplatesContext(tClass);
10361                         bool constant = exp.expType.constant;
10362                         bool passAsTemplate = false;
10363                         Class thisClassFrom = null;
10364                         Type t = ProcessTypeString(exp.expType.templateParameter.dataTypeString, false);
10365                         if(t && t.kind == classType && t._class)
10366                            thisClassFrom = t._class.registered;
10367                         else
10368                            // Mark that 'thisClassFrom' was set to something
10369                            thisClassFrom = eSystem_FindClass(GetPrivateModule(), "class");
10370
10371                         FreeType(t);
10372
10373                         passAsTemplate = tClass.templateClass && (exp.expType.kind != templateType ||
10374                            (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType)));
10375
10376                         /*if(!arg.dataType)
10377                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10378                         FreeType(exp.expType);
10379
10380                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10381                         exp.expType.thisClassFrom = thisClassFrom;
10382                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10383                         else if(exp.expType.kind == pointerType)
10384                         {
10385                            Type t = exp.expType.type;
10386                            while(t.kind == pointerType) t = t.type;
10387                            if(constant) t.constant = constant;
10388                         }
10389                         if(exp.expType)
10390                         {
10391                            if(exp.expType.kind == thisClassType)
10392                            {
10393                               FreeType(exp.expType);
10394                               exp.expType = ReplaceThisClassType(_class);
10395                            }
10396
10397                            if(passAsTemplate)
10398                               exp.expType.passAsTemplate = true;
10399                            //exp.expType.refCount++;
10400                            if(!exp.destType)
10401                            {
10402                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10403                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10404                               else if(exp.destType.kind == pointerType)
10405                               {
10406                                  Type t = exp.destType.type;
10407                                  while(t.kind == pointerType) t = t.type;
10408                                  if(constant) t.constant = constant;
10409                               }
10410
10411                               //exp.destType.refCount++;
10412
10413                               if(exp.destType.kind == thisClassType)
10414                               {
10415                                  FreeType(exp.destType);
10416                                  exp.destType = ReplaceThisClassType(_class);
10417                               }
10418                            }
10419                         }
10420                         FinishTemplatesContext(context);
10421                      }
10422                   }
10423                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10424                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10425                   {
10426                      int id = 0;
10427                      ClassTemplateParameter curParam = null;
10428                      Class sClass;
10429
10430                      for(sClass = tClass; sClass; sClass = sClass.base)
10431                      {
10432                         id = 0;
10433                         if(sClass.templateClass) sClass = sClass.templateClass;
10434                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10435                         {
10436                            if(curParam.type == TemplateParameterType::type &&
10437                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10438                            {
10439                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10440                                  id += sClass.templateParams.count;
10441                               break;
10442                            }
10443                            id++;
10444                         }
10445                         if(curParam) break;
10446                      }
10447
10448                      if(curParam)
10449                      {
10450                         ClassTemplateArgument arg = tClass.templateArgs[id];
10451                         Context context = SetupTemplatesContext(tClass);
10452                         Type basicType;
10453                         /*if(!arg.dataType)
10454                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10455
10456                         basicType = ProcessTypeString(arg.dataTypeString, false);
10457                         if(basicType)
10458                         {
10459                            if(basicType.kind == thisClassType)
10460                            {
10461                               FreeType(basicType);
10462                               basicType = ReplaceThisClassType(_class);
10463                            }
10464
10465                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10466                            if(tClass.templateClass)
10467                               basicType.passAsTemplate = true;
10468                            */
10469
10470                            FreeType(exp.expType);
10471
10472                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10473                            //exp.expType.refCount++;
10474                            if(!exp.destType)
10475                            {
10476                               exp.destType = exp.expType;
10477                               exp.destType.refCount++;
10478                            }
10479
10480                            {
10481                               Expression newExp { };
10482                               OldList * specs = MkList();
10483                               Declarator decl;
10484                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10485                               *newExp = *exp;
10486                               if(exp.destType) exp.destType.refCount++;
10487                               if(exp.expType)  exp.expType.refCount++;
10488                               exp.type = castExp;
10489                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10490                               exp.cast.exp = newExp;
10491                               //FreeType(exp.expType);
10492                               //exp.expType = null;
10493                               //ProcessExpressionType(sourceExp);
10494                            }
10495                         }
10496                         FinishTemplatesContext(context);
10497                      }
10498                   }
10499                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10500                   {
10501                      Class expClass = exp.expType._class.registered;
10502                      if(expClass)
10503                      {
10504                         Class cClass = null;
10505                         int p = 0;
10506                         int paramCount = 0;
10507                         int lastParam = -1;
10508                         char templateString[1024];
10509                         ClassTemplateParameter param;
10510                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10511                         while(cClass != expClass)
10512                         {
10513                            Class sClass;
10514                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10515                            cClass = sClass;
10516
10517                            for(param = cClass.templateParams.first; param; param = param.next)
10518                            {
10519                               Class cClassCur = null;
10520                               int cp = 0;
10521                               ClassTemplateParameter paramCur = null;
10522                               ClassTemplateArgument arg;
10523                               while(cClassCur != tClass && !paramCur)
10524                               {
10525                                  Class sClassCur;
10526                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10527                                  cClassCur = sClassCur;
10528
10529                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10530                                  {
10531                                     if(!strcmp(paramCur.name, param.name))
10532                                     {
10533
10534                                        break;
10535                                     }
10536                                     cp++;
10537                                  }
10538                               }
10539                               if(paramCur && paramCur.type == TemplateParameterType::type)
10540                                  arg = tClass.templateArgs[cp];
10541                               else
10542                                  arg = expClass.templateArgs[p];
10543
10544                               {
10545                                  char argument[256];
10546                                  argument[0] = '\0';
10547                                  /*if(arg.name)
10548                                  {
10549                                     strcat(argument, arg.name.string);
10550                                     strcat(argument, " = ");
10551                                  }*/
10552                                  switch(param.type)
10553                                  {
10554                                     case expression:
10555                                     {
10556                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10557                                        char expString[1024];
10558                                        OldList * specs = MkList();
10559                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10560                                        Expression exp;
10561                                        char * string = PrintHexUInt64(arg.expression.ui64);
10562                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10563                                        delete string;
10564
10565                                        ProcessExpressionType(exp);
10566                                        ComputeExpression(exp);
10567                                        expString[0] = '\0';
10568                                        PrintExpression(exp, expString);
10569                                        strcat(argument, expString);
10570                                        // delete exp;
10571                                        FreeExpression(exp);
10572                                        break;
10573                                     }
10574                                     case identifier:
10575                                     {
10576                                        strcat(argument, arg.member.name);
10577                                        break;
10578                                     }
10579                                     case TemplateParameterType::type:
10580                                     {
10581                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10582                                           strcat(argument, arg.dataTypeString);
10583                                        break;
10584                                     }
10585                                  }
10586                                  if(argument[0])
10587                                  {
10588                                     if(paramCount) strcat(templateString, ", ");
10589                                     if(lastParam != p - 1)
10590                                     {
10591                                        strcat(templateString, param.name);
10592                                        strcat(templateString, " = ");
10593                                     }
10594                                     strcat(templateString, argument);
10595                                     paramCount++;
10596                                     lastParam = p;
10597                                  }
10598                               }
10599                               p++;
10600                            }
10601                         }
10602                         {
10603                            int len = strlen(templateString);
10604                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10605                            templateString[len++] = '>';
10606                            templateString[len++] = '\0';
10607                         }
10608
10609                         FreeType(exp.expType);
10610                         {
10611                            Context context = SetupTemplatesContext(tClass);
10612                            exp.expType = ProcessTypeString(templateString, false);
10613                            FinishTemplatesContext(context);
10614                         }
10615                      }
10616                   }
10617                }
10618             }
10619             else
10620                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10621          }
10622          else if(type && (type.kind == structType || type.kind == unionType))
10623          {
10624             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10625             if(memberType)
10626             {
10627                exp.expType = memberType;
10628                if(memberType)
10629                   memberType.refCount++;
10630             }
10631          }
10632          else
10633          {
10634             char expString[10240];
10635             expString[0] = '\0';
10636             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10637             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10638          }
10639
10640          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10641          {
10642             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10643             {
10644                Identifier id = exp.member.member;
10645                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10646                if(_class)
10647                {
10648                   FreeType(exp.expType);
10649                   exp.expType = ReplaceThisClassType(_class);
10650                }
10651             }
10652          }
10653          yylloc = oldyylloc;
10654          break;
10655       }
10656       // Convert x->y into (*x).y
10657       case pointerExp:
10658       {
10659          Type destType = exp.destType;
10660
10661          // DOING THIS LATER NOW...
10662          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10663          {
10664             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10665             /* TODO: Name Space Fix ups
10666             if(!exp.member.member.classSym)
10667                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10668             */
10669          }
10670
10671          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10672          exp.type = memberExp;
10673          if(destType)
10674             destType.count++;
10675          ProcessExpressionType(exp);
10676          if(destType)
10677             destType.count--;
10678          break;
10679       }
10680       case classSizeExp:
10681       {
10682          //ComputeExpression(exp);
10683
10684          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10685          if(classSym && classSym.registered)
10686          {
10687             if(classSym.registered.type == noHeadClass || (classSym.registered.fixed && classSym.registered.structSize))
10688             {
10689                char name[1024];
10690                Class b = classSym.registered;
10691                name[0] = '\0';
10692                DeclareStruct(curExternal, classSym.string, false, true);
10693                FreeSpecifier(exp._class);
10694                FullClassNameCat(name, classSym.string, false);
10695
10696                if(b.offset == 0)
10697                {
10698                   exp.type = typeSizeExp;
10699                   exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10700                }
10701                else
10702                {
10703                   Expression e;
10704                   exp.type = opExp;
10705                   if(b.structSize == b.offset)
10706                      exp.op.exp1 = MkExpConstant("0");
10707                   else
10708                      exp.op.exp1 = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10709                   exp.op.op = '+';
10710                   e = exp;
10711                   while(b.offset != 0)
10712                   {
10713                      Symbol sym;
10714                      Expression typeSize;
10715
10716                      b = b.base;
10717                      sym = FindClass(b.fullName);
10718
10719                      name[0] = '\0';
10720                      DeclareStruct(curExternal, sym.string, false, true);
10721                      FullClassNameCat(name, sym.string, false);
10722
10723                      if(b.structSize == b.offset)
10724                         typeSize = MkExpConstant("0");
10725                      else
10726                         typeSize = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10727                      e.op.exp2 = b.offset ? MkExpOp(typeSize, '+', null) : typeSize;
10728                      e = e.op.exp2;
10729                   }
10730                }
10731             }
10732             else
10733             {
10734                if(classSym.registered.fixed && !classSym.registered.structSize)
10735                {
10736                   FreeSpecifier(exp._class);
10737                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10738                   exp.type = constantExp;
10739                }
10740                else
10741                {
10742                   char className[1024];
10743                   strcpy(className, "__ecereClass_");
10744                   FullClassNameCat(className, classSym.string, true);
10745
10746                   DeclareClass(curExternal, classSym, className);
10747
10748                   FreeExpContents(exp);
10749                   exp.type = pointerExp;
10750                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10751                   exp.member.member = MkIdentifier("structSize");
10752                }
10753             }
10754          }
10755
10756          exp.expType = Type
10757          {
10758             refCount = 1;
10759             kind = intSizeType;
10760          };
10761          // exp.isConstant = true;
10762          break;
10763       }
10764       case typeSizeExp:
10765       {
10766          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10767
10768          exp.expType = Type
10769          {
10770             refCount = 1;
10771             kind = intSizeType;
10772          };
10773          exp.isConstant = true;
10774
10775          DeclareType(curExternal, type, true, false);
10776          FreeType(type);
10777          break;
10778       }
10779       case castExp:
10780       {
10781          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10782          type.count = 1;
10783          FreeType(exp.cast.exp.destType);
10784          exp.cast.exp.destType = type;
10785          type.refCount++;
10786          type.casted = true;
10787          ProcessExpressionType(exp.cast.exp);
10788          type.casted = false;
10789          type.count = 0;
10790          exp.expType = type;
10791          //type.refCount++;
10792
10793          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10794          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10795          {
10796             void * prev = exp.prev, * next = exp.next;
10797             Type expType = exp.cast.exp.destType;
10798             Expression castExp = exp.cast.exp;
10799             Type destType = exp.destType;
10800
10801             if(expType) expType.refCount++;
10802
10803             //FreeType(exp.destType);
10804             FreeType(exp.expType);
10805             FreeTypeName(exp.cast.typeName);
10806
10807             *exp = *castExp;
10808             FreeType(exp.expType);
10809             FreeType(exp.destType);
10810
10811             exp.expType = expType;
10812             exp.destType = destType;
10813
10814             delete castExp;
10815
10816             exp.prev = prev;
10817             exp.next = next;
10818
10819          }
10820          else
10821          {
10822             exp.isConstant = exp.cast.exp.isConstant;
10823          }
10824          //FreeType(type);
10825          break;
10826       }
10827       case extensionInitializerExp:
10828       {
10829          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10830          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10831          // ProcessInitializer(exp.initializer.initializer, type);
10832          exp.expType = type;
10833          break;
10834       }
10835       case vaArgExp:
10836       {
10837          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10838          ProcessExpressionType(exp.vaArg.exp);
10839          exp.expType = type;
10840          break;
10841       }
10842       case conditionExp:
10843       {
10844          Expression e;
10845          Type t = exp.destType;
10846          if(t && !exp.destType.casted)
10847          {
10848             t = { };
10849             CopyTypeInto(t, exp.destType);
10850             t.count = 0;
10851          }
10852          else if(t)
10853             t.refCount++;
10854
10855          exp.isConstant = true;
10856
10857          FreeType(exp.cond.cond.destType);
10858          exp.cond.cond.destType = MkClassType("bool");
10859          exp.cond.cond.destType.truth = true;
10860          ProcessExpressionType(exp.cond.cond);
10861          if(!exp.cond.cond.isConstant)
10862             exp.isConstant = false;
10863          for(e = exp.cond.exp->first; e; e = e.next)
10864          {
10865             if(!e.next)
10866             {
10867                FreeType(e.destType);
10868                e.destType = t;
10869                if(e.destType) e.destType.refCount++;
10870             }
10871             ProcessExpressionType(e);
10872             if(!e.next)
10873             {
10874                exp.expType = e.expType;
10875                if(e.expType) e.expType.refCount++;
10876             }
10877             if(!e.isConstant)
10878                exp.isConstant = false;
10879          }
10880
10881          FreeType(exp.cond.elseExp.destType);
10882          // Added this check if we failed to find an expType
10883          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10884
10885          // Reversed it...
10886          exp.cond.elseExp.destType = t ? t : exp.expType;
10887
10888          if(exp.cond.elseExp.destType)
10889             exp.cond.elseExp.destType.refCount++;
10890          ProcessExpressionType(exp.cond.elseExp);
10891
10892          // FIXED THIS: Was done before calling process on elseExp
10893          if(!exp.cond.elseExp.isConstant)
10894             exp.isConstant = false;
10895
10896          FreeType(t);
10897          break;
10898       }
10899       case extensionCompoundExp:
10900       {
10901          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10902          {
10903             Statement last = exp.compound.compound.statements->last;
10904             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10905             {
10906                ((Expression)last.expressions->last).destType = exp.destType;
10907                if(exp.destType)
10908                   exp.destType.refCount++;
10909             }
10910             ProcessStatement(exp.compound);
10911             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10912             if(exp.expType)
10913                exp.expType.refCount++;
10914          }
10915          break;
10916       }
10917       case classExp:
10918       {
10919          Specifier spec = exp._classExp.specifiers->first;
10920          if(spec && spec.type == nameSpecifier)
10921          {
10922             exp.expType = MkClassType(spec.name);
10923             exp.expType.kind = subClassType;
10924             exp.byReference = true;
10925          }
10926          else
10927          {
10928             exp.expType = MkClassType("ecere::com::Class");
10929             exp.byReference = true;
10930          }
10931          break;
10932       }
10933       case classDataExp:
10934       {
10935          Class _class = thisClass ? thisClass : currentClass;
10936          if(_class)
10937          {
10938             Identifier id = exp.classData.id;
10939             char structName[1024];
10940             Expression classExp;
10941             strcpy(structName, "__ecereClassData_");
10942             FullClassNameCat(structName, _class.fullName, false);
10943             exp.type = pointerExp;
10944             exp.member.member = id;
10945             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10946                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10947             else
10948                classExp = MkExpIdentifier(MkIdentifier("class"));
10949
10950             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10951                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10952                   MkExpBrackets(MkListOne(MkExpOp(
10953                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10954                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10955                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10956                      )));
10957
10958             ProcessExpressionType(exp);
10959             return;
10960          }
10961          break;
10962       }
10963       case arrayExp:
10964       {
10965          Type type = null;
10966          const char * typeString = null;
10967          char typeStringBuf[1024];
10968          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
10969             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
10970          {
10971             Class templateClass = exp.destType._class.registered;
10972             typeString = templateClass.templateArgs[2].dataTypeString;
10973          }
10974          else if(exp.list)
10975          {
10976             // Guess type from expressions in the array
10977             Expression e;
10978             for(e = exp.list->first; e; e = e.next)
10979             {
10980                ProcessExpressionType(e);
10981                if(e.expType)
10982                {
10983                   if(!type) { type = e.expType; type.refCount++; }
10984                   else
10985                   {
10986                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
10987                      if(!MatchTypeExpression(e, type, null, false, true))
10988                      {
10989                         FreeType(type);
10990                         type = e.expType;
10991                         e.expType = null;
10992
10993                         e = exp.list->first;
10994                         ProcessExpressionType(e);
10995                         if(e.expType)
10996                         {
10997                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
10998                            if(!MatchTypeExpression(e, type, null, false, true))
10999                            {
11000                               FreeType(e.expType);
11001                               e.expType = null;
11002                               FreeType(type);
11003                               type = null;
11004                               break;
11005                            }
11006                         }
11007                      }
11008                   }
11009                   if(e.expType)
11010                   {
11011                      FreeType(e.expType);
11012                      e.expType = null;
11013                   }
11014                }
11015             }
11016             if(type)
11017             {
11018                typeStringBuf[0] = '\0';
11019                PrintTypeNoConst(type, typeStringBuf, false, true);
11020                typeString = typeStringBuf;
11021                FreeType(type);
11022                type = null;
11023             }
11024          }
11025          if(typeString)
11026          {
11027             /*
11028             (Container)& (struct BuiltInContainer)
11029             {
11030                ._vTbl = class(BuiltInContainer)._vTbl,
11031                ._class = class(BuiltInContainer),
11032                .refCount = 0,
11033                .data = (int[]){ 1, 7, 3, 4, 5 },
11034                .count = 5,
11035                .type = class(int),
11036             }
11037             */
11038             char templateString[1024];
11039             OldList * initializers = MkList();
11040             OldList * structInitializers = MkList();
11041             OldList * specs = MkList();
11042             Expression expExt;
11043             Declarator decl = SpecDeclFromString(typeString, specs, null);
11044             sprintf(templateString, "Container<%s>", typeString);
11045
11046             if(exp.list)
11047             {
11048                Expression e;
11049                type = ProcessTypeString(typeString, false);
11050                while((e = exp.list->first))
11051                {
11052                   exp.list->Remove(e);
11053                   e.destType = type;
11054                   type.refCount++;
11055                   ProcessExpressionType(e);
11056                   ListAdd(initializers, MkInitializerAssignment(e));
11057                }
11058                FreeType(type);
11059                delete exp.list;
11060             }
11061
11062             DeclareStruct(curExternal, "ecere::com::BuiltInContainer", false, true);
11063
11064             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11065                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11066             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11067                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11068             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11069                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11070             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11071                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11072                MkInitializerList(initializers))));
11073                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11074             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11075                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11076             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11077                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11078             exp.expType = ProcessTypeString(templateString, false);
11079             exp.type = bracketsExp;
11080             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11081                MkExpOp(null, '&',
11082                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11083                   MkInitializerList(structInitializers)))));
11084             ProcessExpressionType(expExt);
11085          }
11086          else
11087          {
11088             exp.expType = ProcessTypeString("Container", false);
11089             Compiler_Error($"Couldn't determine type of array elements\n");
11090          }
11091          break;
11092       }
11093    }
11094
11095    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11096    {
11097       FreeType(exp.expType);
11098       exp.expType = ReplaceThisClassType(thisClass);
11099    }
11100
11101    // Resolve structures here
11102    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11103    {
11104       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11105       // TODO: Fix members reference...
11106       if(symbol)
11107       {
11108          if(exp.expType.kind != enumType)
11109          {
11110             Type member;
11111             String enumName = CopyString(exp.expType.enumName);
11112
11113             // Fixed a memory leak on self-referencing C structs typedefs
11114             // by instantiating a new type rather than simply copying members
11115             // into exp.expType
11116             FreeType(exp.expType);
11117             exp.expType = Type { };
11118             exp.expType.kind = symbol.type.kind;
11119             exp.expType.refCount++;
11120             exp.expType.enumName = enumName;
11121
11122             exp.expType.members = symbol.type.members;
11123             for(member = symbol.type.members.first; member; member = member.next)
11124                member.refCount++;
11125          }
11126          else
11127          {
11128             NamedLink64 member;
11129             for(member = symbol.type.members.first; member; member = member.next)
11130             {
11131                NamedLink64 value { name = CopyString(member.name) };
11132                exp.expType.members.Add(value);
11133             }
11134          }
11135       }
11136    }
11137
11138    yylloc = exp.loc;
11139    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11140    else if(exp.destType && !exp.destType.keepCast)
11141    {
11142       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11143          exp.needTemplateCast = 1;
11144
11145       if(exp.destType.kind == voidType);
11146       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11147       {
11148          // Warn for casting unrelated types to/from struct classes
11149          bool invalidCast = false;
11150          if(inCompiler && exp.destType.count && exp.expType)
11151          {
11152             Class c1 = (exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
11153             Class c2 = (exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
11154             if(c1 && c1.type != structClass) c1 = null;
11155             if(c2 && c2.type != structClass) c2 = null;
11156             if((c1 && !exp.expType.byReference && !c2 && !exp.destType.isPointerType) || (c2 && !exp.destType.byReference && !c1 && !exp.expType.isPointerType))
11157                invalidCast = true;
11158          }
11159          if(!exp.destType.count || unresolved || invalidCast)
11160          {
11161             if(!exp.expType)
11162             {
11163                yylloc = exp.loc;
11164                if(exp.destType.kind != ellipsisType)
11165                {
11166                   char type2[1024];
11167                   type2[0] = '\0';
11168                   if(inCompiler)
11169                   {
11170                      char expString[10240];
11171                      expString[0] = '\0';
11172
11173                      PrintType(exp.destType, type2, false, true);
11174
11175                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11176                      if(unresolved)
11177                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11178                      else if(exp.type != dummyExp)
11179                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11180                   }
11181                }
11182                else
11183                {
11184                   char expString[10240] ;
11185                   expString[0] = '\0';
11186                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11187
11188                   if(unresolved)
11189                      Compiler_Error($"unresolved identifier %s\n", expString);
11190                   else if(exp.type != dummyExp)
11191                      Compiler_Error($"couldn't determine type of %s\n", expString);
11192                }
11193             }
11194             else
11195             {
11196                char type1[1024];
11197                char type2[1024];
11198                type1[0] = '\0';
11199                type2[0] = '\0';
11200                if(inCompiler)
11201                {
11202                   PrintType(exp.expType, type1, false, true);
11203                   PrintType(exp.destType, type2, false, true);
11204                }
11205
11206                //CheckExpressionType(exp, exp.destType, false);
11207
11208                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11209                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11210                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11211                else
11212                {
11213                   Expression nbExp = GetNonBracketsExp(exp);
11214                   bool skipWarning = false;
11215                   TypeKind kind = exp.destType.kind;
11216                   if((kind == charType || kind == shortType) && exp.destType.isSigned == exp.expType.signedBeforePromotion && nbExp.type == opExp && nbExp.op.exp1 && nbExp.op.exp2)
11217                   {
11218                      int op = nbExp.op.op;
11219                      Expression nbExp1, nbExp2;
11220                      TypeKind from;
11221
11222                      switch(op)
11223                      {
11224                         case '%': case '/':
11225                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11226                            from = nbExp1.expType.promotedFrom;
11227                            // Division and Modulo will not take more room than type before promotion
11228                            if(from == charType || (kind == shortType && from == shortType))
11229                               skipWarning = true;
11230                            break;
11231                         // Left shift
11232                         case LEFT_OP: case RIGHT_OP:
11233                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11234                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11235                            from = nbExp1.expType.promotedFrom;
11236                            // Right shift will not take more room than type before promotion
11237                            if(op == RIGHT_OP && (from == charType || (kind == shortType && from == shortType)))
11238                               skipWarning = true;
11239                            else if(nbExp2.isConstant && nbExp2.type == constantExp && (nbExp.op.op == RIGHT_OP || nbExp1.expType.bitMemberSize))
11240                            {
11241                               int n = (int)strtol(nbExp2.constant, null, 0);
11242                               int s = from == charType ? 8 : 16;
11243                               // Left shifting a bit member constrained in size may still fit in type before promotion
11244                               if(nbExp1.expType.bitMemberSize && nbExp1.expType.bitMemberSize < s)
11245                                  s = nbExp1.expType.bitMemberSize;
11246
11247                               // If right shifted enough things will fit in smaller type
11248                               if(nbExp.op.op == RIGHT_OP)
11249                                  s -= n;
11250                               else
11251                                  s += n;
11252                               if(s <= (kind == charType ? 8 : 16))
11253                                  skipWarning = true;
11254                            }
11255                            break;
11256                         case '-':
11257                            if(!exp.destType.isSigned)
11258                            {
11259                               Expression nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11260                               Expression nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11261                               TypeKind from = nbExp2.expType.promotedFrom;
11262                               // Max value of unsigned type before promotion minus the same will always fit
11263                               if((from == charType || from == shortType) && nbExp1.isConstant && nbExp1.type == constantExp)
11264                               {
11265                                  int n = (int)strtol(nbExp1.constant, null, 0);
11266                                  if(n == (from == charType ? 255 : 65535))
11267                                     skipWarning = true;
11268                               }
11269                            }
11270                            break;
11271                      }
11272                   }
11273
11274                   if(!skipWarning)
11275                   {
11276                      char expString[10240];
11277                      expString[0] = '\0';
11278                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11279
11280 #ifdef _DEBUG
11281                      CheckExpressionType(exp, exp.destType, false, true);
11282 #endif
11283
11284                      // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11285                      if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11286                                         !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11287                                         !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11288                                         !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11289                      {
11290                         if(invalidCast)
11291                            Compiler_Error($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11292                         else
11293                            Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11294                      }
11295                   }
11296
11297                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11298                   if(!inCompiler)
11299                   {
11300                      FreeType(exp.expType);
11301                      exp.destType.refCount++;
11302                      exp.expType = exp.destType;
11303                   }
11304                }
11305             }
11306          }
11307       }
11308       // Cast function pointers to void * as eC already checked compatibility
11309       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11310               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11311       {
11312          Expression nbExp = GetNonBracketsExp(exp);
11313          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11314          {
11315             Expression e = MoveExpContents(exp);
11316             exp.cast.exp = MkExpBrackets(MkListOne(e));
11317             exp.type = castExp;
11318             exp.cast.exp.destType = exp.destType;
11319             if(exp.destType) exp.destType.refCount++;
11320             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11321          }
11322       }
11323    }
11324    else if(unresolved)
11325    {
11326       if(exp.identifier._class && exp.identifier._class.name)
11327          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11328       else if(exp.identifier.string && exp.identifier.string[0])
11329          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11330    }
11331    else if(!exp.expType && exp.type != dummyExp)
11332    {
11333       char expString[10240];
11334       expString[0] = '\0';
11335       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11336       Compiler_Error($"couldn't determine type of %s\n", expString);
11337    }
11338
11339    // Let's try to support any_object & typed_object here:
11340    if(inCompiler)
11341       ApplyAnyObjectLogic(exp);
11342
11343    // Mark nohead classes as by reference, unless we're casting them to an integral type
11344    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11345       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11346          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11347           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11348    {
11349       exp.byReference = true;
11350    }
11351    yylloc = oldyylloc;
11352 }
11353
11354 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11355 {
11356    // THIS CODE WILL FIND NEXT MEMBER...
11357    if(*curMember)
11358    {
11359       *curMember = (*curMember).next;
11360
11361       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11362       {
11363          *curMember = subMemberStack[--(*subMemberStackPos)];
11364          *curMember = (*curMember).next;
11365       }
11366
11367       // SKIP ALL PROPERTIES HERE...
11368       while((*curMember) && (*curMember).isProperty)
11369          *curMember = (*curMember).next;
11370
11371       if(subMemberStackPos)
11372       {
11373          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11374          {
11375             subMemberStack[(*subMemberStackPos)++] = *curMember;
11376
11377             *curMember = (*curMember).members.first;
11378             while(*curMember && (*curMember).isProperty)
11379                *curMember = (*curMember).next;
11380          }
11381       }
11382    }
11383    while(!*curMember)
11384    {
11385       if(!*curMember)
11386       {
11387          if(subMemberStackPos && *subMemberStackPos)
11388          {
11389             *curMember = subMemberStack[--(*subMemberStackPos)];
11390             *curMember = (*curMember).next;
11391          }
11392          else
11393          {
11394             Class lastCurClass = *curClass;
11395
11396             if(*curClass == _class) break;     // REACHED THE END
11397
11398             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11399             *curMember = (*curClass).membersAndProperties.first;
11400          }
11401
11402          while((*curMember) && (*curMember).isProperty)
11403             *curMember = (*curMember).next;
11404          if(subMemberStackPos)
11405          {
11406             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11407             {
11408                subMemberStack[(*subMemberStackPos)++] = *curMember;
11409
11410                *curMember = (*curMember).members.first;
11411                while(*curMember && (*curMember).isProperty)
11412                   *curMember = (*curMember).next;
11413             }
11414          }
11415       }
11416    }
11417 }
11418
11419
11420 static void ProcessInitializer(Initializer init, Type type)
11421 {
11422    switch(init.type)
11423    {
11424       case expInitializer:
11425          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11426          {
11427             // TESTING THIS FOR SHUTTING = 0 WARNING
11428             if(init.exp && !init.exp.destType)
11429             {
11430                FreeType(init.exp.destType);
11431                init.exp.destType = type;
11432                if(type) type.refCount++;
11433             }
11434             if(init.exp)
11435             {
11436                ProcessExpressionType(init.exp);
11437                init.isConstant = init.exp.isConstant;
11438             }
11439             break;
11440          }
11441          else
11442          {
11443             Expression exp = init.exp;
11444             Instantiation inst = exp.instance;
11445             MembersInit members;
11446
11447             init.type = listInitializer;
11448             init.list = MkList();
11449
11450             if(inst.members)
11451             {
11452                for(members = inst.members->first; members; members = members.next)
11453                {
11454                   if(members.type == dataMembersInit)
11455                   {
11456                      MemberInit member;
11457                      for(member = members.dataMembers->first; member; member = member.next)
11458                      {
11459                         ListAdd(init.list, member.initializer);
11460                         member.initializer = null;
11461                      }
11462                   }
11463                   // Discard all MembersInitMethod
11464                }
11465             }
11466             FreeExpression(exp);
11467          }
11468       case listInitializer:
11469       {
11470          Initializer i;
11471          Type initializerType = null;
11472          Class curClass = null;
11473          DataMember curMember = null;
11474          DataMember subMemberStack[256];
11475          int subMemberStackPos = 0;
11476
11477          if(type && type.kind == arrayType)
11478             initializerType = Dereference(type);
11479          else if(type && (type.kind == structType || type.kind == unionType))
11480             initializerType = type.members.first;
11481
11482          for(i = init.list->first; i; i = i.next)
11483          {
11484             if(type && type.kind == classType && type._class && type._class.registered)
11485             {
11486                // THIS IS FOR A C STYLE INSTANTIATION OF STRUCT CLASSES ONLY... WE ONLY CARE ABOUT DATA MEMBERS, AND ACTUAL MEMORY ORDER (PRIVATE MEMBERS ARE INCLUDED)
11487                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11488                // TODO: Generate error on initializing a private data member this way from another module...
11489                if(curMember)
11490                {
11491                   if(!curMember.dataType)
11492                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11493                   initializerType = curMember.dataType;
11494                }
11495             }
11496             ProcessInitializer(i, initializerType);
11497             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11498                initializerType = initializerType.next;
11499             if(!i.isConstant)
11500                init.isConstant = false;
11501          }
11502
11503          if(type && type.kind == arrayType)
11504             FreeType(initializerType);
11505
11506          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11507          {
11508             Compiler_Error($"Assigning list initializer to non list\n");
11509          }
11510          break;
11511       }
11512    }
11513 }
11514
11515 static void ProcessSpecifier(Specifier spec, bool declareStruct, bool warnClasses)
11516 {
11517    switch(spec.type)
11518    {
11519       case baseSpecifier:
11520       {
11521          if(spec.specifier == THISCLASS)
11522          {
11523             if(thisClass)
11524             {
11525                spec.type = nameSpecifier;
11526                spec.name = ReplaceThisClass(thisClass);
11527                spec.symbol = FindClass(spec.name);
11528                ProcessSpecifier(spec, declareStruct, false);
11529             }
11530          }
11531          break;
11532       }
11533       case nameSpecifier:
11534       {
11535          Symbol symbol = FindType(curContext, spec.name);
11536          if(symbol)
11537             DeclareType(curExternal, symbol.type, true, true);
11538          else if(spec.symbol /*&& declareStruct*/)
11539          {
11540             Class c = spec.symbol.registered;
11541             if(warnClasses && !c)
11542                Compiler_Warning("Undeclared class %s\n", spec.name);
11543             DeclareStruct(curExternal, spec.name, c && c.type == noHeadClass, declareStruct && c && c.type == structClass);
11544          }
11545          break;
11546       }
11547       case enumSpecifier:
11548       {
11549          Enumerator e;
11550          if(spec.list)
11551          {
11552             for(e = spec.list->first; e; e = e.next)
11553             {
11554                if(e.exp)
11555                   ProcessExpressionType(e.exp);
11556             }
11557          }
11558          // Fall through for IDE type processing
11559          if(inCompiler)
11560             break;
11561       }
11562       case structSpecifier:
11563       case unionSpecifier:
11564       {
11565          if(spec.definitions)
11566          {
11567             //ClassDef def;
11568             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11569             //if(symbol)
11570                ProcessClass(spec.definitions, symbol);
11571             /*else
11572             {
11573                for(def = spec.definitions->first; def; def = def.next)
11574                {
11575                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11576                      ProcessDeclaration(def.decl);
11577                }
11578             }*/
11579          }
11580          break;
11581       }
11582       /*
11583       case classSpecifier:
11584       {
11585          Symbol classSym = FindClass(spec.name);
11586          if(classSym && classSym.registered && classSym.registered.type == structClass)
11587             DeclareStruct(spec.name, false, true);
11588          break;
11589       }
11590       */
11591    }
11592 }
11593
11594
11595 static void ProcessDeclarator(Declarator decl, bool isFunction)
11596 {
11597    switch(decl.type)
11598    {
11599       case identifierDeclarator:
11600          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11601          {
11602             FreeSpecifier(decl.identifier._class);
11603             decl.identifier._class = null;
11604          }
11605          break;
11606       case arrayDeclarator:
11607          if(decl.array.exp)
11608             ProcessExpressionType(decl.array.exp);
11609       case structDeclarator:
11610       case bracketsDeclarator:
11611       case functionDeclarator:
11612       case pointerDeclarator:
11613       case extendedDeclarator:
11614       case extendedDeclaratorEnd:
11615       {
11616          Identifier id = null;
11617          Specifier classSpec = null;
11618          if(decl.type == functionDeclarator)
11619          {
11620             id = GetDeclId(decl);
11621             if(id && id._class)
11622             {
11623                classSpec = id._class;
11624                id._class = null;
11625             }
11626          }
11627          if(decl.declarator)
11628             ProcessDeclarator(decl.declarator, isFunction);
11629          if(decl.type == functionDeclarator)
11630          {
11631             if(classSpec)
11632             {
11633                TypeName param
11634                {
11635                   qualifiers = MkListOne(classSpec);
11636                   declarator = null;
11637                };
11638                if(!decl.function.parameters)
11639                   decl.function.parameters = MkList();
11640                decl.function.parameters->Insert(null, param);
11641             }
11642             if(decl.function.parameters)
11643             {
11644                TypeName param;
11645
11646                for(param = decl.function.parameters->first; param; param = param.next)
11647                {
11648                   if(param.qualifiers)
11649                   {
11650                      Specifier spec;
11651                      for(spec = param.qualifiers->first; spec; spec = spec.next)
11652                      {
11653                         if(spec.type == baseSpecifier)
11654                         {
11655                            if(spec.specifier == TYPED_OBJECT)
11656                            {
11657                               Declarator d = param.declarator;
11658                               TypeName newParam
11659                               {
11660                                  qualifiers = MkListOne(MkSpecifier(VOID));
11661                                  declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11662                               };
11663                               if(d.type != pointerDeclarator)
11664                                  newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11665
11666                               FreeList(param.qualifiers, FreeSpecifier);
11667
11668                               param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11669                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11670
11671                               DeclareStruct(curExternal, "ecere::com::Class", false, true);
11672
11673                               decl.function.parameters->Insert(param, newParam);
11674                               param = newParam;
11675                               break;
11676                            }
11677                            else if(spec.specifier == ANY_OBJECT)
11678                            {
11679                               Declarator d = param.declarator;
11680
11681                               FreeList(param.qualifiers, FreeSpecifier);
11682
11683                               param.qualifiers = MkListOne(MkSpecifier(VOID));
11684                               if(d.type != pointerDeclarator)
11685                                  param.qualifiers->Insert(null, MkSpecifier(CONST));
11686                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11687                               break;
11688                            }
11689                            else if(spec.specifier == THISCLASS)
11690                            {
11691                               if(thisClass)
11692                               {
11693                                  spec.type = nameSpecifier;
11694                                  spec.name = ReplaceThisClass(thisClass);
11695                                  spec.symbol = FindClass(spec.name);
11696                                  ProcessSpecifier(spec, false, false);
11697                               }
11698                               break;
11699                            }
11700                         }
11701                         else if(spec.type == nameSpecifier)
11702                         {
11703                            ProcessSpecifier(spec, isFunction, true);
11704                         }
11705                      }
11706                   }
11707
11708                   if(param.declarator)
11709                      ProcessDeclarator(param.declarator, false);
11710                }
11711             }
11712          }
11713          break;
11714       }
11715    }
11716 }
11717
11718 static void ProcessDeclaration(Declaration decl, bool warnClasses)
11719 {
11720    yylloc = decl.loc;
11721    switch(decl.type)
11722    {
11723       case initDeclaration:
11724       {
11725          bool declareStruct = false;
11726          /*
11727          lineNum = decl.pos.line;
11728          column = decl.pos.col;
11729          */
11730
11731          if(decl.declarators)
11732          {
11733             InitDeclarator d;
11734
11735             for(d = decl.declarators->first; d; d = d.next)
11736             {
11737                Type type, subType;
11738                ProcessDeclarator(d.declarator, false);
11739
11740                type = ProcessType(decl.specifiers, d.declarator);
11741
11742                if(d.initializer)
11743                {
11744                   ProcessInitializer(d.initializer, type);
11745
11746                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11747
11748                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11749                      d.initializer.exp.type == instanceExp)
11750                   {
11751                      if(type.kind == classType && type._class ==
11752                         d.initializer.exp.expType._class)
11753                      {
11754                         Instantiation inst = d.initializer.exp.instance;
11755                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11756
11757                         d.initializer.exp.instance = null;
11758                         if(decl.specifiers)
11759                            FreeList(decl.specifiers, FreeSpecifier);
11760                         FreeList(decl.declarators, FreeInitDeclarator);
11761
11762                         d = null;
11763
11764                         decl.type = instDeclaration;
11765                         decl.inst = inst;
11766                      }
11767                   }
11768                }
11769                for(subType = type; subType;)
11770                {
11771                   if(subType.kind == classType)
11772                   {
11773                      declareStruct = true;
11774                      break;
11775                   }
11776                   else if(subType.kind == pointerType)
11777                      break;
11778                   else if(subType.kind == arrayType)
11779                      subType = subType.arrayType;
11780                   else
11781                      break;
11782                }
11783
11784                FreeType(type);
11785                if(!d) break;
11786             }
11787          }
11788
11789          if(decl.specifiers)
11790          {
11791             Specifier s;
11792             for(s = decl.specifiers->first; s; s = s.next)
11793             {
11794                ProcessSpecifier(s, declareStruct, true);
11795             }
11796          }
11797          break;
11798       }
11799       case instDeclaration:
11800       {
11801          ProcessInstantiationType(decl.inst);
11802          break;
11803       }
11804       case structDeclaration:
11805       {
11806          Specifier spec;
11807          Declarator d;
11808          bool declareStruct = false;
11809
11810          if(decl.declarators)
11811          {
11812             for(d = decl.declarators->first; d; d = d.next)
11813             {
11814                Type type = ProcessType(decl.specifiers, d.declarator);
11815                Type subType;
11816                ProcessDeclarator(d, false);
11817                for(subType = type; subType;)
11818                {
11819                   if(subType.kind == classType)
11820                   {
11821                      declareStruct = true;
11822                      break;
11823                   }
11824                   else if(subType.kind == pointerType)
11825                      break;
11826                   else if(subType.kind == arrayType)
11827                      subType = subType.arrayType;
11828                   else
11829                      break;
11830                }
11831                FreeType(type);
11832             }
11833          }
11834          if(decl.specifiers)
11835          {
11836             for(spec = decl.specifiers->first; spec; spec = spec.next)
11837                ProcessSpecifier(spec, declareStruct, warnClasses);
11838          }
11839          break;
11840       }
11841    }
11842 }
11843
11844 static FunctionDefinition curFunction;
11845
11846 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11847 {
11848    char propName[1024], propNameM[1024];
11849    char getName[1024], setName[1024];
11850    OldList * args;
11851
11852    DeclareProperty(curExternal, prop, setName, getName);
11853
11854    // eInstance_FireWatchers(object, prop);
11855    strcpy(propName, "__ecereProp_");
11856    FullClassNameCat(propName, prop._class.fullName, false);
11857    strcat(propName, "_");
11858    FullClassNameCat(propName, prop.name, true);
11859
11860    strcpy(propNameM, "__ecerePropM_");
11861    FullClassNameCat(propNameM, prop._class.fullName, false);
11862    strcat(propNameM, "_");
11863    FullClassNameCat(propNameM, prop.name, true);
11864
11865    if(prop.isWatchable)
11866    {
11867       args = MkList();
11868       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11869       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11870       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11871
11872       args = MkList();
11873       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11874       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11875       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11876
11877       DeclareFunctionUtil(curExternal, "eInstance_FireWatchers");
11878    }
11879
11880    {
11881       args = MkList();
11882       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11883       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11884       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11885
11886       args = MkList();
11887       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11888       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11889       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11890
11891       DeclareFunctionUtil(curExternal, "eInstance_FireSelfWatchers");
11892    }
11893
11894    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11895       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11896       curFunction.propSet.fireWatchersDone = true;
11897 }
11898
11899 static void ProcessStatement(Statement stmt)
11900 {
11901    yylloc = stmt.loc;
11902    /*
11903    lineNum = stmt.pos.line;
11904    column = stmt.pos.col;
11905    */
11906    switch(stmt.type)
11907    {
11908       case labeledStmt:
11909          ProcessStatement(stmt.labeled.stmt);
11910          break;
11911       case caseStmt:
11912          // This expression should be constant...
11913          if(stmt.caseStmt.exp)
11914          {
11915             FreeType(stmt.caseStmt.exp.destType);
11916             stmt.caseStmt.exp.destType = curSwitchType;
11917             if(curSwitchType) curSwitchType.refCount++;
11918             ProcessExpressionType(stmt.caseStmt.exp);
11919             ComputeExpression(stmt.caseStmt.exp);
11920          }
11921          if(stmt.caseStmt.stmt)
11922             ProcessStatement(stmt.caseStmt.stmt);
11923          break;
11924       case compoundStmt:
11925       {
11926          if(stmt.compound.context)
11927          {
11928             Declaration decl;
11929             Statement s;
11930
11931             Statement prevCompound = curCompound;
11932             Context prevContext = curContext;
11933
11934             if(!stmt.compound.isSwitch)
11935                curCompound = stmt;
11936             curContext = stmt.compound.context;
11937
11938             if(stmt.compound.declarations)
11939             {
11940                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
11941                   ProcessDeclaration(decl, true);
11942             }
11943             if(stmt.compound.statements)
11944             {
11945                for(s = stmt.compound.statements->first; s; s = s.next)
11946                   ProcessStatement(s);
11947             }
11948
11949             curContext = prevContext;
11950             curCompound = prevCompound;
11951          }
11952          break;
11953       }
11954       case expressionStmt:
11955       {
11956          Expression exp;
11957          if(stmt.expressions)
11958          {
11959             for(exp = stmt.expressions->first; exp; exp = exp.next)
11960                ProcessExpressionType(exp);
11961          }
11962          break;
11963       }
11964       case ifStmt:
11965       {
11966          Expression exp;
11967
11968          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
11969          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
11970          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
11971          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
11972          {
11973             ProcessExpressionType(exp);
11974          }
11975          if(stmt.ifStmt.stmt)
11976             ProcessStatement(stmt.ifStmt.stmt);
11977          if(stmt.ifStmt.elseStmt)
11978             ProcessStatement(stmt.ifStmt.elseStmt);
11979          break;
11980       }
11981       case switchStmt:
11982       {
11983          Type oldSwitchType = curSwitchType;
11984          if(stmt.switchStmt.exp)
11985          {
11986             Expression exp;
11987             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
11988             {
11989                if(!exp.next)
11990                {
11991                   /*
11992                   Type destType
11993                   {
11994                      kind = intType;
11995                      refCount = 1;
11996                   };
11997                   e.exp.destType = destType;
11998                   */
11999
12000                   ProcessExpressionType(exp);
12001                }
12002                if(!exp.next)
12003                   curSwitchType = exp.expType;
12004             }
12005          }
12006          ProcessStatement(stmt.switchStmt.stmt);
12007          curSwitchType = oldSwitchType;
12008          break;
12009       }
12010       case whileStmt:
12011       {
12012          if(stmt.whileStmt.exp)
12013          {
12014             Expression exp;
12015
12016             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
12017             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
12018             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
12019             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
12020             {
12021                ProcessExpressionType(exp);
12022             }
12023          }
12024          if(stmt.whileStmt.stmt)
12025             ProcessStatement(stmt.whileStmt.stmt);
12026          break;
12027       }
12028       case doWhileStmt:
12029       {
12030          if(stmt.doWhile.exp)
12031          {
12032             Expression exp;
12033
12034             if(stmt.doWhile.exp->last)
12035             {
12036                FreeType(((Expression)stmt.doWhile.exp->last).destType);
12037                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
12038                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
12039             }
12040             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
12041             {
12042                ProcessExpressionType(exp);
12043             }
12044          }
12045          if(stmt.doWhile.stmt)
12046             ProcessStatement(stmt.doWhile.stmt);
12047          break;
12048       }
12049       case forStmt:
12050       {
12051          Expression exp;
12052          if(stmt.forStmt.init)
12053             ProcessStatement(stmt.forStmt.init);
12054
12055          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
12056          {
12057             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
12058             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
12059             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
12060          }
12061
12062          if(stmt.forStmt.check)
12063             ProcessStatement(stmt.forStmt.check);
12064          if(stmt.forStmt.increment)
12065          {
12066             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
12067                ProcessExpressionType(exp);
12068          }
12069
12070          if(stmt.forStmt.stmt)
12071             ProcessStatement(stmt.forStmt.stmt);
12072          break;
12073       }
12074       case forEachStmt:
12075       {
12076          Identifier id = stmt.forEachStmt.id;
12077          OldList * exp = stmt.forEachStmt.exp;
12078          OldList * filter = stmt.forEachStmt.filter;
12079          Statement block = stmt.forEachStmt.stmt;
12080          char iteratorType[1024];
12081          Type source;
12082          Expression e;
12083          bool isBuiltin = exp && exp->last &&
12084             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12085               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12086          Expression arrayExp;
12087          const char * typeString = null;
12088          int builtinCount = 0;
12089
12090          for(e = exp ? exp->first : null; e; e = e.next)
12091          {
12092             if(!e.next)
12093             {
12094                FreeType(e.destType);
12095                e.destType = ProcessTypeString("Container", false);
12096             }
12097             if(!isBuiltin || e.next)
12098                ProcessExpressionType(e);
12099          }
12100
12101          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12102          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12103             eClass_IsDerived(source._class.registered, containerClass)))
12104          {
12105             Class _class = source ? source._class.registered : null;
12106             Symbol symbol;
12107             Expression expIt = null;
12108             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12109             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12110             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12111             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12112
12113             if(inCompiler)
12114             {
12115                stmt.type = compoundStmt;
12116
12117                stmt.compound.context = Context { };
12118                stmt.compound.context.parent = curContext;
12119                curContext = stmt.compound.context;
12120             }
12121
12122             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12123             {
12124                Class mapClass = eSystem_FindClass(privateModule, "Map");
12125                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12126                isCustomAVLTree = true;
12127                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12128                   isAVLTree = true;
12129                else */if(eClass_IsDerived(source._class.registered, mapClass))
12130                   isMap = true;
12131             }
12132             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12133             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12134             {
12135                Class listClass = eSystem_FindClass(privateModule, "List");
12136                isLinkList = true;
12137                isList = eClass_IsDerived(source._class.registered, listClass);
12138             }
12139
12140             if(inCompiler && isArray)
12141             {
12142                Declarator decl;
12143                OldList * specs = MkList();
12144                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12145                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12146                stmt.compound.declarations = MkListOne(
12147                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12148                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12149                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12150                      MkInitializerAssignment(MkExpBrackets(exp))))));
12151             }
12152             else if(isBuiltin)
12153             {
12154                Type type = null;
12155                char typeStringBuf[1024];
12156
12157                // TODO: Merge this code?
12158                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12159                if(((Expression)exp->last).type == castExp)
12160                {
12161                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12162                   if(typeName)
12163                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12164                }
12165
12166                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12167                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12168                   arrayExp.destType._class.registered.templateArgs)
12169                {
12170                   Class templateClass = arrayExp.destType._class.registered;
12171                   typeString = templateClass.templateArgs[2].dataTypeString;
12172                }
12173                else if(arrayExp.list)
12174                {
12175                   // Guess type from expressions in the array
12176                   Expression e;
12177                   for(e = arrayExp.list->first; e; e = e.next)
12178                   {
12179                      ProcessExpressionType(e);
12180                      if(e.expType)
12181                      {
12182                         if(!type) { type = e.expType; type.refCount++; }
12183                         else
12184                         {
12185                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12186                            if(!MatchTypeExpression(e, type, null, false, true))
12187                            {
12188                               FreeType(type);
12189                               type = e.expType;
12190                               e.expType = null;
12191
12192                               e = arrayExp.list->first;
12193                               ProcessExpressionType(e);
12194                               if(e.expType)
12195                               {
12196                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12197                                  if(!MatchTypeExpression(e, type, null, false, true))
12198                                  {
12199                                     FreeType(e.expType);
12200                                     e.expType = null;
12201                                     FreeType(type);
12202                                     type = null;
12203                                     break;
12204                                  }
12205                               }
12206                            }
12207                         }
12208                         if(e.expType)
12209                         {
12210                            FreeType(e.expType);
12211                            e.expType = null;
12212                         }
12213                      }
12214                   }
12215                   if(type)
12216                   {
12217                      typeStringBuf[0] = '\0';
12218                      PrintType(type, typeStringBuf, false, true);
12219                      typeString = typeStringBuf;
12220                      FreeType(type);
12221                   }
12222                }
12223                if(typeString)
12224                {
12225                   if(inCompiler)
12226                   {
12227                      OldList * initializers = MkList();
12228                      Declarator decl;
12229                      OldList * specs = MkList();
12230                      if(arrayExp.list)
12231                      {
12232                         Expression e;
12233
12234                         builtinCount = arrayExp.list->count;
12235                         type = ProcessTypeString(typeString, false);
12236                         while((e = arrayExp.list->first))
12237                         {
12238                            arrayExp.list->Remove(e);
12239                            e.destType = type;
12240                            type.refCount++;
12241                            ProcessExpressionType(e);
12242                            if(inCompiler)
12243                               ListAdd(initializers, MkInitializerAssignment(e));
12244                         }
12245                         FreeType(type);
12246                         delete arrayExp.list;
12247                      }
12248                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12249
12250                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12251                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12252
12253                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12254                         PlugDeclarator(
12255                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12256                            ), MkInitializerList(initializers)))));
12257                      FreeList(exp, FreeExpression);
12258                   }
12259                   else if(arrayExp.list)
12260                   {
12261                      Expression e;
12262                      type = ProcessTypeString(typeString, false);
12263                      for(e = arrayExp.list->first; e; e = e.next)
12264                      {
12265                         e.destType = type;
12266                         type.refCount++;
12267                         ProcessExpressionType(e);
12268                      }
12269                      FreeType(type);
12270                   }
12271                }
12272                else
12273                {
12274                   arrayExp.expType = ProcessTypeString("Container", false);
12275                   Compiler_Error($"Couldn't determine type of array elements\n");
12276                }
12277
12278                /*
12279                Declarator decl;
12280                OldList * specs = MkList();
12281
12282                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12283                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12284                stmt.compound.declarations = MkListOne(
12285                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12286                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12287                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12288                      MkInitializerAssignment(MkExpBrackets(exp))))));
12289                */
12290             }
12291             else if(inCompiler && isLinkList && !isList)
12292             {
12293                Declarator decl;
12294                OldList * specs = MkList();
12295                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12296                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12297                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12298                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12299                      MkInitializerAssignment(MkExpBrackets(exp))))));
12300             }
12301             /*else if(isCustomAVLTree)
12302             {
12303                Declarator decl;
12304                OldList * specs = MkList();
12305                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12306                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12307                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12308                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12309                      MkInitializerAssignment(MkExpBrackets(exp))))));
12310             }*/
12311             else if(inCompiler && _class.templateArgs)
12312             {
12313                if(isMap)
12314                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12315                else
12316                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12317
12318                stmt.compound.declarations = MkListOne(
12319                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12320                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12321                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12322             }
12323             if(inCompiler)
12324             {
12325                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12326
12327                if(block)
12328                {
12329                   // Reparent sub-contexts in this statement
12330                   switch(block.type)
12331                   {
12332                      case compoundStmt:
12333                         if(block.compound.context)
12334                            block.compound.context.parent = stmt.compound.context;
12335                         break;
12336                      case ifStmt:
12337                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12338                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12339                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12340                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12341                         break;
12342                      case switchStmt:
12343                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12344                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12345                         break;
12346                      case whileStmt:
12347                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12348                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12349                         break;
12350                      case doWhileStmt:
12351                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12352                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12353                         break;
12354                      case forStmt:
12355                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12356                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12357                         break;
12358                      case forEachStmt:
12359                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12360                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12361                         break;
12362                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12363                      case labeledStmt:
12364                      case caseStmt
12365                      case expressionStmt:
12366                      case gotoStmt:
12367                      case continueStmt:
12368                      case breakStmt
12369                      case returnStmt:
12370                      case asmStmt:
12371                      case badDeclarationStmt:
12372                      case fireWatchersStmt:
12373                      case stopWatchingStmt:
12374                      case watchStmt:
12375                      */
12376                   }
12377                }
12378
12379                if(filter)
12380                {
12381                   block = MkIfStmt(filter, block, null);
12382                }
12383                if(isArray)
12384                {
12385                   stmt.compound.statements = MkListOne(MkForStmt(
12386                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12387                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12388                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12389                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12390                      block));
12391                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12392                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12393                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12394                }
12395                else if(isBuiltin)
12396                {
12397                   char count[128];
12398                   //OldList * specs = MkList();
12399                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12400
12401                   sprintf(count, "%d", builtinCount);
12402
12403                   stmt.compound.statements = MkListOne(MkForStmt(
12404                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12405                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12406                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12407                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12408                      block));
12409
12410                   /*
12411                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12412                   stmt.compound.statements = MkListOne(MkForStmt(
12413                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12414                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12415                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12416                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12417                      block));
12418                  */
12419                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12420                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12421                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12422                }
12423                else if(isLinkList && !isList)
12424                {
12425                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12426                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12427                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12428                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12429                   {
12430                      stmt.compound.statements = MkListOne(MkForStmt(
12431                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12432                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12433                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12434                         block));
12435                   }
12436                   else
12437                   {
12438                      OldList * specs = MkList();
12439                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12440                      stmt.compound.statements = MkListOne(MkForStmt(
12441                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12442                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12443                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12444                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12445                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12446                         block));
12447                   }
12448                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12449                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12450                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12451                }
12452                /*else if(isCustomAVLTree)
12453                {
12454                   stmt.compound.statements = MkListOne(MkForStmt(
12455                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12456                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12457                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12458                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12459                      block));
12460
12461                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12462                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12463                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12464                }*/
12465                else
12466                {
12467                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12468                      MkIdentifier("Next")), null)), block));
12469                }
12470                ProcessExpressionType(expIt);
12471                if(stmt.compound.declarations->first)
12472                   ProcessDeclaration(stmt.compound.declarations->first, true);
12473
12474                if(symbol)
12475                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12476
12477                ProcessStatement(stmt);
12478             }
12479             else
12480                ProcessStatement(stmt.forEachStmt.stmt);
12481             if(inCompiler)
12482                curContext = stmt.compound.context.parent;
12483             break;
12484          }
12485          else
12486          {
12487             Compiler_Error($"Expression is not a container\n");
12488          }
12489          break;
12490       }
12491       case gotoStmt:
12492          break;
12493       case continueStmt:
12494          break;
12495       case breakStmt:
12496          break;
12497       case returnStmt:
12498       {
12499          Expression exp;
12500          if(stmt.expressions)
12501          {
12502             for(exp = stmt.expressions->first; exp; exp = exp.next)
12503             {
12504                if(!exp.next)
12505                {
12506                   if(curFunction && !curFunction.type)
12507                      curFunction.type = ProcessType(
12508                         curFunction.specifiers, curFunction.declarator);
12509                   FreeType(exp.destType);
12510                   // TODO: current property if not compiling
12511                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12512                   if(exp.destType) exp.destType.refCount++;
12513                }
12514                ProcessExpressionType(exp);
12515             }
12516          }
12517          break;
12518       }
12519       case badDeclarationStmt:
12520       {
12521          ProcessDeclaration(stmt.decl, true);
12522          break;
12523       }
12524       case asmStmt:
12525       {
12526          AsmField field;
12527          if(stmt.asmStmt.inputFields)
12528          {
12529             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12530                if(field.expression)
12531                   ProcessExpressionType(field.expression);
12532          }
12533          if(stmt.asmStmt.outputFields)
12534          {
12535             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12536                if(field.expression)
12537                   ProcessExpressionType(field.expression);
12538          }
12539          if(stmt.asmStmt.clobberedFields)
12540          {
12541             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12542             {
12543                if(field.expression)
12544                   ProcessExpressionType(field.expression);
12545             }
12546          }
12547          break;
12548       }
12549       case watchStmt:
12550       {
12551          PropertyWatch propWatch;
12552          OldList * watches = stmt._watch.watches;
12553          Expression object = stmt._watch.object;
12554          Expression watcher = stmt._watch.watcher;
12555          if(watcher)
12556             ProcessExpressionType(watcher);
12557          if(object)
12558             ProcessExpressionType(object);
12559
12560          if(inCompiler)
12561          {
12562             if(watcher || thisClass)
12563             {
12564                External external = curExternal;
12565                Context context = curContext;
12566
12567                stmt.type = expressionStmt;
12568                stmt.expressions = MkList();
12569
12570                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12571                {
12572                   ClassFunction func;
12573                   char watcherName[1024];
12574                   Class watcherClass = watcher ?
12575                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12576                   External createdExternal;
12577
12578                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12579                   if(propWatch.deleteWatch)
12580                      strcat(watcherName, "_delete");
12581                   else
12582                   {
12583                      Identifier propID;
12584                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12585                      {
12586                         strcat(watcherName, "_");
12587                         strcat(watcherName, propID.string);
12588                      }
12589                   }
12590
12591                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12592                   {
12593                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12594                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12595                      ProcessClassFunctionBody(func, propWatch.compound);
12596                      propWatch.compound = null;
12597
12598                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12599
12600                      FreeClassFunction(func);
12601
12602                      curExternal = createdExternal;
12603                      ProcessFunction(createdExternal.function);
12604
12605                      if(propWatch.deleteWatch)
12606                      {
12607                         OldList * args = MkList();
12608                         ListAdd(args, CopyExpression(object));
12609                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12610                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12611                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12612                      }
12613                      else
12614                      {
12615                         Class _class = object.expType._class.registered;
12616                         Identifier propID;
12617
12618                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12619                         {
12620                            char propName[1024];
12621                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12622                            if(prop)
12623                            {
12624                               char getName[1024], setName[1024];
12625                               OldList * args = MkList();
12626
12627                               DeclareProperty(createdExternal, prop, setName, getName);
12628
12629                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12630                               strcpy(propName, "__ecereProp_");
12631                               FullClassNameCat(propName, prop._class.fullName, false);
12632                               strcat(propName, "_");
12633                               FullClassNameCat(propName, prop.name, true);
12634
12635                               ListAdd(args, CopyExpression(object));
12636                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12637                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12638                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12639
12640                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12641
12642                               external.CreateUniqueEdge(createdExternal, true);
12643                            }
12644                            else
12645                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12646                         }
12647                      }
12648                   }
12649                   else
12650                      Compiler_Error($"Invalid watched object\n");
12651                }
12652
12653                curExternal = external;
12654                curContext = context;
12655
12656                if(watcher)
12657                   FreeExpression(watcher);
12658                if(object)
12659                   FreeExpression(object);
12660                FreeList(watches, FreePropertyWatch);
12661             }
12662             else
12663                Compiler_Error($"No observer specified and not inside a class\n");
12664          }
12665          else
12666          {
12667             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12668             {
12669                ProcessStatement(propWatch.compound);
12670             }
12671
12672          }
12673          break;
12674       }
12675       case fireWatchersStmt:
12676       {
12677          OldList * watches = stmt._watch.watches;
12678          Expression object = stmt._watch.object;
12679          Class _class;
12680          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12681          // printf("%X\n", watches);
12682          // printf("%X\n", stmt._watch.watches);
12683          if(object)
12684             ProcessExpressionType(object);
12685
12686          if(inCompiler)
12687          {
12688             _class = object ?
12689                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12690
12691             if(_class)
12692             {
12693                Identifier propID;
12694
12695                stmt.type = expressionStmt;
12696                stmt.expressions = MkList();
12697
12698                // Check if we're inside a property set
12699                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12700                {
12701                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12702                }
12703                else if(!watches)
12704                {
12705                   //Compiler_Error($"No property specified and not inside a property set\n");
12706                }
12707                if(watches)
12708                {
12709                   for(propID = watches->first; propID; propID = propID.next)
12710                   {
12711                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12712                      if(prop)
12713                      {
12714                         CreateFireWatcher(prop, object, stmt);
12715                      }
12716                      else
12717                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12718                   }
12719                }
12720                else
12721                {
12722                   // Fire all properties!
12723                   Property prop;
12724                   Class base;
12725                   for(base = _class; base; base = base.base)
12726                   {
12727                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12728                      {
12729                         if(prop.isProperty && prop.isWatchable)
12730                         {
12731                            CreateFireWatcher(prop, object, stmt);
12732                         }
12733                      }
12734                   }
12735                }
12736
12737                if(object)
12738                   FreeExpression(object);
12739                FreeList(watches, FreeIdentifier);
12740             }
12741             else
12742                Compiler_Error($"Invalid object specified and not inside a class\n");
12743          }
12744          break;
12745       }
12746       case stopWatchingStmt:
12747       {
12748          OldList * watches = stmt._watch.watches;
12749          Expression object = stmt._watch.object;
12750          Expression watcher = stmt._watch.watcher;
12751          Class _class;
12752          if(object)
12753             ProcessExpressionType(object);
12754          if(watcher)
12755             ProcessExpressionType(watcher);
12756          if(inCompiler)
12757          {
12758             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12759
12760             if(watcher || thisClass)
12761             {
12762                if(_class)
12763                {
12764                   Identifier propID;
12765
12766                   stmt.type = expressionStmt;
12767                   stmt.expressions = MkList();
12768
12769                   if(!watches)
12770                   {
12771                      OldList * args;
12772                      // eInstance_StopWatching(object, null, watcher);
12773                      args = MkList();
12774                      ListAdd(args, CopyExpression(object));
12775                      ListAdd(args, MkExpConstant("0"));
12776                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12777                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12778                   }
12779                   else
12780                   {
12781                      for(propID = watches->first; propID; propID = propID.next)
12782                      {
12783                         char propName[1024];
12784                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12785                         if(prop)
12786                         {
12787                            char getName[1024], setName[1024];
12788                            OldList * args = MkList();
12789
12790                            DeclareProperty(curExternal, prop, setName, getName);
12791
12792                            // eInstance_StopWatching(object, prop, watcher);
12793                            strcpy(propName, "__ecereProp_");
12794                            FullClassNameCat(propName, prop._class.fullName, false);
12795                            strcat(propName, "_");
12796                            FullClassNameCat(propName, prop.name, true);
12797
12798                            ListAdd(args, CopyExpression(object));
12799                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12800                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12801                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12802                         }
12803                         else
12804                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12805                      }
12806                   }
12807
12808                   if(object)
12809                      FreeExpression(object);
12810                   if(watcher)
12811                      FreeExpression(watcher);
12812                   FreeList(watches, FreeIdentifier);
12813                }
12814                else
12815                   Compiler_Error($"Invalid object specified and not inside a class\n");
12816             }
12817             else
12818                Compiler_Error($"No observer specified and not inside a class\n");
12819          }
12820          break;
12821       }
12822    }
12823 }
12824
12825 static void ProcessFunction(FunctionDefinition function)
12826 {
12827    Identifier id = GetDeclId(function.declarator);
12828    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12829    Type type = symbol ? symbol.type : null;
12830    Class oldThisClass = thisClass;
12831    Context oldTopContext = topContext;
12832
12833    yylloc = function.loc;
12834    // Process thisClass
12835
12836    if(type && type.thisClass)
12837    {
12838       Symbol classSym = type.thisClass;
12839       Class _class = type.thisClass.registered;
12840       char className[1024];
12841       char structName[1024];
12842       Declarator funcDecl;
12843       Symbol thisSymbol;
12844
12845       bool typedObject = false;
12846
12847       if(_class && !_class.base)
12848       {
12849          _class = currentClass;
12850          if(_class && !_class.symbol)
12851             _class.symbol = FindClass(_class.fullName);
12852          classSym = _class ? _class.symbol : null;
12853          typedObject = true;
12854       }
12855
12856       thisClass = _class;
12857
12858       if(inCompiler && _class)
12859       {
12860          if(type.kind == functionType)
12861          {
12862             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12863             {
12864                //TypeName param = symbol.type.params.first;
12865                Type param = symbol.type.params.first;
12866                symbol.type.params.Remove(param);
12867                //FreeTypeName(param);
12868                FreeType(param);
12869             }
12870             if(type.classObjectType != classPointer)
12871             {
12872                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12873                symbol.type.staticMethod = true;
12874                symbol.type.thisClass = null;
12875
12876                // HIGH DANGER: VERIFYING THIS...
12877                symbol.type.extraParam = false;
12878             }
12879          }
12880
12881          strcpy(className, "__ecereClass_");
12882          FullClassNameCat(className, _class.fullName, true);
12883
12884          structName[0] = 0;
12885          FullClassNameCat(structName, _class.fullName, false);
12886
12887          // [class] this
12888          funcDecl = GetFuncDecl(function.declarator);
12889          if(funcDecl)
12890          {
12891             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12892             {
12893                TypeName param = funcDecl.function.parameters->first;
12894                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12895                {
12896                   funcDecl.function.parameters->Remove(param);
12897                   FreeTypeName(param);
12898                }
12899             }
12900
12901             if(!function.propertyNoThis)
12902             {
12903                TypeName thisParam = null;
12904
12905                if(type.classObjectType != classPointer)
12906                {
12907                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12908                   if(!funcDecl.function.parameters)
12909                      funcDecl.function.parameters = MkList();
12910                   funcDecl.function.parameters->Insert(null, thisParam);
12911                }
12912
12913                if(typedObject)
12914                {
12915                   if(type.classObjectType != classPointer)
12916                   {
12917                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
12918                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
12919                   }
12920
12921                   thisParam = TypeName
12922                   {
12923                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
12924                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
12925                   };
12926                   DeclareStruct(curExternal, "ecere::com::Class", false, true);
12927                   funcDecl.function.parameters->Insert(null, thisParam);
12928                }
12929             }
12930          }
12931
12932          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12933          {
12934             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12935             funcDecl = GetFuncDecl(initDecl.declarator);
12936             if(funcDecl)
12937             {
12938                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12939                {
12940                   TypeName param = funcDecl.function.parameters->first;
12941                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12942                   {
12943                      funcDecl.function.parameters->Remove(param);
12944                      FreeTypeName(param);
12945                   }
12946                }
12947
12948                if(type.classObjectType != classPointer)
12949                {
12950                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12951                   {
12952                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12953
12954                      if(!funcDecl.function.parameters)
12955                         funcDecl.function.parameters = MkList();
12956                      funcDecl.function.parameters->Insert(null, thisParam);
12957                   }
12958                }
12959             }
12960          }
12961       }
12962
12963       // Add this to the context
12964       if(function.body)
12965       {
12966          if(type.classObjectType != classPointer)
12967          {
12968             thisSymbol = Symbol
12969             {
12970                string = CopyString("this");
12971                type = classSym ? MkClassType(classSym.string) : null;
12972             };
12973             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
12974
12975             if(typedObject && thisSymbol.type)
12976             {
12977                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
12978                thisSymbol.type.byReference = type.byReference;
12979                thisSymbol.type.typedByReference = type.byReference;
12980             }
12981          }
12982       }
12983
12984       // Pointer to class data
12985       if(inCompiler && _class && _class.type == normalClass && type.classObjectType != classPointer)
12986       {
12987          DataMember member = null;
12988          {
12989             Class base;
12990             for(base = _class; base && base.type != systemClass; base = base.next)
12991             {
12992                for(member = base.membersAndProperties.first; member; member = member.next)
12993                   if(!member.isProperty)
12994                      break;
12995                if(member)
12996                   break;
12997             }
12998          }
12999          for(member = _class.membersAndProperties.first; member; member = member.next)
13000             if(!member.isProperty)
13001                break;
13002          if(member)
13003          {
13004             char pointerName[1024];
13005
13006             Declaration decl;
13007             Initializer initializer;
13008             Expression exp, bytePtr;
13009
13010             strcpy(pointerName, "__ecerePointer_");
13011             FullClassNameCat(pointerName, _class.fullName, false);
13012             {
13013                char className[1024];
13014                strcpy(className, "__ecereClass_");
13015                FullClassNameCat(className, classSym.string, true);
13016
13017                DeclareClass(curExternal, classSym, className);
13018             }
13019
13020             // ((byte *) this)
13021             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
13022
13023             if(_class.fixed)
13024             {
13025                Expression e;
13026                if(_class.offset && _class.offset == _class.base.structSize)
13027                {
13028                   e = MkExpClassSize(MkSpecifierName(_class.base.fullName));
13029                   ProcessExpressionType(e);
13030                }
13031                else
13032                {
13033                   char string[256];
13034                   sprintf(string, "%d", _class.offset);  // Need Bootstrap Fix
13035                   e = MkExpConstant(string);
13036                }
13037                exp = QBrackets(MkExpOp(bytePtr, '+', e));
13038             }
13039             else
13040             {
13041                // ([bytePtr] + [className]->offset)
13042                exp = QBrackets(MkExpOp(bytePtr, '+',
13043                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
13044             }
13045
13046             // (this ? [exp] : 0)
13047             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
13048             exp.expType = Type
13049             {
13050                refCount = 1;
13051                kind = pointerType;
13052                type = Type { refCount = 1, kind = voidType };
13053             };
13054
13055             if(function.body)
13056             {
13057                yylloc = function.body.loc;
13058                // ([structName] *) [exp]
13059                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13060                initializer = MkInitializerAssignment(
13061                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13062
13063                // [structName] * [pointerName] = [initializer];
13064                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13065
13066                {
13067                   Context prevContext = curContext;
13068                   OldList * list;
13069                   curContext = function.body.compound.context;
13070
13071                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13072                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13073                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13074
13075                   curContext = prevContext;
13076                }
13077
13078                // WHY?
13079                decl.symbol = null;
13080
13081                if(!function.body.compound.declarations)
13082                   function.body.compound.declarations = MkList();
13083                function.body.compound.declarations->Insert(null, decl);
13084             }
13085          }
13086       }
13087
13088
13089       // Loop through the function and replace undeclared identifiers
13090       // which are a member of the class (methods, properties or data)
13091       // by "this.[member]"
13092    }
13093    else
13094       thisClass = null;
13095
13096    if(id)
13097    {
13098       FreeSpecifier(id._class);
13099       id._class = null;
13100
13101       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13102       {
13103          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13104          id = GetDeclId(initDecl.declarator);
13105
13106          FreeSpecifier(id._class);
13107          id._class = null;
13108       }
13109    }
13110    if(function.body)
13111       topContext = function.body.compound.context;
13112    {
13113       FunctionDefinition oldFunction = curFunction;
13114       curFunction = function;
13115       if(function.body)
13116          ProcessStatement(function.body);
13117
13118       // If this is a property set and no firewatchers has been done yet, add one here
13119       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13120       {
13121          Statement prevCompound = curCompound;
13122          Context prevContext = curContext;
13123
13124          Statement fireWatchers = MkFireWatchersStmt(null, null);
13125          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13126          ListAdd(function.body.compound.statements, fireWatchers);
13127
13128          curCompound = function.body;
13129          curContext = function.body.compound.context;
13130
13131          ProcessStatement(fireWatchers);
13132
13133          curContext = prevContext;
13134          curCompound = prevCompound;
13135
13136       }
13137
13138       curFunction = oldFunction;
13139    }
13140
13141    if(function.declarator)
13142    {
13143       ProcessDeclarator(function.declarator, true);
13144    }
13145
13146    topContext = oldTopContext;
13147    thisClass = oldThisClass;
13148 }
13149
13150 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13151 static void ProcessClass(OldList definitions, Symbol symbol)
13152 {
13153    ClassDef def;
13154    External external = curExternal;
13155    Class regClass = symbol ? symbol.registered : null;
13156
13157    // Process all functions
13158    for(def = definitions.first; def; def = def.next)
13159    {
13160       if(def.type == functionClassDef)
13161       {
13162          if(def.function.declarator)
13163             curExternal = def.function.declarator.symbol.pointerExternal;
13164          else
13165             curExternal = external;
13166
13167          ProcessFunction((FunctionDefinition)def.function);
13168       }
13169       else if(def.type == declarationClassDef)
13170       {
13171          if(def.decl.type == instDeclaration)
13172          {
13173             thisClass = regClass;
13174             ProcessInstantiationType(def.decl.inst);
13175             thisClass = null;
13176          }
13177          // Testing this
13178          else
13179          {
13180             Class backThisClass = thisClass;
13181             if(regClass) thisClass = regClass;
13182             ProcessDeclaration(def.decl, symbol ? true : false);
13183             thisClass = backThisClass;
13184          }
13185       }
13186       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13187       {
13188          MemberInit defProperty;
13189
13190          // Add this to the context
13191          Symbol thisSymbol = Symbol
13192          {
13193             string = CopyString("this");
13194             type = regClass ? MkClassType(regClass.fullName) : null;
13195          };
13196          globalContext.symbols.Add((BTNode)thisSymbol);
13197
13198          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13199          {
13200             thisClass = regClass;
13201             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13202             thisClass = null;
13203          }
13204
13205          globalContext.symbols.Remove((BTNode)thisSymbol);
13206          FreeSymbol(thisSymbol);
13207       }
13208       else if(def.type == propertyClassDef && def.propertyDef)
13209       {
13210          PropertyDef prop = def.propertyDef;
13211
13212          // Add this to the context
13213          thisClass = regClass;
13214          if(prop.setStmt)
13215          {
13216             if(regClass)
13217             {
13218                Symbol thisSymbol
13219                {
13220                   string = CopyString("this");
13221                   type = MkClassType(regClass.fullName);
13222                };
13223                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13224             }
13225
13226             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13227             ProcessStatement(prop.setStmt);
13228          }
13229          if(prop.getStmt)
13230          {
13231             if(regClass)
13232             {
13233                Symbol thisSymbol
13234                {
13235                   string = CopyString("this");
13236                   type = MkClassType(regClass.fullName);
13237                };
13238                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13239             }
13240
13241             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13242             ProcessStatement(prop.getStmt);
13243          }
13244          if(prop.issetStmt)
13245          {
13246             if(regClass)
13247             {
13248                Symbol thisSymbol
13249                {
13250                   string = CopyString("this");
13251                   type = MkClassType(regClass.fullName);
13252                };
13253                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13254             }
13255
13256             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13257             ProcessStatement(prop.issetStmt);
13258          }
13259
13260          thisClass = null;
13261       }
13262       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13263       {
13264          PropertyWatch propertyWatch = def.propertyWatch;
13265
13266          thisClass = regClass;
13267          if(propertyWatch.compound)
13268          {
13269             Symbol thisSymbol
13270             {
13271                string = CopyString("this");
13272                type = regClass ? MkClassType(regClass.fullName) : null;
13273             };
13274
13275             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13276
13277             curExternal = null;
13278             ProcessStatement(propertyWatch.compound);
13279          }
13280          thisClass = null;
13281       }
13282    }
13283 }
13284
13285 void DeclareFunctionUtil(External neededBy, const String s)
13286 {
13287    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13288    if(function)
13289    {
13290       char name[1024];
13291       name[0] = 0;
13292       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13293          strcpy(name, "__ecereFunction_");
13294       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13295       DeclareFunction(neededBy, function, name);
13296    }
13297    else if(neededBy)
13298       FindSymbol(s, globalContext, globalContext, false, false);
13299 }
13300
13301 void ComputeDataTypes()
13302 {
13303    External external;
13304
13305    currentClass = null;
13306
13307    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13308
13309    DeclareStruct(null, "ecere::com::Class", false, true);
13310    DeclareStruct(null, "ecere::com::Instance", false, true);
13311    DeclareStruct(null, "ecere::com::Property", false, true);
13312    DeclareStruct(null, "ecere::com::DataMember", false, true);
13313    DeclareStruct(null, "ecere::com::Method", false, true);
13314    DeclareStruct(null, "ecere::com::SerialBuffer", false, true);
13315    DeclareStruct(null, "ecere::com::ClassTemplateArgument", false, true);
13316
13317    DeclareFunctionUtil(null, "eSystem_New");
13318    DeclareFunctionUtil(null, "eSystem_New0");
13319    DeclareFunctionUtil(null, "eSystem_Renew");
13320    DeclareFunctionUtil(null, "eSystem_Renew0");
13321    DeclareFunctionUtil(null, "eSystem_Delete");
13322    DeclareFunctionUtil(null, "eClass_GetProperty");
13323    DeclareFunctionUtil(null, "eClass_SetProperty");
13324    DeclareFunctionUtil(null, "eInstance_FireSelfWatchers");
13325    DeclareFunctionUtil(null, "eInstance_SetMethod");
13326    DeclareFunctionUtil(null, "eInstance_IncRef");
13327    DeclareFunctionUtil(null, "eInstance_StopWatching");
13328    DeclareFunctionUtil(null, "eInstance_Watch");
13329    DeclareFunctionUtil(null, "eInstance_FireWatchers");
13330
13331    for(external = ast->first; external; external = external.next)
13332    {
13333       afterExternal = curExternal = external;
13334       if(external.type == functionExternal)
13335       {
13336          if(memoryGuard)
13337          {
13338             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13339             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13340          }
13341
13342          currentClass = external.function._class;
13343          ProcessFunction(external.function);
13344       }
13345       // There shouldn't be any _class member access here anyways...
13346       else if(external.type == declarationExternal)
13347       {
13348          if(memoryGuard && external.declaration && external.declaration.type == instDeclaration)
13349          {
13350             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13351             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13352          }
13353
13354          currentClass = null;
13355          if(external.declaration)
13356             ProcessDeclaration(external.declaration, true);
13357       }
13358       else if(external.type == classExternal)
13359       {
13360          ClassDefinition _class = external._class;
13361          currentClass = external.symbol.registered;
13362          if(memoryGuard)
13363          {
13364             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13365             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13366          }
13367          if(_class.definitions)
13368          {
13369             ProcessClass(_class.definitions, _class.symbol);
13370          }
13371          if(inCompiler)
13372          {
13373             // Free class data...
13374             ast->Remove(external);
13375             delete external;
13376          }
13377       }
13378       else if(external.type == nameSpaceExternal)
13379       {
13380          thisNameSpace = external.id.string;
13381       }
13382    }
13383    currentClass = null;
13384    thisNameSpace = null;
13385    curExternal = null;
13386 }