compiler/libec: Improvements to units operations
[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             if(!ctx) break;   // This happened opening old mapTileCache.ec from archives?
125             symbol = (Symbol)ctx.symbols.FindString(id.string);
126             if(symbol) break;
127          }
128       }
129
130       // If it is not, check if it is a member of the _class
131       if(!symbol && ((!id._class || (id._class.name && !strcmp(id._class.name, "property"))) || (id.classSym && eClass_IsDerived(_class, id.classSym.registered))))
132       {
133          Property prop = eClass_FindProperty(_class, id.string, privateModule);
134          Method method = null;
135          DataMember member = null;
136          ClassProperty classProp = null;
137          if(!prop)
138          {
139             method = eClass_FindMethod(_class, id.string, privateModule);
140          }
141          if(!prop && !method)
142             member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
143          if(!prop && !method && !member)
144          {
145             classProp = eClass_FindClassProperty(_class, id.string);
146          }
147          if(prop || method || member || classProp)
148          {
149             // Replace by this.[member]
150             exp.type = memberExp;
151             exp.member.member = id;
152             exp.member.memberType = unresolvedMember;
153             exp.member.exp = QMkExpId("this");
154             //exp.member.exp.loc = exp.loc;
155             exp.addedThis = true;
156          }
157          else if(_class && _class.templateParams.first)
158          {
159             Class sClass;
160             for(sClass = _class; sClass; sClass = sClass.base)
161             {
162                if(sClass.templateParams.first)
163                {
164                   ClassTemplateParameter param;
165                   for(param = sClass.templateParams.first; param; param = param.next)
166                   {
167                      if(param.type == expression && !strcmp(param.name, id.string))
168                      {
169                         Expression argExp = GetTemplateArgExpByName(param.name, _class, TemplateParameterType::expression);
170
171                         if(argExp)
172                         {
173                            Declarator decl;
174                            OldList * specs = MkList();
175
176                            FreeIdentifier(exp.member.member);
177
178                            ProcessExpressionType(argExp);
179
180                            decl = SpecDeclFromString(param.dataTypeString, specs, null);
181
182                            exp.expType = ProcessType(specs, decl);
183
184                            // *[expType] *[argExp]
185                            exp.type = bracketsExp;
186                            exp.list = MkListOne(MkExpOp(null, '*',
187                               MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpOp(null, '&', argExp))));
188                         }
189                      }
190                   }
191                }
192             }
193          }
194       }
195    }
196 }
197
198 ////////////////////////////////////////////////////////////////////////
199 // PRINTING ////////////////////////////////////////////////////////////
200 ////////////////////////////////////////////////////////////////////////
201
202 public char * PrintInt(int64 result)
203 {
204    char temp[100];
205    if(result > MAXINT)
206       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
207    else
208       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
209    if(result > MAXINT || result < MININT)
210       strcat(temp, "LL");
211    return CopyString(temp);
212 }
213
214 public char * PrintUInt(uint64 result)
215 {
216    char temp[100];
217    if(result > MAXDWORD)
218       sprintf(temp, FORMAT64HEXLL /*"0x%I64X"*/, result);
219    else if(result > MAXINT)
220       sprintf(temp, FORMAT64HEX /*"0x%I64X"*/, result);
221    else
222       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
223    return CopyString(temp);
224 }
225
226 public char *  PrintInt64(int64 result)
227 {
228    char temp[100];
229    if(result > MAXINT || result < MININT)
230       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
231    else
232       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
233    return CopyString(temp);
234 }
235
236 public char * PrintUInt64(uint64 result)
237 {
238    char temp[100];
239    if(result > MAXDWORD)
240       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
241    else if(result > MAXINT)
242       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
243    else
244       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
245    return CopyString(temp);
246 }
247
248 public char * PrintHexUInt(uint64 result)
249 {
250    char temp[100];
251    if(result > MAXDWORD)
252       sprintf(temp, FORMAT64HEX /*"0x%I64xLL"*/, result);
253    else
254       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
255    if(result > MAXDWORD)
256       strcat(temp, "LL");
257    return CopyString(temp);
258 }
259
260 public char * PrintHexUInt64(uint64 result)
261 {
262    char temp[100];
263    if(result > MAXDWORD)
264       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
265    else
266       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
267    return CopyString(temp);
268 }
269
270 public char * PrintShort(short result)
271 {
272    char temp[100];
273    sprintf(temp, "%d", (unsigned short)result);
274    return CopyString(temp);
275 }
276
277 public char * PrintUShort(unsigned short result)
278 {
279    char temp[100];
280    if(result > 32767)
281       sprintf(temp, "0x%X", (int)result);
282    else
283       sprintf(temp, "%d", (int)result);
284    return CopyString(temp);
285 }
286
287 public char * PrintChar(char result)
288 {
289    char temp[100];
290    if(result > 0 && isprint(result))
291       sprintf(temp, "'%c'", result);
292    else if(result < 0)
293       sprintf(temp, "%d", (int)result);
294    else
295       //sprintf(temp, "%#X", result);
296       sprintf(temp, "0x%X", (unsigned char)result);
297    return CopyString(temp);
298 }
299
300 public char * PrintUChar(unsigned char result)
301 {
302    char temp[100];
303    sprintf(temp, "0x%X", result);
304    return CopyString(temp);
305 }
306
307 public char * PrintFloat(float result)
308 {
309    char temp[350];
310    if(result.isInf)
311    {
312       if(result.signBit)
313          strcpy(temp, "-inf");
314       else
315          strcpy(temp, "inf");
316    }
317    else if(result.isNan)
318    {
319       if(result.signBit)
320          strcpy(temp, "-nan");
321       else
322          strcpy(temp, "nan");
323    }
324    else
325       sprintf(temp, "%.16ff", result);
326    return CopyString(temp);
327 }
328
329 public char * PrintDouble(double result)
330 {
331    char temp[350];
332    if(result.isInf)
333    {
334       if(result.signBit)
335          strcpy(temp, "-inf");
336       else
337          strcpy(temp, "inf");
338    }
339    else if(result.isNan)
340    {
341       if(result.signBit)
342          strcpy(temp, "-nan");
343       else
344          strcpy(temp, "nan");
345    }
346    else
347       sprintf(temp, "%.16f", result);
348    return CopyString(temp);
349 }
350
351 ////////////////////////////////////////////////////////////////////////
352 ////////////////////////////////////////////////////////////////////////
353
354 //public Operand GetOperand(Expression exp);
355
356 #define GETVALUE(name, t) \
357    public bool GetOp##name(Operand op2, t * value2) \
358    {                                                        \
359       if(op2.kind == intType && op2.type.isSigned) *value2 = (t) op2.i; \
360       else if(op2.kind == intType) *value2 = (t) op2.ui;                 \
361       else if(op2.kind == int64Type && op2.type.isSigned) *value2 = (t) op2.i64; \
362       else if(op2.kind == int64Type) *value2 = (t) op2.ui64;                 \
363       else if(op2.kind == intSizeType && op2.type.isSigned) *value2 = (t) op2.i64; \
364       else if(op2.kind == intSizeType) *value2 = (t) op2.ui64; \
365       else if(op2.kind == intPtrType && op2.type.isSigned) *value2 = (t) op2.i64; \
366       else if(op2.kind == intPtrType) *value2 = (t) op2.ui64;                 \
367       else if(op2.kind == shortType && op2.type.isSigned) *value2 = (t) op2.s;   \
368       else if(op2.kind == shortType) *value2 = (t) op2.us;                        \
369       else if(op2.kind == charType && op2.type.isSigned) *value2 = (t) op2.c;    \
370       else if(op2.kind == _BoolType || op2.kind == charType) *value2 = (t) op2.uc; \
371       else if(op2.kind == floatType) *value2 = (t) op2.f;                         \
372       else if(op2.kind == doubleType) *value2 = (t) op2.d;                        \
373       else if(op2.kind == pointerType) *value2 = (t) op2.ui64;                    \
374       else                                                                          \
375          return false;                                                              \
376       return true;                                                                  \
377    } \
378    public bool Get##name(Expression exp, t * value2) \
379    {                                                        \
380       Operand op2 = GetOperand(exp);                        \
381       return GetOp##name(op2, value2); \
382    }
383
384 // To help the debugger currently not preprocessing...
385 #define HELP(x) x
386
387 GETVALUE(Int, HELP(int));
388 GETVALUE(UInt, HELP(unsigned int));
389 GETVALUE(Int64, HELP(int64));
390 GETVALUE(UInt64, HELP(uint64));
391 GETVALUE(IntPtr, HELP(intptr));
392 GETVALUE(UIntPtr, HELP(uintptr));
393 GETVALUE(IntSize, HELP(intsize));
394 GETVALUE(UIntSize, HELP(uintsize));
395 GETVALUE(Short, HELP(short));
396 GETVALUE(UShort, HELP(unsigned short));
397 GETVALUE(Char, HELP(char));
398 GETVALUE(UChar, HELP(unsigned char));
399 GETVALUE(Float, HELP(float));
400 GETVALUE(Double, HELP(double));
401
402 void ComputeExpression(Expression exp);
403
404 void ComputeClassMembers(Class _class, bool isMember)
405 {
406    DataMember member = isMember ? (DataMember) _class : null;
407    Context context = isMember ? null : SetupTemplatesContext(_class);
408    if(member || ((_class.type == bitClass || _class.type == normalClass || _class.type == structClass || _class.type == noHeadClass) &&
409                  (_class.type == bitClass || (!_class.structSize || _class.structSize == _class.offset)) && _class.computeSize))
410    {
411       int unionMemberOffset = 0;
412       int bitFields = 0;
413
414       /*
415       if(!member && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass) && _class.memberOffset && _class.memberOffset > _class.base.structSize)
416          _class.memberOffset = (_class.base && _class.base.type != systemClass) ? _class.base.structSize : 0;
417       */
418
419       if(member)
420       {
421          member.memberOffset = 0;
422          if(targetBits < sizeof(void *) * 8)
423             member.structAlignment = 0;
424       }
425       else if(targetBits < sizeof(void *) * 8)
426          _class.structAlignment = 0;
427
428       // Confusion here: non struct classes seem to have their memberOffset restart at 0 at each hierarchy level
429       if(!member && ((_class.type == normalClass || _class.type == noHeadClass) || (_class.type == structClass && _class.memberOffset && _class.memberOffset > _class.base.structSize)))
430          _class.memberOffset = (_class.base && _class.type == structClass) ? _class.base.structSize : 0;
431
432       if(!member && _class.destructionWatchOffset)
433          _class.memberOffset += sizeof(OldList);
434
435       // To avoid reentrancy...
436       //_class.structSize = -1;
437
438       {
439          DataMember dataMember;
440          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
441          {
442             if(!dataMember.isProperty)
443             {
444                if(dataMember.type == normalMember && dataMember.dataTypeString && !dataMember.dataType)
445                {
446                   dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
447                   /*if(!dataMember.dataType)
448                      dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
449                      */
450                }
451             }
452          }
453       }
454
455       {
456          DataMember dataMember;
457          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
458          {
459             if(!dataMember.isProperty && (dataMember.type != normalMember || dataMember.dataTypeString))
460             {
461                if(!isMember && _class.type == bitClass && dataMember.dataType)
462                {
463                   BitMember bitMember = (BitMember) dataMember;
464                   uint64 mask = 0;
465                   int d;
466
467                   ComputeTypeSize(dataMember.dataType);
468
469                   if(bitMember.pos == -1) bitMember.pos = _class.memberOffset;
470                   if(!bitMember.size) bitMember.size = dataMember.dataType.size * 8;
471
472                   _class.memberOffset = bitMember.pos + bitMember.size;
473                   for(d = 0; d<bitMember.size; d++)
474                   {
475                      if(d)
476                         mask <<= 1;
477                      mask |= 1;
478                   }
479                   bitMember.mask = mask << bitMember.pos;
480                }
481                else if(dataMember.type == normalMember && dataMember.dataType)
482                {
483                   int size;
484                   int alignment = 0;
485
486                   // Prevent infinite recursion
487                   if(dataMember.dataType.kind != classType ||
488                      ((!dataMember.dataType._class || !dataMember.dataType._class.registered || dataMember.dataType._class.registered != _class ||
489                      _class.type != structClass)))
490                      ComputeTypeSize(dataMember.dataType);
491
492                   if(dataMember.dataType.bitFieldCount)
493                   {
494                      bitFields += dataMember.dataType.bitFieldCount;
495                      size = 0;
496                   }
497                   else
498                   {
499                      if(bitFields)
500                      {
501                         int size = (bitFields + 7) / 8;
502
503                         if(isMember)
504                         {
505                            // TESTING THIS PADDING CODE
506                            if(alignment)
507                            {
508                               member.structAlignment = Max(member.structAlignment, alignment);
509
510                               if(member.memberOffset % alignment)
511                                  member.memberOffset += alignment - (member.memberOffset % alignment);
512                            }
513
514                            dataMember.offset = member.memberOffset;
515                            if(member.type == unionMember)
516                               unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
517                            else
518                            {
519                               member.memberOffset += size;
520                            }
521                         }
522                         else
523                         {
524                            // TESTING THIS PADDING CODE
525                            if(alignment)
526                            {
527                               _class.structAlignment = Max(_class.structAlignment, alignment);
528
529                               if(_class.memberOffset % alignment)
530                                  _class.memberOffset += alignment - (_class.memberOffset % alignment);
531                            }
532
533                            dataMember.offset = _class.memberOffset;
534                            _class.memberOffset += size;
535                         }
536                         bitFields = 0;
537                      }
538                      size = dataMember.dataType.size;
539                      alignment = dataMember.dataType.alignment;
540                   }
541
542                   if(isMember)
543                   {
544                      // TESTING THIS PADDING CODE
545                      if(alignment)
546                      {
547                         member.structAlignment = Max(member.structAlignment, alignment);
548
549                         if(member.memberOffset % alignment)
550                            member.memberOffset += alignment - (member.memberOffset % alignment);
551                      }
552
553                      dataMember.offset = member.memberOffset;
554                      if(member.type == unionMember)
555                         unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
556                      else
557                      {
558                         member.memberOffset += size;
559                      }
560                   }
561                   else
562                   {
563                      // TESTING THIS PADDING CODE
564                      if(alignment)
565                      {
566                         _class.structAlignment = Max(_class.structAlignment, alignment);
567
568                         if(_class.memberOffset % alignment)
569                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
570                      }
571
572                      dataMember.offset = _class.memberOffset;
573                      _class.memberOffset += size;
574                   }
575                }
576                else
577                {
578                   int alignment;
579
580                   ComputeClassMembers((Class)dataMember, true);
581                   alignment = dataMember.structAlignment;
582
583                   if(isMember)
584                   {
585                      if(alignment)
586                      {
587                         if(member.memberOffset % alignment)
588                            member.memberOffset += alignment - (member.memberOffset % alignment);
589
590                         member.structAlignment = Max(member.structAlignment, alignment);
591                      }
592                      dataMember.offset = member.memberOffset;
593                      if(member.type == unionMember)
594                         unionMemberOffset = Max(unionMemberOffset, dataMember.memberOffset);
595                      else
596                         member.memberOffset += dataMember.memberOffset;
597                   }
598                   else
599                   {
600                      if(alignment)
601                      {
602                         if(_class.memberOffset % alignment)
603                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
604                         _class.structAlignment = Max(_class.structAlignment, alignment);
605                      }
606                      dataMember.offset = _class.memberOffset;
607                      _class.memberOffset += dataMember.memberOffset;
608                   }
609                }
610             }
611          }
612          if(bitFields)
613          {
614             int alignment = 0;
615             int size = (bitFields + 7) / 8;
616
617             if(isMember)
618             {
619                // TESTING THIS PADDING CODE
620                if(alignment)
621                {
622                   member.structAlignment = Max(member.structAlignment, alignment);
623
624                   if(member.memberOffset % alignment)
625                      member.memberOffset += alignment - (member.memberOffset % alignment);
626                }
627
628                if(member.type == unionMember)
629                   unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
630                else
631                {
632                   member.memberOffset += size;
633                }
634             }
635             else
636             {
637                // TESTING THIS PADDING CODE
638                if(alignment)
639                {
640                   _class.structAlignment = Max(_class.structAlignment, alignment);
641
642                   if(_class.memberOffset % alignment)
643                      _class.memberOffset += alignment - (_class.memberOffset % alignment);
644                }
645                _class.memberOffset += size;
646             }
647             bitFields = 0;
648          }
649       }
650       if(member && member.type == unionMember)
651       {
652          member.memberOffset = unionMemberOffset;
653       }
654
655       if(!isMember)
656       {
657          /*if(_class.type == structClass)
658             _class.size = _class.memberOffset;
659          else
660          */
661
662          if(_class.type != bitClass)
663          {
664             int extra = 0;
665             if(_class.structAlignment)
666             {
667                if(_class.memberOffset % _class.structAlignment)
668                   extra += _class.structAlignment - (_class.memberOffset % _class.structAlignment);
669             }
670             _class.structSize = (_class.base ? (_class.base.templateClass ?
671                (_class.base.type == noHeadClass ? _class.base.templateClass.memberOffset : _class.base.templateClass.structSize) :
672                   (_class.base.type == noHeadClass ? _class.base.memberOffset : _class.base.structSize) ) : 0) + _class.memberOffset + extra;
673             if(!member)
674             {
675                Property prop;
676                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
677                {
678                   if(prop.isProperty && prop.isWatchable)
679                   {
680                      prop.watcherOffset = _class.structSize;
681                      _class.structSize += sizeof(OldList);
682                   }
683                }
684             }
685
686             // Fix Derivatives
687             {
688                OldLink derivative;
689                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
690                {
691                   Class deriv = derivative.data;
692
693                   if(deriv.computeSize)
694                   {
695                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
696                      deriv.offset = /*_class.offset + */(_class.type == noHeadClass ? _class.memberOffset : _class.structSize);
697                      deriv.memberOffset = 0;
698                      // ----------------------
699
700                      deriv.structSize = deriv.offset;
701
702                      ComputeClassMembers(deriv, false);
703                   }
704                }
705             }
706          }
707       }
708    }
709    if(context)
710       FinishTemplatesContext(context);
711 }
712
713 public void ComputeModuleClasses(Module module)
714 {
715    Class _class;
716    OldLink subModule;
717
718    for(subModule = module.modules.first; subModule; subModule = subModule.next)
719       ComputeModuleClasses(subModule.data);
720    for(_class = module.classes.first; _class; _class = _class.next)
721       ComputeClassMembers(_class, false);
722 }
723
724
725 public int ComputeTypeSize(Type type)
726 {
727    uint size = type ? type.size : 0;
728    if(!size && type && !type.computing)
729    {
730       type.computing = true;
731       switch(type.kind)
732       {
733          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
734          case charType: type.alignment = size = sizeof(char); break;
735          case intType: type.alignment = size = sizeof(int); break;
736          case int64Type: type.alignment = size = sizeof(int64); break;
737          case intPtrType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
738          case intSizeType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
739          case longType: type.alignment = size = sizeof(long); break;
740          case shortType: type.alignment = size = sizeof(short); break;
741          case floatType: type.alignment = size = sizeof(float); break;
742          case doubleType: type.alignment = size = sizeof(double); break;
743          case classType:
744          {
745             Class _class = type._class ? type._class.registered : null;
746
747             if(_class && _class.type == structClass)
748             {
749                // Ensure all members are properly registered
750                ComputeClassMembers(_class, false);
751                type.alignment = _class.structAlignment;
752                type.pointerAlignment = (bool)_class.pointerAlignment;
753                size = _class.structSize;
754                if(type.alignment && size % type.alignment)
755                   size += type.alignment - (size % type.alignment);
756
757             }
758             else if(_class && (_class.type == unitClass ||
759                    _class.type == enumClass ||
760                    _class.type == bitClass))
761             {
762                if(!_class.dataType)
763                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
764                size = type.alignment = ComputeTypeSize(_class.dataType);
765             }
766             else
767             {
768                size = type.alignment = targetBits / 8; // sizeof(Instance *);
769                type.pointerAlignment = true;
770             }
771             break;
772          }
773          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */ type.pointerAlignment = true; break;
774          case arrayType:
775             if(type.arraySizeExp)
776             {
777                ProcessExpressionType(type.arraySizeExp);
778                ComputeExpression(type.arraySizeExp);
779                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType &&
780                   type.arraySizeExp.expType.kind != shortType &&
781                   type.arraySizeExp.expType.kind != charType &&
782                   type.arraySizeExp.expType.kind != longType &&
783                   type.arraySizeExp.expType.kind != int64Type &&
784                   type.arraySizeExp.expType.kind != intSizeType &&
785                   type.arraySizeExp.expType.kind != intPtrType &&
786                   type.arraySizeExp.expType.kind != enumType &&
787                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
788                {
789                   Location oldLoc = yylloc;
790                   // bool isConstant = type.arraySizeExp.isConstant;
791                   char expression[10240];
792                   expression[0] = '\0';
793                   type.arraySizeExp.expType = null;
794                   yylloc = type.arraySizeExp.loc;
795                   if(inCompiler)
796                      PrintExpression(type.arraySizeExp, expression);
797                   Compiler_Error($"Array size not constant int (%s)\n", expression);
798                   yylloc = oldLoc;
799                }
800                GetInt(type.arraySizeExp, &type.arraySize);
801             }
802             else if(type.enumClass)
803             {
804                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
805                {
806                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
807                }
808                else
809                   type.arraySize = 0;
810             }
811             else
812             {
813                // Unimplemented auto size
814                type.arraySize = 0;
815             }
816
817             size = ComputeTypeSize(type.type) * type.arraySize;
818             if(type.type)
819             {
820                type.alignment = type.type.alignment;
821                type.pointerAlignment = type.type.pointerAlignment;
822             }
823
824             break;
825          case structType:
826          {
827             if(!type.members.first && type.enumName)
828             {
829                Symbol symbol = FindStruct(curContext, type.enumName);
830                if(symbol && symbol.type)
831                {
832                   ComputeTypeSize(symbol.type);
833                   size = symbol.type.size;
834                }
835             }
836             else
837             {
838                Type member;
839                for(member = type.members.first; member; member = member.next)
840                {
841                   uint addSize = ComputeTypeSize(member);
842
843                   member.offset = size;
844                   if(member.alignment && size % member.alignment)
845                      member.offset += member.alignment - (size % member.alignment);
846                   size = member.offset;
847
848                   if(member.pointerAlignment && type.size <= 4)
849                      type.pointerAlignment = true;
850                   else if(!member.pointerAlignment && member.alignment >= 8)
851                      type.pointerAlignment = false;
852
853                   type.alignment = Max(type.alignment, member.alignment);
854                   size += addSize;
855                }
856                if(type.alignment && size % type.alignment)
857                   size += type.alignment - (size % type.alignment);
858             }
859             break;
860          }
861          case unionType:
862          {
863             if(!type.members.first && type.enumName)
864             {
865                Symbol symbol = FindStruct(curContext, type.enumName);
866                if(symbol && symbol.type)
867                {
868                   ComputeTypeSize(symbol.type);
869                   size = symbol.type.size;
870                   type.alignment = symbol.type.alignment;
871                }
872             }
873             else
874             {
875                Type member;
876                for(member = type.members.first; member; member = member.next)
877                {
878                   uint addSize = ComputeTypeSize(member);
879
880                   member.offset = size;
881                   if(member.alignment && size % member.alignment)
882                      member.offset += member.alignment - (size % member.alignment);
883                   size = member.offset;
884
885                   if(member.pointerAlignment && type.size <= 4)
886                      type.pointerAlignment = true;
887                   else if(!member.pointerAlignment && member.alignment >= 8)
888                      type.pointerAlignment = false;
889
890                   type.alignment = Max(type.alignment, member.alignment);
891
892                   size = Max(size, addSize);
893                }
894                if(type.alignment && size % type.alignment)
895                   size += type.alignment - (size % type.alignment);
896             }
897             break;
898          }
899          case templateType:
900          {
901             TemplateParameter param = type.templateParameter;
902             Type baseType = ProcessTemplateParameterType(param);
903             if(baseType)
904             {
905                size = ComputeTypeSize(baseType);
906                type.alignment = baseType.alignment;
907                type.pointerAlignment = baseType.pointerAlignment;
908             }
909             else
910                type.alignment = size = sizeof(uint64);
911             break;
912          }
913          case enumType:
914          {
915             type.alignment = size = sizeof(enum { test });
916             break;
917          }
918          case thisClassType:
919          {
920             type.alignment = size = targetBits / 8; //sizeof(void *);
921             type.pointerAlignment = true;
922             break;
923          }
924       }
925       type.size = size;
926       type.computing = false;
927    }
928    return size;
929 }
930
931
932 /*static */int AddMembers(External neededBy, OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
933 {
934    // This function is in need of a major review when implementing private members etc.
935    DataMember topMember = isMember ? (DataMember) _class : null;
936    uint totalSize = 0;
937    uint maxSize = 0;
938    int alignment;
939    uint size;
940    DataMember member;
941    int anonID = 1;
942    Context context = isMember ? null : SetupTemplatesContext(_class);
943    if(addedPadding)
944       *addedPadding = false;
945
946    if(!isMember && _class.base)
947    {
948       maxSize = _class.structSize;
949       //if(_class.base.type != systemClass) // Commented out with new Instance _class
950       {
951          // DANGER: Testing this noHeadClass here...
952          if(_class.type == structClass || _class.type == noHeadClass)
953             /*totalSize = */AddMembers(neededBy, declarations, _class.base, false, &totalSize, topClass, null);
954          else
955          {
956             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
957             if(maxSize > baseSize)
958                maxSize -= baseSize;
959             else
960                maxSize = 0;
961          }
962       }
963    }
964
965    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
966    {
967       if(!member.isProperty)
968       {
969          switch(member.type)
970          {
971             case normalMember:
972             {
973                if(member.dataTypeString)
974                {
975                   OldList * specs = MkList(), * decls = MkList();
976                   Declarator decl;
977
978                   decl = SpecDeclFromString(member.dataTypeString, specs,
979                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
980                   ListAdd(decls, MkStructDeclarator(decl, null));
981                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
982
983                   if(!member.dataType)
984                      member.dataType = ProcessType(specs, decl);
985
986                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
987
988                   {
989                      Type type = ProcessType(specs, decl);
990                      DeclareType(neededBy, member.dataType, true, false);
991                      FreeType(type);
992                   }
993                   /*
994                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
995                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
996                      DeclareStruct(member.dataType._class.string, false);
997                   */
998
999                   ComputeTypeSize(member.dataType);
1000                   size = member.dataType.size;
1001                   alignment = member.dataType.alignment;
1002
1003                   if(alignment)
1004                   {
1005                      if(totalSize % alignment)
1006                         totalSize += alignment - (totalSize % alignment);
1007                   }
1008                   totalSize += size;
1009                }
1010                break;
1011             }
1012             case unionMember:
1013             case structMember:
1014             {
1015                OldList * specs = MkList(), * list = MkList();
1016                char id[100];
1017                sprintf(id, "__anon%d", anonID++);
1018
1019                size = 0;
1020                AddMembers(neededBy, list, (Class)member, true, &size, topClass, null);
1021                ListAdd(specs,
1022                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
1023                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, MkListOne(MkDeclaratorIdentifier(MkIdentifier(id))),null)));
1024                alignment = member.structAlignment;
1025
1026                if(alignment)
1027                {
1028                   if(totalSize % alignment)
1029                      totalSize += alignment - (totalSize % alignment);
1030                }
1031                totalSize += size;
1032                break;
1033             }
1034          }
1035       }
1036    }
1037    if(retSize)
1038    {
1039       if(topMember && topMember.type == unionMember)
1040          *retSize = Max(*retSize, totalSize);
1041       else
1042          *retSize += totalSize;
1043    }
1044    else if(totalSize < maxSize && _class.type != systemClass)
1045    {
1046       int autoPadding = 0;
1047       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
1048          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
1049       if(totalSize + autoPadding < maxSize)
1050       {
1051          char sizeString[50];
1052          sprintf(sizeString, "%d", maxSize - totalSize);
1053          ListAdd(declarations,
1054             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
1055             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
1056          if(addedPadding)
1057             *addedPadding = true;
1058       }
1059    }
1060    if(context)
1061       FinishTemplatesContext(context);
1062    return topMember ? topMember.memberID : _class.memberID;
1063 }
1064
1065 static int DeclareMembers(External neededBy, Class _class, bool isMember)
1066 {
1067    DataMember topMember = isMember ? (DataMember) _class : null;
1068    DataMember member;
1069    Context context = isMember ? null : SetupTemplatesContext(_class);
1070
1071    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1072       DeclareMembers(neededBy, _class.base, false);
1073
1074    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1075    {
1076       if(!member.isProperty)
1077       {
1078          switch(member.type)
1079          {
1080             case normalMember:
1081             {
1082                if(!member.dataType && member.dataTypeString)
1083                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1084                if(member.dataType)
1085                   DeclareType(neededBy, member.dataType, true, false);
1086                break;
1087             }
1088             case unionMember:
1089             case structMember:
1090             {
1091                DeclareMembers(neededBy, (Class)member, true);
1092                break;
1093             }
1094          }
1095       }
1096    }
1097    if(context)
1098       FinishTemplatesContext(context);
1099
1100    return topMember ? topMember.memberID : _class.memberID;
1101 }
1102
1103 static void IdentifyAnonStructs(OldList/*<ClassDef>*/ *  definitions)
1104 {
1105    ClassDef def;
1106    int anonID = 1;
1107    for(def = definitions->first; def; def = def.next)
1108    {
1109       if(def.type == declarationClassDef)
1110       {
1111          Declaration decl = def.decl;
1112          if(decl && decl.specifiers)
1113          {
1114             Specifier spec;
1115             bool isStruct = false;
1116             for(spec = decl.specifiers->first; spec; spec = spec.next)
1117             {
1118                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1119                {
1120                   if(spec.definitions)
1121                      IdentifyAnonStructs(spec.definitions);
1122                   isStruct = true;
1123                }
1124             }
1125             if(isStruct)
1126             {
1127                Declarator d = null;
1128                if(decl.declarators)
1129                {
1130                   for(d = decl.declarators->first; d; d = d.next)
1131                   {
1132                      Identifier idDecl = GetDeclId(d);
1133                      if(idDecl)
1134                         break;
1135                   }
1136                }
1137                if(!d)
1138                {
1139                   char id[100];
1140                   sprintf(id, "__anon%d", anonID++);
1141                   if(!decl.declarators)
1142                      decl.declarators = MkList();
1143                   ListAdd(decl.declarators, MkDeclaratorIdentifier(MkIdentifier(id)));
1144                }
1145             }
1146          }
1147       }
1148    }
1149 }
1150
1151 External DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference)
1152 {
1153    return _DeclareStruct(neededBy, name, skipNoHead, needDereference, false);
1154 }
1155
1156 External _DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference, bool fwdDecl)
1157 {
1158    External external = null;
1159    Symbol classSym = FindClass(name);
1160    OldList * curDeclarations = null;
1161
1162    if(!inCompiler || !classSym) return null;
1163
1164    // We don't need any declaration for bit classes...
1165    if(classSym.registered &&
1166       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1167       return null;
1168
1169    if(!classSym.registered || (classSym.registered.type == normalClass && classSym.registered.structSize && classSym.registered.base && classSym.registered.base.base))
1170       _DeclareStruct(neededBy, "ecere::com::Instance", false, true, fwdDecl);
1171
1172    external = classSym.structExternal;
1173
1174    if(external && external.declaration)
1175    {
1176       Specifier spec;
1177       for(spec = external.declaration.specifiers ? external.declaration.specifiers->first : null; spec; spec = spec.next)
1178          if(spec.type == structSpecifier || spec.type == unionSpecifier)
1179          {
1180             curDeclarations = spec.definitions;
1181             break;
1182          }
1183    }
1184
1185    if(classSym.registered && !classSym.declaring && classSym.imported && (!classSym.declaredStructSym || (classSym.registered.type == noHeadClass && !skipNoHead && external && !curDeclarations)))
1186    {
1187       OldList * specifiers, * declarators;
1188       OldList * declarations = null;
1189       char structName[1024];
1190       bool addedPadding = false;
1191       Specifier curSpec = null;
1192
1193       classSym.declaring++;
1194
1195       if(strchr(classSym.string, '<'))
1196       {
1197          if(classSym.registered.templateClass)
1198             external = _DeclareStruct(neededBy, classSym.registered.templateClass.fullName, skipNoHead, needDereference, fwdDecl);
1199          classSym.declaring--;
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(external.declaration)
1226          {
1227             Specifier spec;
1228             for(spec = external.declaration.specifiers ? external.declaration.specifiers->first : null; spec; spec = spec.next)
1229                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1230                {
1231                   curSpec = spec;
1232                   curDeclarations = spec.definitions;
1233                   break;
1234                }
1235          }
1236
1237          if(declarations && (!declarations->count || (declarations->count == 1 && addedPadding)))
1238          {
1239             FreeList(declarations, FreeClassDef);
1240             declarations = null;
1241          }
1242
1243          if(classSym.registered.type != noHeadClass && !declarations)
1244          {
1245             FreeExternal(external);
1246             external = null;
1247             classSym.structExternal = null;
1248          }
1249          else
1250          {
1251             if(curSpec)
1252                curSpec.definitions = declarations;
1253             else
1254             {
1255                specifiers = MkList();
1256                declarators = MkList();
1257                ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1258                external.declaration = MkDeclaration(specifiers, declarators);
1259             }
1260             if(add)
1261                ast->Add(external);
1262          }
1263       }
1264       classSym.declaring--;
1265    }
1266    else if(!classSym.declaredStructSym && classSym.structExternal)
1267    {
1268       classSym.declaredStructSym = true;
1269
1270       if(classSym.registered)
1271          DeclareMembers(classSym.structExternal, classSym.registered, false);
1272
1273       if(classSym.structExternal.declaration && classSym.structExternal.declaration.specifiers)
1274       {
1275          Specifier spec;
1276          for(spec = classSym.structExternal.declaration.specifiers->first; spec; spec = spec.next)
1277          {
1278             if(spec.definitions)
1279                IdentifyAnonStructs(spec.definitions);
1280          }
1281       }
1282    }
1283    if(inCompiler && neededBy && (external || !classSym.imported))
1284    {
1285       if(!external)
1286       {
1287          classSym.structExternal = external = MkExternalDeclaration(null);
1288          external.symbol = classSym;
1289          ast->Add(external);
1290       }
1291       if(reachedPass15 && !external.declaration && classSym.registered && classSym.registered.type == noHeadClass)
1292       {
1293          // Declare nohead classes without definitions here (e.g. IteratorPointer)
1294          char structName[1024];
1295          OldList * specifiers, * declarators;
1296          structName[0] = 0;
1297          FullClassNameCat(structName, name, false);
1298          specifiers = MkList();
1299          declarators = MkList();
1300          ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), null));
1301          external.declaration = MkDeclaration(specifiers, declarators);
1302       }
1303       if(fwdDecl)
1304       {
1305          External e = external.fwdDecl ? external.fwdDecl : external;
1306          if(e.incoming.count)
1307             neededBy.CreateUniqueEdge(e, !needDereference && !external.fwdDecl);
1308       }
1309       else
1310          neededBy.CreateUniqueEdge(external, !needDereference);
1311    }
1312    return external;
1313 }
1314
1315 void DeclareProperty(External neededBy, Property prop, char * setName, char * getName)
1316 {
1317    Symbol symbol = prop.symbol;
1318    bool imported = false;
1319    bool dllImport = false;
1320    External structExternal = null;
1321    External instExternal = null;
1322
1323    strcpy(setName, "__ecereProp_");
1324    FullClassNameCat(setName, prop._class.fullName, false);
1325    strcat(setName, "_Set_");
1326    FullClassNameCat(setName, prop.name, true);
1327
1328    strcpy(getName, "__ecereProp_");
1329    FullClassNameCat(getName, prop._class.fullName, false);
1330    strcat(getName, "_Get_");
1331    FullClassNameCat(getName, prop.name, true);
1332
1333    if(!symbol || symbol._import)
1334    {
1335       if(!symbol)
1336       {
1337          Symbol classSym;
1338
1339          if(!prop._class.symbol)
1340             prop._class.symbol = FindClass(prop._class.fullName);
1341          classSym = prop._class.symbol;
1342          if(classSym && !classSym._import)
1343          {
1344             ModuleImport module;
1345
1346             if(prop._class.module)
1347                module = FindModule(prop._class.module);
1348             else
1349                module = mainModule;
1350
1351             classSym._import = ClassImport
1352             {
1353                name = CopyString(prop._class.fullName);
1354                isRemote = prop._class.isRemote;
1355             };
1356             module.classes.Add(classSym._import);
1357          }
1358          symbol = prop.symbol = Symbol { };
1359          symbol._import = (ClassImport)PropertyImport
1360          {
1361             name = CopyString(prop.name);
1362             isVirtual = false; //prop.isVirtual;
1363             hasSet = prop.Set ? true : false;
1364             hasGet = prop.Get ? true : false;
1365          };
1366          if(classSym)
1367             classSym._import.properties.Add(symbol._import);
1368       }
1369       imported = true;
1370       // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1371       if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1372          prop._class.module.importType != staticImport)
1373          dllImport = true;
1374    }
1375
1376    if(!symbol.type)
1377    {
1378       Context context = SetupTemplatesContext(prop._class);
1379       symbol.type = ProcessTypeString(prop.dataTypeString, false);
1380       FinishTemplatesContext(context);
1381    }
1382
1383    if((prop.Get && !symbol.externalGet) || (prop.Set && !symbol.externalSet))
1384    {
1385       if(prop._class.type == normalClass && prop._class.structSize)
1386          instExternal = DeclareStruct(null, "ecere::com::Instance", false, true);
1387       structExternal = DeclareStruct(null, prop._class.fullName, prop._class.type != structClass /*true*/, false);
1388    }
1389
1390    // Get
1391    if(prop.Get && !symbol.externalGet)
1392    {
1393       Declaration decl;
1394       OldList * specifiers, * declarators;
1395       Declarator d;
1396       OldList * params;
1397       Specifier spec = null;
1398       External external;
1399       Declarator typeDecl;
1400       bool simple = false;
1401       bool needReference;
1402
1403       specifiers = MkList();
1404       declarators = MkList();
1405       params = MkList();
1406
1407       ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1408          MkDeclaratorIdentifier(MkIdentifier("this"))));
1409
1410       d = MkDeclaratorIdentifier(MkIdentifier(getName));
1411       //if(imported)
1412       if(dllImport)
1413          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1414
1415       {
1416          Context context = SetupTemplatesContext(prop._class);
1417          typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1418          FinishTemplatesContext(context);
1419       }
1420
1421       // Make sure the simple _class's type is declared
1422       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1423       for(spec = specifiers->first; spec; spec = spec.next)
1424       {
1425          if(spec.type == nameSpecifier)
1426          {
1427             Symbol classSym = spec.symbol;
1428             if(needReference)
1429             {
1430                symbol._class = classSym.registered;
1431                if(classSym.registered && classSym.registered.type == structClass)
1432                   simple = true;
1433             }
1434             break;
1435          }
1436       }
1437
1438       if(!simple)
1439          d = PlugDeclarator(typeDecl, d);
1440       else
1441       {
1442          ListAdd(params, MkTypeName(specifiers,
1443             PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1444          specifiers = MkList();
1445       }
1446
1447       d = MkDeclaratorFunction(d, params);
1448
1449       //if(imported)
1450       if(dllImport)
1451          specifiers->Insert(null, MkSpecifier(EXTERN));
1452       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1453          specifiers->Insert(null, MkSpecifier(STATIC));
1454       if(simple)
1455          ListAdd(specifiers, MkSpecifier(VOID));
1456
1457       ListAdd(declarators, MkInitDeclarator(d, null));
1458
1459       decl = MkDeclaration(specifiers, declarators);
1460
1461       external = MkExternalDeclaration(decl);
1462
1463       if(structExternal)
1464          external.CreateEdge(structExternal, false);
1465       if(instExternal)
1466          external.CreateEdge(instExternal, false);
1467
1468       if(spec)
1469          DeclareStruct(external, spec.name, false, needReference);
1470
1471       ast->Add(external);
1472       external.symbol = symbol;
1473       symbol.externalGet = external;
1474
1475       ReplaceThisClassSpecifiers(specifiers, prop._class);
1476
1477       if(typeDecl)
1478          FreeDeclarator(typeDecl);
1479    }
1480
1481    // Set
1482    if(prop.Set && !symbol.externalSet)
1483    {
1484       Declaration decl;
1485       OldList * specifiers, * declarators;
1486       Declarator d;
1487       OldList * params;
1488       Specifier spec = null;
1489       External external;
1490       Declarator typeDecl;
1491       bool needReference;
1492
1493       declarators = MkList();
1494       params = MkList();
1495
1496       if(!prop.conversion || prop._class.type == structClass)
1497       {
1498          ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1499             MkDeclaratorIdentifier(MkIdentifier("this"))));
1500       }
1501
1502       specifiers = MkList();
1503
1504       {
1505          Context context = SetupTemplatesContext(prop._class);
1506          typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1507             MkDeclaratorIdentifier(MkIdentifier("value")));
1508          FinishTemplatesContext(context);
1509       }
1510       if(!strcmp(prop._class.base.fullName, "eda::Row") || !strcmp(prop._class.base.fullName, "eda::Id"))
1511          specifiers->Insert(null, MkSpecifier(CONST));
1512
1513       ListAdd(params, MkTypeName(specifiers, d));
1514
1515       d = MkDeclaratorIdentifier(MkIdentifier(setName));
1516       if(dllImport)
1517          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1518       d = MkDeclaratorFunction(d, params);
1519
1520       // Make sure the simple _class's type is declared
1521       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1522       for(spec = specifiers->first; spec; spec = spec.next)
1523       {
1524          if(spec.type == nameSpecifier)
1525          {
1526             Symbol classSym = spec.symbol;
1527             if(needReference)
1528                symbol._class = classSym.registered;
1529             break;
1530          }
1531       }
1532
1533       ListAdd(declarators, MkInitDeclarator(d, null));
1534
1535       specifiers = MkList();
1536       if(dllImport)
1537          specifiers->Insert(null, MkSpecifier(EXTERN));
1538       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1539          specifiers->Insert(null, MkSpecifier(STATIC));
1540
1541       if(!prop.conversion || prop._class.type == structClass)
1542          ListAdd(specifiers, MkSpecifier(VOID));
1543       else
1544          ListAdd(specifiers, MkSpecifierName(prop._class.fullName));
1545
1546       decl = MkDeclaration(specifiers, declarators);
1547
1548       external = MkExternalDeclaration(decl);
1549
1550       if(structExternal)
1551          external.CreateEdge(structExternal, false);
1552       if(instExternal)
1553          external.CreateEdge(instExternal, false);
1554
1555       if(spec)
1556          DeclareStruct(external, spec.name, false, needReference);
1557
1558       ast->Add(external);
1559       external.symbol = symbol;
1560       symbol.externalSet = external;
1561
1562       ReplaceThisClassSpecifiers(specifiers, prop._class);
1563    }
1564
1565    // Property (for Watchers)
1566    if(!symbol.externalPtr)
1567    {
1568       Declaration decl;
1569       External external;
1570       OldList * specifiers = MkList();
1571       char propName[1024];
1572
1573       if(imported)
1574          specifiers->Insert(null, MkSpecifier(EXTERN));
1575       else
1576       {
1577          specifiers->Insert(null, MkSpecifier(STATIC));
1578          specifiers->Add(MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
1579       }
1580
1581       ListAdd(specifiers, MkSpecifierName("Property"));
1582
1583       strcpy(propName, "__ecereProp_");
1584       FullClassNameCat(propName, prop._class.fullName, false);
1585       strcat(propName, "_");
1586       FullClassNameCat(propName, prop.name, true);
1587
1588       {
1589          OldList * list = MkList();
1590          ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1591
1592          if(!imported)
1593          {
1594             strcpy(propName, "__ecerePropM_");
1595             FullClassNameCat(propName, prop._class.fullName, false);
1596             strcat(propName, "_");
1597             FullClassNameCat(propName, prop.name, true);
1598
1599             ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1600          }
1601          decl = MkDeclaration(specifiers, list);
1602       }
1603
1604       external = MkExternalDeclaration(decl);
1605       ast->Insert(curExternal.prev, external);
1606       external.symbol = symbol;
1607       symbol.externalPtr = external;
1608    }
1609
1610    if(inCompiler && neededBy)
1611    {
1612       // Could improve this to create edge on only what is needed...
1613       if(symbol.externalPtr)
1614          neededBy.CreateUniqueEdge(symbol.externalPtr, false);
1615
1616       if(symbol.externalGet)
1617          neededBy.CreateUniqueEdge(symbol.externalGet, symbol.externalGet.type == functionExternal);
1618
1619       if(symbol.externalSet)
1620          neededBy.CreateUniqueEdge(symbol.externalSet, symbol.externalSet.type == functionExternal);
1621
1622       // IsSet ?
1623    }
1624 }
1625
1626 // ***************** EXPRESSION PROCESSING ***************************
1627 public Type Dereference(Type source)
1628 {
1629    Type type = null;
1630    if(source)
1631    {
1632       if(source.kind == pointerType || source.kind == arrayType)
1633       {
1634          type = source.type;
1635          source.type.refCount++;
1636       }
1637       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1638       {
1639          type = Type
1640          {
1641             kind = charType;
1642             refCount = 1;
1643          };
1644       }
1645       // Support dereferencing of no head classes for now...
1646       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1647       {
1648          type = source;
1649          source.refCount++;
1650       }
1651       else
1652          Compiler_Error($"cannot dereference type\n");
1653    }
1654    return type;
1655 }
1656
1657 static Type Reference(Type source)
1658 {
1659    Type type = null;
1660    if(source)
1661    {
1662       type = Type
1663       {
1664          kind = pointerType;
1665          type = source;
1666          refCount = 1;
1667       };
1668       source.refCount++;
1669    }
1670    return type;
1671 }
1672
1673 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1674 {
1675    Identifier ident = member.identifiers ? member.identifiers->first : null;
1676    bool found = false;
1677    DataMember dataMember = null;
1678    Method method = null;
1679    bool freeType = false;
1680
1681    yylloc = member.loc;
1682
1683    if(!ident)
1684    {
1685       if(curMember)
1686       {
1687          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1688          if(*curMember)
1689          {
1690             found = true;
1691             dataMember = *curMember;
1692          }
1693       }
1694    }
1695    else
1696    {
1697       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1698       DataMember _subMemberStack[256];
1699       int _subMemberStackPos = 0;
1700
1701       // FILL MEMBER STACK
1702       if(!thisMember)
1703          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1704       if(thisMember)
1705       {
1706          dataMember = thisMember;
1707          if(curMember && thisMember.memberAccess == publicAccess)
1708          {
1709             *curMember = thisMember;
1710             *curClass = thisMember._class;
1711             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1712             *subMemberStackPos = _subMemberStackPos;
1713          }
1714          found = true;
1715       }
1716       else
1717       {
1718          // Setting a method
1719          method = eClass_FindMethod(_class, ident.string, privateModule);
1720          if(method && method.type == virtualMethod)
1721             found = true;
1722          else
1723             method = null;
1724       }
1725    }
1726
1727    if(found)
1728    {
1729       Type type = null;
1730       if(dataMember)
1731       {
1732          if(!dataMember.dataType && dataMember.dataTypeString)
1733          {
1734             //Context context = SetupTemplatesContext(dataMember._class);
1735             Context context = SetupTemplatesContext(_class);
1736             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1737             FinishTemplatesContext(context);
1738          }
1739          type = dataMember.dataType;
1740       }
1741       else if(method)
1742       {
1743          // This is for destination type...
1744          if(!method.dataType)
1745             ProcessMethodType(method);
1746          //DeclareMethod(method);
1747          // method.dataType = ((Symbol)method.symbol)->type;
1748          type = method.dataType;
1749       }
1750
1751       if(ident && ident.next)
1752       {
1753          for(ident = ident.next; ident && type; ident = ident.next)
1754          {
1755             if(type.kind == classType)
1756             {
1757                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1758                if(!dataMember)
1759                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1760                if(dataMember)
1761                   type = dataMember.dataType;
1762             }
1763             else if(type.kind == structType || type.kind == unionType)
1764             {
1765                Type memberType;
1766                for(memberType = type.members.first; memberType; memberType = memberType.next)
1767                {
1768                   if(!strcmp(memberType.name, ident.string))
1769                   {
1770                      type = memberType;
1771                      break;
1772                   }
1773                }
1774             }
1775          }
1776       }
1777
1778       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1779       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1780       {
1781          int id = 0;
1782          ClassTemplateParameter curParam = null;
1783          Class sClass;
1784          for(sClass = _class; sClass; sClass = sClass.base)
1785          {
1786             id = 0;
1787             if(sClass.templateClass) sClass = sClass.templateClass;
1788             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1789             {
1790                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1791                {
1792                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1793                   {
1794                      if(sClass.templateClass) sClass = sClass.templateClass;
1795                      id += sClass.templateParams.count;
1796                   }
1797                   break;
1798                }
1799                id++;
1800             }
1801             if(curParam) break;
1802          }
1803
1804          if(curParam)
1805          {
1806             ClassTemplateArgument arg = _class.templateArgs[id];
1807             if(arg.dataTypeString)
1808             {
1809                bool constant = type.constant;
1810                // FreeType(type);
1811                type = ProcessTypeString(arg.dataTypeString, false);
1812                if(type.kind == classType && constant) type.constant = true;
1813                else if(type.kind == pointerType)
1814                {
1815                   Type t = type.type;
1816                   while(t.kind == pointerType) t = t.type;
1817                   if(constant) t.constant = constant;
1818                }
1819                freeType = true;
1820                if(type && _class.templateClass)
1821                   type.passAsTemplate = true;
1822                if(type)
1823                {
1824                   // type.refCount++;
1825                   /*if(!exp.destType)
1826                   {
1827                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1828                      exp.destType.refCount++;
1829                   }*/
1830                }
1831             }
1832          }
1833       }
1834       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1835       {
1836          Class expClass = type._class.registered;
1837          Class cClass = null;
1838          int paramCount = 0;
1839          int lastParam = -1;
1840
1841          char templateString[1024];
1842          ClassTemplateParameter param;
1843          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1844          for(cClass = expClass; cClass; cClass = cClass.base)
1845          {
1846             int p = 0;
1847             if(cClass.templateClass) cClass = cClass.templateClass;
1848             for(param = cClass.templateParams.first; param; param = param.next)
1849             {
1850                int id = p;
1851                Class sClass;
1852                ClassTemplateArgument arg;
1853                for(sClass = cClass.base; sClass; sClass = sClass.base)
1854                {
1855                   if(sClass.templateClass) sClass = sClass.templateClass;
1856                   id += sClass.templateParams.count;
1857                }
1858                arg = expClass.templateArgs[id];
1859
1860                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1861                {
1862                   ClassTemplateParameter cParam;
1863                   //int p = numParams - sClass.templateParams.count;
1864                   int p = 0;
1865                   Class nextClass;
1866                   if(sClass.templateClass) sClass = sClass.templateClass;
1867
1868                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1869                   {
1870                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1871                      p += nextClass.templateParams.count;
1872                   }
1873
1874                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1875                   {
1876                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1877                      {
1878                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1879                         {
1880                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1881                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1882                            break;
1883                         }
1884                      }
1885                   }
1886                }
1887
1888                {
1889                   char argument[256];
1890                   argument[0] = '\0';
1891                   /*if(arg.name)
1892                   {
1893                      strcat(argument, arg.name.string);
1894                      strcat(argument, " = ");
1895                   }*/
1896                   switch(param.type)
1897                   {
1898                      case expression:
1899                      {
1900                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1901                         char expString[1024];
1902                         OldList * specs = MkList();
1903                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1904                         Expression exp;
1905                         char * string = PrintHexUInt64(arg.expression.ui64);
1906                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1907                         delete string;
1908
1909                         ProcessExpressionType(exp);
1910                         ComputeExpression(exp);
1911                         expString[0] = '\0';
1912                         PrintExpression(exp, expString);
1913                         strcat(argument, expString);
1914                         //delete exp;
1915                         FreeExpression(exp);
1916                         break;
1917                      }
1918                      case identifier:
1919                      {
1920                         strcat(argument, arg.member.name);
1921                         break;
1922                      }
1923                      case TemplateParameterType::type:
1924                      {
1925                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1926                            strcat(argument, arg.dataTypeString);
1927                         break;
1928                      }
1929                   }
1930                   if(argument[0])
1931                   {
1932                      if(paramCount) strcat(templateString, ", ");
1933                      if(lastParam != p - 1)
1934                      {
1935                         strcat(templateString, param.name);
1936                         strcat(templateString, " = ");
1937                      }
1938                      strcat(templateString, argument);
1939                      paramCount++;
1940                      lastParam = p;
1941                   }
1942                   p++;
1943                }
1944             }
1945          }
1946          {
1947             int len = strlen(templateString);
1948             if(templateString[len-1] == '<')
1949                len--;
1950             else
1951             {
1952                if(templateString[len-1] == '>')
1953                   templateString[len++] = ' ';
1954                templateString[len++] = '>';
1955             }
1956             templateString[len++] = '\0';
1957          }
1958          {
1959             Context context = SetupTemplatesContext(_class);
1960             if(freeType) FreeType(type);
1961             type = ProcessTypeString(templateString, false);
1962             freeType = true;
1963             FinishTemplatesContext(context);
1964          }
1965       }
1966
1967       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1968       {
1969          ProcessExpressionType(member.initializer.exp);
1970          if(!member.initializer.exp.expType)
1971          {
1972             if(inCompiler)
1973             {
1974                char expString[10240];
1975                expString[0] = '\0';
1976                PrintExpression(member.initializer.exp, expString);
1977                ChangeCh(expString, '\n', ' ');
1978                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1979             }
1980          }
1981          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1982          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
1983          {
1984             Compiler_Error($"incompatible instance method %s\n", ident.string);
1985          }
1986       }
1987       else if(member.initializer)
1988       {
1989          /*
1990          FreeType(member.exp.destType);
1991          member.exp.destType = type;
1992          if(member.exp.destType)
1993             member.exp.destType.refCount++;
1994          ProcessExpressionType(member.exp);
1995          */
1996
1997          ProcessInitializer(member.initializer, type);
1998       }
1999       if(freeType) FreeType(type);
2000    }
2001    else
2002    {
2003       if(_class && _class.type == unitClass)
2004       {
2005          if(member.initializer)
2006          {
2007             /*
2008             FreeType(member.exp.destType);
2009             member.exp.destType = MkClassType(_class.fullName);
2010             ProcessExpressionType(member.initializer, type);
2011             */
2012             Type type = MkClassType(_class.fullName);
2013             ProcessInitializer(member.initializer, type);
2014             FreeType(type);
2015          }
2016       }
2017       else
2018       {
2019          if(member.initializer)
2020          {
2021             //ProcessExpressionType(member.exp);
2022             ProcessInitializer(member.initializer, null);
2023          }
2024          if(ident)
2025          {
2026             if(method)
2027             {
2028                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2029             }
2030             else if(_class)
2031             {
2032                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2033                if(inCompiler)
2034                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2035             }
2036          }
2037          else if(_class)
2038             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2039       }
2040    }
2041 }
2042
2043 void ProcessInstantiationType(Instantiation inst)
2044 {
2045    yylloc = inst.loc;
2046    if(inst._class)
2047    {
2048       MembersInit members;
2049       Symbol classSym;
2050       Class _class;
2051
2052       classSym = inst._class.symbol;
2053       _class = classSym ? classSym.registered : null;
2054
2055       if(!_class || _class.type != noHeadClass)
2056          DeclareStruct(curExternal, inst._class.name, false, true);
2057
2058       afterExternal = afterExternal ? afterExternal : curExternal;
2059
2060       if(inst.exp)
2061          ProcessExpressionType(inst.exp);
2062
2063       inst.isConstant = true;
2064       if(inst.members)
2065       {
2066          DataMember curMember = null;
2067          Class curClass = null;
2068          DataMember subMemberStack[256];
2069          int subMemberStackPos = 0;
2070
2071          for(members = inst.members->first; members; members = members.next)
2072          {
2073             switch(members.type)
2074             {
2075                case methodMembersInit:
2076                {
2077                   char name[1024];
2078                   static uint instMethodID = 0;
2079                   External external = curExternal;
2080                   Context context = curContext;
2081                   Declarator declarator = members.function.declarator;
2082                   Identifier nameID = GetDeclId(declarator);
2083                   char * unmangled = nameID ? nameID.string : null;
2084                   Expression exp;
2085                   External createdExternal = null;
2086
2087                   if(inCompiler)
2088                   {
2089                      char number[16];
2090                      strcpy(name, "__ecereInstMeth_");
2091                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2092                      strcat(name, "_");
2093                      strcat(name, nameID.string);
2094                      strcat(name, "_");
2095                      sprintf(number, "_%08d", instMethodID++);
2096                      strcat(name, number);
2097                      nameID.string = CopyString(name);
2098                   }
2099
2100                   // Do modifications here...
2101                   if(declarator)
2102                   {
2103                      Symbol symbol = declarator.symbol;
2104                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2105
2106                      if(method && method.type == virtualMethod)
2107                      {
2108                         symbol.method = method;
2109                         ProcessMethodType(method);
2110
2111                         if(!symbol.type.thisClass)
2112                         {
2113                            if(method.dataType.thisClass && currentClass &&
2114                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2115                            {
2116                               if(!currentClass.symbol)
2117                                  currentClass.symbol = FindClass(currentClass.fullName);
2118                               symbol.type.thisClass = currentClass.symbol;
2119                            }
2120                            else
2121                            {
2122                               if(!_class.symbol)
2123                                  _class.symbol = FindClass(_class.fullName);
2124                               symbol.type.thisClass = _class.symbol;
2125                            }
2126                         }
2127                         DeclareType(curExternal, symbol.type, true, true);
2128
2129                      }
2130                      else if(classSym)
2131                      {
2132                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2133                            unmangled, classSym.string);
2134                      }
2135                   }
2136
2137                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2138
2139                   if(nameID)
2140                   {
2141                      FreeSpecifier(nameID._class);
2142                      nameID._class = null;
2143                   }
2144
2145                   curExternal = createdExternal;
2146                   if(inCompiler)
2147                   {
2148                      if(createdExternal.function)
2149                         ProcessFunction(createdExternal.function);
2150                   }
2151                   else if(declarator)
2152                   {
2153                      curExternal = declarator.symbol.pointerExternal;
2154                      ProcessFunction((FunctionDefinition)members.function);
2155                   }
2156                   curExternal = external;
2157                   curContext = context;
2158
2159                   if(inCompiler)
2160                   {
2161                      FreeClassFunction(members.function);
2162
2163                      // In this pass, turn this into a MemberInitData
2164                      exp = QMkExpId(name);
2165                      members.type = dataMembersInit;
2166                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2167
2168                      delete unmangled;
2169                   }
2170                   break;
2171                }
2172                case dataMembersInit:
2173                {
2174                   if(members.dataMembers && classSym)
2175                   {
2176                      MemberInit member;
2177                      Location oldyyloc = yylloc;
2178                      for(member = members.dataMembers->first; member; member = member.next)
2179                      {
2180                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2181                         if(member.initializer && !member.initializer.isConstant)
2182                            inst.isConstant = false;
2183                      }
2184                      yylloc = oldyyloc;
2185                   }
2186                   break;
2187                }
2188             }
2189          }
2190       }
2191    }
2192 }
2193
2194 void DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2195 {
2196    _DeclareType(neededFor, type, needDereference, forFunctionDef, false);
2197 }
2198
2199 void DeclareTypeForwardDeclare(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2200 {
2201    _DeclareType(neededFor, type, needDereference, forFunctionDef, true);
2202 }
2203
2204 static void _DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef, bool fwdDecl)
2205 {
2206    if(inCompiler)
2207    {
2208       if(type.kind == functionType)
2209       {
2210          Type param;
2211          for(param = type.params.first; param; param = param.next)
2212             _DeclareType(neededFor, param, forFunctionDef, false, fwdDecl);
2213          _DeclareType(neededFor, type.returnType, forFunctionDef, false, fwdDecl);
2214       }
2215       else if(type.kind == pointerType)
2216          _DeclareType(neededFor, type.type, false, false, fwdDecl);
2217       else if(type.kind == classType)
2218       {
2219          Class c = type._class.registered;
2220          _DeclareStruct(neededFor, c ? c.fullName : "ecere::com::Instance", c ? c.type == noHeadClass : false, needDereference && c && c.type == structClass, fwdDecl);
2221       }
2222       else if(type.kind == structType || type.kind == unionType)
2223       {
2224          Type member;
2225          for(member = type.members.first; member; member = member.next)
2226             _DeclareType(neededFor, member, needDereference, forFunctionDef, fwdDecl);
2227       }
2228       else if(type.kind == arrayType)
2229          _DeclareType(neededFor, type.arrayType, true, false, fwdDecl);
2230    }
2231 }
2232
2233 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2234 {
2235    ClassTemplateArgument * arg = null;
2236    int id = 0;
2237    ClassTemplateParameter curParam = null;
2238    Class sClass;
2239    for(sClass = _class; sClass; sClass = sClass.base)
2240    {
2241       id = 0;
2242       if(sClass.templateClass) sClass = sClass.templateClass;
2243       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2244       {
2245          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2246          {
2247             for(sClass = sClass.base; sClass; sClass = sClass.base)
2248             {
2249                if(sClass.templateClass) sClass = sClass.templateClass;
2250                id += sClass.templateParams.count;
2251             }
2252             break;
2253          }
2254          id++;
2255       }
2256       if(curParam) break;
2257    }
2258    if(curParam)
2259    {
2260       arg = &_class.templateArgs[id];
2261       if(arg && param.type == type)
2262          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2263    }
2264    return arg;
2265 }
2266
2267 public Context SetupTemplatesContext(Class _class)
2268 {
2269    Context context = PushContext();
2270    context.templateTypesOnly = true;
2271    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2272    {
2273       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2274       for(; param; param = param.next)
2275       {
2276          if(param.type == type && param.identifier)
2277          {
2278             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2279             curContext.templateTypes.Add((BTNode)type);
2280          }
2281       }
2282    }
2283    else if(_class)
2284    {
2285       Class sClass;
2286       for(sClass = _class; sClass; sClass = sClass.base)
2287       {
2288          ClassTemplateParameter p;
2289          for(p = sClass.templateParams.first; p; p = p.next)
2290          {
2291             //OldList * specs = MkList();
2292             //Declarator decl = null;
2293             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2294             if(p.type == type)
2295             {
2296                TemplateParameter param = p.param;
2297                TemplatedType type;
2298                if(!param)
2299                {
2300                   // ADD DATA TYPE HERE...
2301                   p.param = param = TemplateParameter
2302                   {
2303                      identifier = MkIdentifier(p.name), type = p.type,
2304                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2305                   };
2306                }
2307                type = TemplatedType { key = (uintptr)p.name, param = param };
2308                curContext.templateTypes.Add((BTNode)type);
2309             }
2310          }
2311       }
2312    }
2313    return context;
2314 }
2315
2316 public void FinishTemplatesContext(Context context)
2317 {
2318    PopContext(context);
2319    FreeContext(context);
2320    delete context;
2321 }
2322
2323 public void ProcessMethodType(Method method)
2324 {
2325    if(!method.dataType)
2326    {
2327       Context context = SetupTemplatesContext(method._class);
2328
2329       method.dataType = ProcessTypeString(method.dataTypeString, false);
2330
2331       FinishTemplatesContext(context);
2332
2333       if(method.type != virtualMethod && method.dataType)
2334       {
2335          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2336          {
2337             if(!method._class.symbol)
2338                method._class.symbol = FindClass(method._class.fullName);
2339             method.dataType.thisClass = method._class.symbol;
2340          }
2341       }
2342
2343       // Why was this commented out? Working fine without now...
2344
2345       /*
2346       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2347          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2348          */
2349    }
2350
2351    /*
2352    if(type)
2353    {
2354       char * par = strstr(type, "(");
2355       char * classOp = null;
2356       int classOpLen = 0;
2357       if(par)
2358       {
2359          int c;
2360          for(c = par-type-1; c >= 0; c++)
2361          {
2362             if(type[c] == ':' && type[c+1] == ':')
2363             {
2364                classOp = type + c - 1;
2365                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2366                {
2367                   classOp--;
2368                   classOpLen++;
2369                }
2370                break;
2371             }
2372             else if(!isspace(type[c]))
2373                break;
2374          }
2375       }
2376       if(classOp)
2377       {
2378          char temp[1024];
2379          int typeLen = strlen(type);
2380          memcpy(temp, classOp, classOpLen);
2381          temp[classOpLen] = '\0';
2382          if(temp[0])
2383             _class = eSystem_FindClass(module, temp);
2384          else
2385             _class = null;
2386          method.dataTypeString = new char[typeLen - classOpLen + 1];
2387          memcpy(method.dataTypeString, type, classOp - type);
2388          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2389       }
2390       else
2391          method.dataTypeString = type;
2392    }
2393    */
2394 }
2395
2396
2397 public void ProcessPropertyType(Property prop)
2398 {
2399    if(!prop.dataType)
2400    {
2401       Context context = SetupTemplatesContext(prop._class);
2402       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2403       FinishTemplatesContext(context);
2404    }
2405 }
2406
2407 public void DeclareMethod(External neededFor, Method method, const char * name)
2408 {
2409    Symbol symbol = method.symbol;
2410    if(!symbol || (!symbol.pointerExternal && (!symbol.methodCodeExternal || method.type == virtualMethod)))
2411    {
2412       bool dllImport = false;
2413
2414       if(!method.dataType)
2415          method.dataType = ProcessTypeString(method.dataTypeString, false);
2416
2417       //if(!symbol || symbol._import || method.type == virtualMethod)
2418       {
2419          if(!symbol || method.type == virtualMethod)
2420          {
2421             Symbol classSym;
2422             if(!method._class.symbol)
2423                method._class.symbol = FindClass(method._class.fullName);
2424             classSym = method._class.symbol;
2425             if(!classSym._import)
2426             {
2427                ModuleImport module;
2428
2429                if(method._class.module && method._class.module.name)
2430                   module = FindModule(method._class.module);
2431                else
2432                   module = mainModule;
2433                classSym._import = ClassImport
2434                {
2435                   name = CopyString(method._class.fullName);
2436                   isRemote = method._class.isRemote;
2437                };
2438                module.classes.Add(classSym._import);
2439             }
2440             if(!symbol)
2441             {
2442                symbol = method.symbol = Symbol { };
2443             }
2444             if(!symbol._import)
2445             {
2446                symbol._import = (ClassImport)MethodImport
2447                {
2448                   name = CopyString(method.name);
2449                   isVirtual = method.type == virtualMethod;
2450                };
2451                classSym._import.methods.Add(symbol._import);
2452             }
2453             if(!symbol)
2454             {
2455                symbol.type = method.dataType;
2456                if(symbol.type) symbol.type.refCount++;
2457             }
2458          }
2459          if(!method.dataType.dllExport)
2460          {
2461             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2462                dllImport = true;
2463          }
2464       }
2465
2466       if(inCompiler)
2467       {
2468          // We need a declaration here :)
2469          Declaration decl;
2470          OldList * specifiers, * declarators;
2471          Declarator d;
2472          Declarator funcDecl;
2473          External external;
2474
2475          specifiers = MkList();
2476          declarators = MkList();
2477
2478          if(dllImport)
2479             ListAdd(specifiers, MkSpecifier(EXTERN));
2480          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2481             ListAdd(specifiers, MkSpecifier(STATIC));
2482
2483          if(method.type == virtualMethod)
2484          {
2485             ListAdd(specifiers, MkSpecifier(INT));
2486             d = MkDeclaratorIdentifier(MkIdentifier(name));
2487          }
2488          else
2489          {
2490             d = MkDeclaratorIdentifier(MkIdentifier(name));
2491             if(dllImport)
2492                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2493             {
2494                Context context = SetupTemplatesContext(method._class);
2495                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2496                FinishTemplatesContext(context);
2497             }
2498             funcDecl = GetFuncDecl(d);
2499
2500             if(dllImport)
2501             {
2502                Specifier spec, next;
2503                for(spec = specifiers->first; spec; spec = next)
2504                {
2505                   next = spec.next;
2506                   if(spec.type == extendedSpecifier)
2507                   {
2508                      specifiers->Remove(spec);
2509                      FreeSpecifier(spec);
2510                   }
2511                }
2512             }
2513
2514             // Add this parameter if not a static method
2515             if(method.dataType && !method.dataType.staticMethod)
2516             {
2517                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2518                {
2519                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2520                   TypeName thisParam = MkTypeName(MkListOne(
2521                      MkSpecifierName(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2522                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2523                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2524                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2525
2526                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2527                   {
2528                      TypeName param = funcDecl.function.parameters->first;
2529                      funcDecl.function.parameters->Remove(param);
2530                      FreeTypeName(param);
2531                   }
2532
2533                   if(!funcDecl.function.parameters)
2534                      funcDecl.function.parameters = MkList();
2535                   funcDecl.function.parameters->Insert(null, thisParam);
2536                }
2537             }
2538          }
2539          ProcessDeclarator(d, true);
2540
2541          ListAdd(declarators, MkInitDeclarator(d, null));
2542
2543          decl = MkDeclaration(specifiers, declarators);
2544
2545          ReplaceThisClassSpecifiers(specifiers, method._class);
2546
2547          external = MkExternalDeclaration(decl);
2548          external.symbol = symbol;
2549          symbol.pointerExternal = external;
2550          ast->Add(external);
2551          DeclareStruct(external, method._class.fullName, true, true);
2552          if(method.dataType)
2553             DeclareType(external, method.dataType, true, true);
2554       }
2555    }
2556    if(inCompiler && neededFor)
2557    {
2558       External external = symbol.pointerExternal ? symbol.pointerExternal : symbol.methodCodeExternal;
2559       neededFor.CreateUniqueEdge(external, external.type == functionExternal);
2560    }
2561 }
2562
2563 char * ReplaceThisClass(Class _class)
2564 {
2565    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2566    {
2567       bool first = true;
2568       int p = 0;
2569       ClassTemplateParameter param;
2570       int lastParam = -1;
2571
2572       char className[1024];
2573       strcpy(className, _class.fullName);
2574       for(param = _class.templateParams.first; param; param = param.next)
2575       {
2576          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2577          {
2578             if(first) strcat(className, "<");
2579             if(!first) strcat(className, ", ");
2580             if(lastParam + 1 != p)
2581             {
2582                strcat(className, param.name);
2583                strcat(className, " = ");
2584             }
2585             strcat(className, param.name);
2586             first = false;
2587             lastParam = p;
2588          }
2589          p++;
2590       }
2591       if(!first)
2592       {
2593          int len = strlen(className);
2594          if(className[len-1] == '>') className[len++] = ' ';
2595          className[len++] = '>';
2596          className[len++] = '\0';
2597       }
2598       return CopyString(className);
2599    }
2600    else
2601       return CopyString(_class.fullName);
2602 }
2603
2604 Type ReplaceThisClassType(Class _class)
2605 {
2606    Type type;
2607    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2608    {
2609       bool first = true;
2610       int p = 0;
2611       ClassTemplateParameter param;
2612       int lastParam = -1;
2613       char className[1024];
2614       strcpy(className, _class.fullName);
2615
2616       for(param = _class.templateParams.first; param; param = param.next)
2617       {
2618          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2619          {
2620             if(first) strcat(className, "<");
2621             if(!first) strcat(className, ", ");
2622             if(lastParam + 1 != p)
2623             {
2624                strcat(className, param.name);
2625                strcat(className, " = ");
2626             }
2627             strcat(className, param.name);
2628             first = false;
2629             lastParam = p;
2630          }
2631          p++;
2632       }
2633       if(!first)
2634       {
2635          int len = strlen(className);
2636          if(className[len-1] == '>') className[len++] = ' ';
2637          className[len++] = '>';
2638          className[len++] = '\0';
2639       }
2640       type = MkClassType(className);
2641       //type = ProcessTypeString(className, false);
2642    }
2643    else
2644    {
2645       type = MkClassType(_class.fullName);
2646       //type = ProcessTypeString(_class.fullName, false);
2647    }
2648    //type.wasThisClass = true;
2649    return type;
2650 }
2651
2652 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2653 {
2654    if(specs != null && _class)
2655    {
2656       Specifier spec;
2657       for(spec = specs.first; spec; spec = spec.next)
2658       {
2659          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2660          {
2661             spec.type = nameSpecifier;
2662             spec.name = ReplaceThisClass(_class);
2663             spec.symbol = FindClass(spec.name); //_class.symbol;
2664          }
2665       }
2666    }
2667 }
2668
2669 // Returns imported or not
2670 bool DeclareFunction(External neededFor, GlobalFunction function, char * name)
2671 {
2672    Symbol symbol = function.symbol;
2673    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2674    if(!symbol || !symbol.pointerExternal)
2675    {
2676       bool imported = false;
2677       bool dllImport = false;
2678
2679       if(!function.dataType)
2680       {
2681          function.dataType = ProcessTypeString(function.dataTypeString, false);
2682          if(!function.dataType.thisClass)
2683             function.dataType.staticMethod = true;
2684       }
2685
2686       if(inCompiler)
2687       {
2688          if(!symbol)
2689          {
2690             ModuleImport module = FindModule(function.module);
2691             // WARNING: This is not added anywhere...
2692             symbol = function.symbol = Symbol {  };
2693
2694             if(module.name)
2695             {
2696                if(!function.dataType.dllExport)
2697                {
2698                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2699                   module.functions.Add(symbol._import);
2700                }
2701             }
2702             // Set the symbol type
2703             {
2704                symbol.type = ProcessTypeString(function.dataTypeString, false);
2705                if(!symbol.type.thisClass)
2706                   symbol.type.staticMethod = true;
2707             }
2708          }
2709          imported = symbol._import ? true : false;
2710          if(imported && function.module != privateModule && function.module.importType != staticImport)
2711             dllImport = true;
2712       }
2713
2714       if(inCompiler)
2715       {
2716          // TOCHECK: What's with the functionExternal check here? Is it Edge breaking / forward declaration?
2717          //if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2718          {
2719             // We need a declaration here :)
2720             Declaration decl;
2721             OldList * specifiers, * declarators;
2722             Declarator d;
2723             Declarator funcDecl;
2724             External external;
2725
2726             specifiers = MkList();
2727             declarators = MkList();
2728
2729             ListAdd(specifiers, MkSpecifier(EXTERN));
2730
2731             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2732             if(dllImport)
2733                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2734
2735             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2736             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2737             if(function.module.importType == staticImport)
2738             {
2739                Specifier spec;
2740                for(spec = specifiers->first; spec; spec = spec.next)
2741                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2742                   {
2743                      specifiers->Remove(spec);
2744                      FreeSpecifier(spec);
2745                      break;
2746                   }
2747             }
2748
2749             funcDecl = GetFuncDecl(d);
2750
2751             // Make sure we don't have empty parameter declarations for static methods...
2752             if(funcDecl && !funcDecl.function.parameters)
2753             {
2754                funcDecl.function.parameters = MkList();
2755                funcDecl.function.parameters->Insert(null,
2756                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2757             }
2758
2759             ListAdd(declarators, MkInitDeclarator(d, null));
2760
2761             {
2762                Context oldCtx = curContext;
2763                curContext = globalContext;
2764                decl = MkDeclaration(specifiers, declarators);
2765                curContext = oldCtx;
2766             }
2767
2768             // Keep a different symbol for the function definition than the declaration...
2769             /* Note: This should be handled by the edge breaking...
2770             if(symbol.pointerExternal && symbol.pointerExternal.type == functionExternal)
2771             {
2772                Symbol functionSymbol { };
2773                // Copy symbol
2774                {
2775                   *functionSymbol = *symbol;
2776                   functionSymbol.string = CopyString(symbol.string);
2777                   if(functionSymbol.type)
2778                      functionSymbol.type.refCount++;
2779                }
2780
2781                excludedSymbols->Add(functionSymbol);
2782
2783                symbol.pointerExternal.symbol = functionSymbol;
2784             }
2785             */
2786             external = MkExternalDeclaration(decl);
2787             ast->Add(external);
2788             external.symbol = symbol;
2789             symbol.pointerExternal = external;
2790
2791             DeclareType(external, function.dataType, true, true);
2792          }
2793       }
2794    }
2795    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2796       neededFor.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
2797    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2798 }
2799
2800 void DeclareGlobalData(External neededFor, GlobalData data)
2801 {
2802    Symbol symbol = data.symbol;
2803    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2804    if(!symbol || !symbol.pointerExternal)
2805    {
2806       if(inCompiler)
2807       {
2808          if(!symbol)
2809             symbol = data.symbol = Symbol { };
2810       }
2811       if(!data.dataType)
2812          data.dataType = ProcessTypeString(data.dataTypeString, false);
2813
2814       if(inCompiler)
2815       {
2816          // We need a declaration here :)
2817          Declaration decl;
2818          OldList * specifiers, * declarators;
2819          Declarator d;
2820          External external;
2821
2822          specifiers = MkList();
2823          declarators = MkList();
2824
2825          ListAdd(specifiers, MkSpecifier(EXTERN));
2826          d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2827          d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2828
2829          ListAdd(declarators, MkInitDeclarator(d, null));
2830
2831          decl = MkDeclaration(specifiers, declarators);
2832          external = MkExternalDeclaration(decl);
2833          if(curExternal)
2834             ast->Insert(curExternal.prev, external);
2835          external.symbol = symbol;
2836          symbol.pointerExternal = external;
2837
2838          DeclareType(external, data.dataType, true, true);
2839       }
2840    }
2841    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2842       neededFor.CreateUniqueEdge(symbol.pointerExternal, false);
2843 }
2844
2845 class Conversion : struct
2846 {
2847    Conversion prev, next;
2848    Property convert;
2849    bool isGet;
2850    Type resultType;
2851 };
2852
2853 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
2854 {
2855    bool status = true;
2856    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
2857       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
2858    {
2859       Class sourceClass = source.kind == classType ? source._class.registered : null;
2860       Class destClass = dest.kind == classType ? dest._class.registered : null;
2861       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
2862          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
2863       {
2864          Type sourceType = source, destType = dest;
2865          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
2866          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
2867          if(!destType.constant && sourceType.constant)
2868          {
2869             status = false;
2870             if(warn)
2871                Compiler_Warning($"discarding const qualifier\n");
2872          }
2873       }
2874    }
2875    return status;
2876 }
2877
2878 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
2879                        bool isConversionExploration, bool warnConst)
2880 {
2881    if(source && dest)
2882    {
2883       if(warnConst)
2884          CheckConstCompatibility(source, dest, true);
2885       // Property convert;
2886
2887       if(source.kind == templateType && dest.kind != templateType)
2888       {
2889          Type type = ProcessTemplateParameterType(source.templateParameter);
2890          if(type) source = type;
2891       }
2892
2893       if(dest.kind == templateType && source.kind != templateType)
2894       {
2895          Type type = ProcessTemplateParameterType(dest.templateParameter);
2896          if(type) dest = type;
2897       }
2898
2899       if(dest.classObjectType == typedObject && dest.kind != functionType)
2900       {
2901          if(source.classObjectType != anyObject)
2902             return true;
2903          else
2904          {
2905             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
2906             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
2907             {
2908                return true;
2909             }
2910          }
2911       }
2912       else
2913       {
2914          if(source.kind != functionType && source.classObjectType == anyObject)
2915             return true;
2916          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
2917             return true;
2918       }
2919
2920       if((dest.kind == structType && source.kind == structType) ||
2921          (dest.kind == unionType && source.kind == unionType))
2922       {
2923          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
2924              (source.members.first && source.members.first == dest.members.first))
2925             return true;
2926       }
2927
2928       if(dest.kind == ellipsisType && source.kind != voidType)
2929          return true;
2930
2931       if(dest.kind == pointerType && dest.type.kind == voidType &&
2932          ((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))
2933          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
2934
2935          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
2936
2937          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
2938          return true;
2939       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
2940          ((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))
2941          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
2942          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
2943
2944          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
2945          return true;
2946
2947       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
2948       {
2949          if(source._class.registered && source._class.registered.type == unitClass)
2950          {
2951             if(conversions != null)
2952             {
2953                if(source._class.registered == dest._class.registered)
2954                   return true;
2955             }
2956             else
2957             {
2958                Class sourceBase, destBase;
2959                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
2960                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
2961                if(sourceBase == destBase)
2962                   return true;
2963             }
2964          }
2965          // Don't match enum inheriting from other enum if resolving enumeration values
2966          // TESTING: !dest.classObjectType
2967          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
2968             (enumBaseType ||
2969                (!source._class.registered || source._class.registered.type != enumClass) ||
2970                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
2971             return true;
2972          else
2973          {
2974             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
2975             if(dest._class && dest._class.registered && source._class && source._class.registered &&
2976                (dest.casted || (enumBaseType && dest._class.registered.type == enumClass &&
2977                   (source.kind == classType ||  // Added this here for a base enum to be acceptable for a derived enum (#139)
2978                    source._class.registered.type != enumClass)
2979                 ) ) )
2980             {
2981                if(eClass_IsDerived(dest._class.registered, source._class.registered))
2982                {
2983                   return true;
2984                }
2985             }
2986          }
2987       }
2988
2989       // JUST ADDED THIS...
2990       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
2991          return true;
2992
2993       if(doConversion)
2994       {
2995          // Just added this for Straight conversion of ColorAlpha => Color
2996          if(source.kind == classType)
2997          {
2998             Class _class;
2999             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3000             {
3001                Property convert;
3002                for(convert = _class.conversions.first; convert; convert = convert.next)
3003                {
3004                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3005                   {
3006                      Conversion after = (conversions != null) ? conversions.last : null;
3007
3008                      if(!convert.dataType)
3009                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3010                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
3011                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3012                         MatchTypes(convert.dataType, dest, conversions, null, null,
3013                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
3014                               convert.dataType.kind == classType, false, true, warnConst))
3015                      {
3016                         if(!conversions && !convert.Get)
3017                            return true;
3018                         else if(conversions != null)
3019                         {
3020                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3021                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3022                               (dest.kind != classType || dest._class.registered != _class.base))
3023                               return true;
3024                            else
3025                            {
3026                               Conversion conv { convert = convert, isGet = true };
3027                               // conversions.Add(conv);
3028                               conversions.Insert(after, conv);
3029
3030                               return true;
3031                            }
3032                         }
3033                      }
3034                   }
3035                }
3036             }
3037          }
3038
3039          // MOVING THIS??
3040
3041          if(dest.kind == classType)
3042          {
3043             Class _class;
3044             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3045             {
3046                Property convert;
3047                for(convert = _class.conversions.first; convert; convert = convert.next)
3048                {
3049                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3050                   {
3051                      Type constType = null;
3052                      bool success = false;
3053                      // Conversion after = (conversions != null) ? conversions.last : null;
3054
3055                      if(!convert.dataType)
3056                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3057
3058                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3059                      {
3060                         Type ptrType { };
3061                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3062                         CopyTypeInto(ptrType, convert.dataType.type);
3063                         ptrType.constant = true;
3064                      }
3065
3066                      // Just added this equality check to prevent recursion.... Make it safer?
3067                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3068                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3069                      {
3070                         if(!conversions && !convert.Set)
3071                            success = true;
3072                         else if(conversions != null)
3073                         {
3074                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3075                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3076                               (source.kind != classType || source._class.registered != _class.base))
3077                               success = true;
3078                            else
3079                            {
3080                               // *** Testing this! ***
3081                               Conversion conv { convert = convert };
3082                               conversions.Add(conv);
3083                               //conversions.Insert(after, conv);
3084                               success = true;
3085                            }
3086                         }
3087                      }
3088                      if(constType)
3089                         FreeType(constType);
3090                      if(success)
3091                         return true;
3092                   }
3093                }
3094             }
3095             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3096             {
3097                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3098                   (source.kind != classType || source._class.registered.type != structClass))
3099                   return true;
3100             }*/
3101
3102             // TESTING THIS... IS THIS OK??
3103             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3104             {
3105                if(!dest._class.registered.dataType)
3106                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3107                // Only support this for classes...
3108                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3109                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3110                {
3111                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3112                   {
3113                      return true;
3114                   }
3115                }
3116             }
3117          }
3118
3119          // Moved this lower
3120          if(source.kind == classType)
3121          {
3122             Class _class;
3123             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3124             {
3125                Property convert;
3126                for(convert = _class.conversions.first; convert; convert = convert.next)
3127                {
3128                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3129                   {
3130                      Conversion after = (conversions != null) ? conversions.last : null;
3131
3132                      if(!convert.dataType)
3133                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3134                      if(convert.dataType != source &&
3135                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3136                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3137                      {
3138                         if(!conversions && !convert.Get)
3139                            return true;
3140                         else if(conversions != null)
3141                         {
3142                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3143                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3144                               (dest.kind != classType || dest._class.registered != _class.base))
3145                               return true;
3146                            else
3147                            {
3148                               Conversion conv { convert = convert, isGet = true };
3149
3150                               // conversions.Add(conv);
3151                               conversions.Insert(after, conv);
3152                               return true;
3153                            }
3154                         }
3155                      }
3156                   }
3157                }
3158             }
3159
3160             // TESTING THIS... IS THIS OK??
3161             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3162             {
3163                if(!source._class.registered.dataType)
3164                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3165                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3166                {
3167                   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))
3168                      return true;
3169                   // For bool to be accepted by byte, short, etc.
3170                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3171                      return true;
3172                }
3173             }
3174          }
3175       }
3176
3177       if(source.kind == classType || source.kind == subClassType)
3178          ;
3179       else if(dest.kind == source.kind &&
3180          (dest.kind != structType && dest.kind != unionType &&
3181           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3182           return true;
3183       // RECENTLY ADDED THESE
3184       else if(dest.kind == doubleType && source.kind == floatType)
3185          return true;
3186       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3187          return true;
3188       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3189          return true;
3190       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3191          return true;
3192       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3193          return true;
3194       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3195          return true;
3196       else if(source.kind == enumType &&
3197          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3198           return true;
3199       else if(dest.kind == enumType && !isConversionExploration &&
3200          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3201           return true;
3202       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3203               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3204       {
3205          Type paramSource, paramDest;
3206
3207          if(dest.kind == methodType)
3208             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3209          if(source.kind == methodType)
3210             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3211
3212          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3213          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3214          if(dest.kind == methodType)
3215             dest = dest.method.dataType;
3216          if(source.kind == methodType)
3217             source = source.method.dataType;
3218
3219          paramSource = source.params.first;
3220          if(paramSource && paramSource.kind == voidType) paramSource = null;
3221          paramDest = dest.params.first;
3222          if(paramDest && paramDest.kind == voidType) paramDest = null;
3223
3224
3225          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3226             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3227          {
3228             // Source thisClass must be derived from destination thisClass
3229             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3230                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3231             {
3232                if(paramDest && paramDest.kind == classType)
3233                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3234                else
3235                   Compiler_Error($"method class should not take an object\n");
3236                return false;
3237             }
3238             paramDest = paramDest.next;
3239          }
3240          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3241          {
3242             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3243             {
3244                if(dest.thisClass)
3245                {
3246                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3247                   {
3248                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3249                      return false;
3250                   }
3251                }
3252                else
3253                {
3254                   // THIS WAS BACKWARDS:
3255                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3256                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3257                   {
3258                      if(owningClassDest)
3259                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3260                      else
3261                         Compiler_Error($"overriding class expected to be derived from method class\n");
3262                      return false;
3263                   }
3264                }
3265                paramSource = paramSource.next;
3266             }
3267             else
3268             {
3269                if(dest.thisClass)
3270                {
3271                   // Source thisClass must be derived from destination thisClass
3272                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3273                   {
3274                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3275                      return false;
3276                   }
3277                }
3278                else
3279                {
3280                   // THIS WAS BACKWARDS TOO??
3281                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3282                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3283                   {
3284                      //if(owningClass)
3285                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3286                      //else
3287                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3288                      return false;
3289                   }
3290                }
3291             }
3292          }
3293
3294
3295          // Source return type must be derived from destination return type
3296          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3297          {
3298             Compiler_Warning($"incompatible return type for function\n");
3299             return false;
3300          }
3301          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3302          else
3303             CheckConstCompatibility(dest.returnType, source.returnType, true);
3304
3305          // Check parameters
3306
3307          for(; paramDest; paramDest = paramDest.next)
3308          {
3309             if(!paramSource)
3310             {
3311                //Compiler_Warning($"not enough parameters\n");
3312                Compiler_Error($"not enough parameters\n");
3313                return false;
3314             }
3315             {
3316                Type paramDestType = paramDest;
3317                Type paramSourceType = paramSource;
3318                Type type = paramDestType;
3319
3320                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3321                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3322                   paramSource.kind != templateType)
3323                {
3324                   int id = 0;
3325                   ClassTemplateParameter curParam = null;
3326                   Class sClass;
3327                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3328                   {
3329                      id = 0;
3330                      if(sClass.templateClass) sClass = sClass.templateClass;
3331                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3332                      {
3333                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3334                         {
3335                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3336                            {
3337                               if(sClass.templateClass) sClass = sClass.templateClass;
3338                               id += sClass.templateParams.count;
3339                            }
3340                            break;
3341                         }
3342                         id++;
3343                      }
3344                      if(curParam) break;
3345                   }
3346
3347                   if(curParam)
3348                   {
3349                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3350                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3351                   }
3352                }
3353
3354                // paramDest must be derived from paramSource
3355                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3356                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3357                {
3358                   char type[1024];
3359                   type[0] = 0;
3360                   PrintType(paramDest, type, false, true);
3361                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3362
3363                   if(paramDestType != paramDest)
3364                      FreeType(paramDestType);
3365                   return false;
3366                }
3367                if(paramDestType != paramDest)
3368                   FreeType(paramDestType);
3369             }
3370
3371             paramSource = paramSource.next;
3372          }
3373          if(paramSource)
3374          {
3375             Compiler_Error($"too many parameters\n");
3376             return false;
3377          }
3378          return true;
3379       }
3380       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3381       {
3382          return true;
3383       }
3384       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3385          (source.kind == arrayType || source.kind == pointerType))
3386       {
3387          // Pointers to pointer is incompatible with non normal/nohead classes
3388          if(!(dest.type && dest.type.kind == pointerType && source.type.kind == classType && source.type._class &&
3389             source.type._class.registered && (source.type._class.registered.type != normalClass && source.type._class.registered.type != noHeadClass) && !source.type.byReference))
3390          {
3391             ComputeTypeSize(source.type);
3392             ComputeTypeSize(dest.type);
3393             if(source.type.size == dest.type.size && MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3394                return true;
3395          }
3396       }
3397    }
3398    return false;
3399 }
3400
3401 static void FreeConvert(Conversion convert)
3402 {
3403    if(convert.resultType)
3404       FreeType(convert.resultType);
3405 }
3406
3407 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3408                               char * string, OldList conversions)
3409 {
3410    BTNamedLink link;
3411
3412    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3413    {
3414       Class _class = link.data;
3415       if(_class.type == enumClass)
3416       {
3417          OldList converts { };
3418          Type type { };
3419          type.kind = classType;
3420
3421          if(!_class.symbol)
3422             _class.symbol = FindClass(_class.fullName);
3423          type._class = _class.symbol;
3424
3425          if(MatchTypes(type, dest, &converts, null, null, dest.kind != classType || !dest._class || strcmp(dest._class.string, "bool"),
3426                false, false, false, false))
3427          {
3428             NamedLink64 value;
3429             Class enumClass = eSystem_FindClass(privateModule, "enum");
3430             if(enumClass)
3431             {
3432                Class baseClass;
3433                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3434                {
3435                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3436                   for(value = e.values.first; value; value = value.next)
3437                   {
3438                      if(!strcmp(value.name, string))
3439                         break;
3440                   }
3441                   if(value)
3442                   {
3443                      FreeType(sourceExp.expType);
3444
3445                      sourceExp.isConstant = true;
3446                      sourceExp.expType = MkClassType(baseClass.fullName);
3447                      if(inCompiler || inPreCompiler || inDebugger)
3448                      {
3449                         char constant[256];
3450                         FreeExpContents(sourceExp);
3451
3452                         sourceExp.type = constantExp;
3453                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3454                            sprintf(constant, FORMAT64D, value.data);
3455                         else
3456                            sprintf(constant, FORMAT64HEXLL, value.data);
3457                         sourceExp.constant = CopyString(constant);
3458                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3459                      }
3460
3461                      while(converts.first)
3462                      {
3463                         Conversion convert = converts.first;
3464                         converts.Remove(convert);
3465                         conversions.Add(convert);
3466                      }
3467                      delete type;
3468                      return true;
3469                   }
3470                }
3471             }
3472          }
3473          if(converts.first)
3474             converts.Free(FreeConvert);
3475          delete type;
3476       }
3477    }
3478    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3479       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3480          return true;
3481    return false;
3482 }
3483
3484 public bool ModuleVisibility(Module searchIn, Module searchFor)
3485 {
3486    SubModule subModule;
3487
3488    if(searchFor == searchIn)
3489       return true;
3490
3491    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3492    {
3493       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3494       {
3495          if(ModuleVisibility(subModule.module, searchFor))
3496             return true;
3497       }
3498    }
3499    return false;
3500 }
3501
3502 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3503 {
3504    Module module;
3505
3506    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3507       return true;
3508    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3509       return true;
3510    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3511       return true;
3512
3513    for(module = mainModule.application.allModules.first; module; module = module.next)
3514    {
3515       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3516          return true;
3517    }
3518    return false;
3519 }
3520
3521 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3522 {
3523    Type source;
3524    Type realDest = dest;
3525    Type backupSourceExpType = null;
3526    Expression nbExp = GetNonBracketsExp(sourceExp);
3527    Expression computedExp = nbExp;
3528    dest.refCount++;
3529
3530    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3531       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3532    {
3533       computedExp = CopyExpression(nbExp);        // Keep the original expression, but compute for checking enum ranges
3534       ComputeExpression(computedExp /*sourceExp*/);
3535    }
3536
3537    source = sourceExp.expType;
3538
3539    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3540    {
3541       if(computedExp != nbExp)
3542       {
3543          FreeExpression(computedExp);
3544          computedExp = nbExp;
3545       }
3546       FreeType(dest);
3547       return true;
3548    }
3549
3550    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3551    {
3552        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3553        {
3554           Class sourceBase, destBase;
3555           for(sourceBase = source._class.registered;
3556               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3557               sourceBase = sourceBase.base);
3558           for(destBase = dest._class.registered;
3559               destBase && destBase.base && destBase.base.type != systemClass;
3560               destBase = destBase.base);
3561           //if(source._class.registered == dest._class.registered)
3562           if(sourceBase == destBase)
3563           {
3564             if(computedExp != nbExp)
3565             {
3566                FreeExpression(computedExp);
3567                computedExp = nbExp;
3568             }
3569             FreeType(dest);
3570             return true;
3571          }
3572       }
3573    }
3574
3575    if(source)
3576    {
3577       OldList * specs;
3578       bool flag = false;
3579       int64 value = MAXINT;
3580
3581       source.refCount++;
3582
3583       if(computedExp.type == constantExp)
3584       {
3585          if(source.isSigned)
3586             value = strtoll(computedExp.constant, null, 0);
3587          else
3588             value = strtoull(computedExp.constant, null, 0);
3589       }
3590       else if(computedExp.type == opExp && computedExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3591       {
3592          if(source.isSigned)
3593             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3594          else
3595             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3596       }
3597       if(computedExp != nbExp)
3598       {
3599          FreeExpression(computedExp);
3600          computedExp = nbExp;
3601       }
3602
3603       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3604          !strcmp(source._class.registered.fullName, "unichar" /*"ecere::com::unichar"*/))
3605       {
3606          FreeType(source);
3607          source = Type { kind = intType, isSigned = false, refCount = 1 };
3608       }
3609
3610       if(dest.kind == classType)
3611       {
3612          Class _class = dest._class ? dest._class.registered : null;
3613
3614          if(_class && _class.type == unitClass)
3615          {
3616             if(source.kind != classType)
3617             {
3618                Type tempType { };
3619                Type tempDest, tempSource;
3620
3621                for(; _class.base.type != systemClass; _class = _class.base);
3622                tempSource = dest;
3623                tempDest = tempType;
3624
3625                tempType.kind = classType;
3626                if(!_class.symbol)
3627                   _class.symbol = FindClass(_class.fullName);
3628
3629                tempType._class = _class.symbol;
3630                tempType.truth = dest.truth;
3631                if(tempType._class)
3632                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3633
3634                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3635                backupSourceExpType = sourceExp.expType;
3636                if(dest.passAsTemplate)
3637                {
3638                   // Don't carry passAsTemplate
3639                   sourceExp.expType = { };
3640                   CopyTypeInto(sourceExp.expType, dest);
3641                   sourceExp.expType.passAsTemplate = false;
3642                }
3643                else
3644                {
3645                   sourceExp.expType = dest;
3646                   dest.refCount++;
3647                }
3648                //sourceExp.expType = MkClassType(_class.fullName);
3649                flag = true;
3650
3651                delete tempType;
3652             }
3653          }
3654
3655
3656          // Why wasn't there something like this?
3657          if(_class && _class.type == bitClass && source.kind != classType)
3658          {
3659             if(!dest._class.registered.dataType)
3660                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3661             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3662             {
3663                FreeType(source);
3664                FreeType(sourceExp.expType);
3665                source = sourceExp.expType = MkClassType(dest._class.string);
3666                source.refCount++;
3667
3668                //source.kind = classType;
3669                //source._class = dest._class;
3670             }
3671          }
3672
3673          // Adding two enumerations
3674          /*
3675          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3676          {
3677             if(!source._class.registered.dataType)
3678                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3679             if(!dest._class.registered.dataType)
3680                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3681
3682             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3683             {
3684                FreeType(source);
3685                source = sourceExp.expType = MkClassType(dest._class.string);
3686                source.refCount++;
3687
3688                //source.kind = classType;
3689                //source._class = dest._class;
3690             }
3691          }*/
3692
3693          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3694          {
3695             OldList * specs = MkList();
3696             Declarator decl;
3697             char string[1024];
3698
3699             ReadString(string, sourceExp.string);
3700             decl = SpecDeclFromString(string, specs, null);
3701
3702             FreeExpContents(sourceExp);
3703             FreeType(sourceExp.expType);
3704
3705             sourceExp.type = classExp;
3706             sourceExp._classExp.specifiers = specs;
3707             sourceExp._classExp.decl = decl;
3708             sourceExp.expType = dest;
3709             dest.refCount++;
3710
3711             FreeType(source);
3712             FreeType(dest);
3713             if(backupSourceExpType) FreeType(backupSourceExpType);
3714             return true;
3715          }
3716       }
3717       else if(source.kind == classType)
3718       {
3719          Class _class = source._class ? source._class.registered : null;
3720
3721          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || _class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3722          {
3723             /*
3724             if(dest.kind != classType)
3725             {
3726                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3727                if(!source._class.registered.dataType)
3728                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3729
3730                FreeType(dest);
3731                dest = MkClassType(source._class.string);
3732                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3733                //   dest = MkClassType(source._class.string);
3734             }
3735             */
3736
3737             if(dest.kind != classType)
3738             {
3739                Type tempType { };
3740                Type tempDest, tempSource;
3741
3742                if(!source._class.registered.dataType)
3743                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3744
3745                for(; _class.base.type != systemClass; _class = _class.base);
3746                tempDest = source;
3747                tempSource = tempType;
3748                tempType.kind = classType;
3749                tempType._class = FindClass(_class.fullName);
3750                tempType.truth = source.truth;
3751                tempType.classObjectType = source.classObjectType;
3752
3753                if(tempType._class)
3754                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3755
3756                // PUT THIS BACK TESTING UNITS?
3757                if(conversions && conversions.last)
3758                {
3759                   ((Conversion)(conversions.last)).resultType = dest;
3760                   dest.refCount++;
3761                }
3762
3763                FreeType(sourceExp.expType);
3764                sourceExp.expType = MkClassType(_class.fullName);
3765                sourceExp.expType.truth = source.truth;
3766                sourceExp.expType.classObjectType = source.classObjectType;
3767
3768                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3769
3770                if(!sourceExp.destType)
3771                {
3772                   FreeType(sourceExp.destType);
3773                   sourceExp.destType = sourceExp.expType;
3774                   if(sourceExp.expType)
3775                      sourceExp.expType.refCount++;
3776                }
3777                //flag = true;
3778                //source = _class.dataType;
3779
3780
3781                // TOCHECK: TESTING THIS NEW CODE
3782                if(!_class.dataType)
3783                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3784                FreeType(dest);
3785                dest = MkClassType(source._class.string);
3786                dest.truth = source.truth;
3787                dest.classObjectType = source.classObjectType;
3788
3789                FreeType(source);
3790                source = _class.dataType;
3791                source.refCount++;
3792
3793                delete tempType;
3794             }
3795          }
3796       }
3797
3798       if(!flag)
3799       {
3800          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3801          {
3802             FreeType(source);
3803             FreeType(dest);
3804             return true;
3805          }
3806       }
3807
3808       // Implicit Casts
3809       /*
3810       if(source.kind == classType)
3811       {
3812          Class _class = source._class.registered;
3813          if(_class.type == unitClass)
3814          {
3815             if(!_class.dataType)
3816                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3817             source = _class.dataType;
3818          }
3819       }*/
3820
3821       if(dest.kind == classType)
3822       {
3823          Class _class = dest._class ? dest._class.registered : null;
3824          bool fittingValue = false;
3825          if(_class && _class.type == enumClass)
3826          {
3827             Class enumClass = eSystem_FindClass(privateModule, "enum");
3828             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3829             if(c && value >= 0 && value <= c.largest)
3830                fittingValue = true;
3831          }
3832
3833          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3834             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3835          {
3836             if(_class.type == normalClass || _class.type == noHeadClass)
3837             {
3838                Expression newExp { };
3839                *newExp = *sourceExp;
3840                if(sourceExp.destType) sourceExp.destType.refCount++;
3841                if(sourceExp.expType)  sourceExp.expType.refCount++;
3842                sourceExp.type = castExp;
3843                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3844                sourceExp.cast.exp = newExp;
3845                FreeType(sourceExp.expType);
3846                sourceExp.expType = null;
3847                ProcessExpressionType(sourceExp);
3848
3849                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3850                if(!inCompiler)
3851                {
3852                   FreeType(sourceExp.expType);
3853                   sourceExp.expType = dest;
3854                }
3855
3856                FreeType(source);
3857                if(inCompiler) FreeType(dest);
3858
3859                if(backupSourceExpType) FreeType(backupSourceExpType);
3860                return true;
3861             }
3862
3863             if(!_class.dataType)
3864                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3865             FreeType(dest);
3866             dest = _class.dataType;
3867             dest.refCount++;
3868          }
3869
3870          // Accept lower precision types for units, since we want to keep the unit type
3871          if(dest.kind == doubleType &&
3872             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3873              source.kind == charType || source.kind == _BoolType))
3874          {
3875             specs = MkListOne(MkSpecifier(DOUBLE));
3876          }
3877          else if(dest.kind == floatType &&
3878             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3879             source.kind == _BoolType || source.kind == doubleType))
3880          {
3881             specs = MkListOne(MkSpecifier(FLOAT));
3882          }
3883          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3884             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3885          {
3886             specs = MkList();
3887             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3888             ListAdd(specs, MkSpecifier(INT64));
3889          }
3890          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
3891             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3892          {
3893             specs = MkList();
3894             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3895             ListAdd(specs, MkSpecifier(INT));
3896          }
3897          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
3898             source.kind == floatType || source.kind == doubleType))
3899          {
3900             specs = MkList();
3901             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3902             ListAdd(specs, MkSpecifier(SHORT));
3903          }
3904          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
3905             source.kind == floatType || source.kind == doubleType))
3906          {
3907             specs = MkList();
3908             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3909             ListAdd(specs, MkSpecifier(CHAR));
3910          }
3911          else
3912          {
3913             FreeType(source);
3914             FreeType(dest);
3915             if(backupSourceExpType)
3916             {
3917                // Failed to convert: revert previous exp type
3918                if(sourceExp.expType) FreeType(sourceExp.expType);
3919                sourceExp.expType = backupSourceExpType;
3920             }
3921             return false;
3922          }
3923       }
3924       else if(dest.kind == doubleType &&
3925          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
3926           source.kind == _BoolType || source.kind == charType))
3927       {
3928          specs = MkListOne(MkSpecifier(DOUBLE));
3929       }
3930       else if(dest.kind == floatType &&
3931          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3932       {
3933          specs = MkListOne(MkSpecifier(FLOAT));
3934       }
3935       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3936          (value == 1 || value == 0))
3937       {
3938          specs = MkList();
3939          ListAdd(specs, MkSpecifier(BOOL));
3940       }
3941       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3942          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
3943       {
3944          if(source.kind == intType)
3945          {
3946             FreeType(dest);
3947             FreeType(source);
3948             if(backupSourceExpType) FreeType(backupSourceExpType);
3949             return true;
3950          }
3951          else
3952          {
3953             specs = MkList();
3954             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3955             ListAdd(specs, MkSpecifier(CHAR));
3956          }
3957       }
3958       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
3959          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
3960       {
3961          if(source.kind == intType)
3962          {
3963             FreeType(dest);
3964             FreeType(source);
3965             if(backupSourceExpType) FreeType(backupSourceExpType);
3966             return true;
3967          }
3968          else
3969          {
3970             specs = MkList();
3971             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3972             ListAdd(specs, MkSpecifier(SHORT));
3973          }
3974       }
3975       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
3976       {
3977          specs = MkList();
3978          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3979          ListAdd(specs, MkSpecifier(INT));
3980       }
3981       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
3982       {
3983          specs = MkList();
3984          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3985          ListAdd(specs, MkSpecifier(INT64));
3986       }
3987       else if(dest.kind == enumType &&
3988          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3989       {
3990          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
3991       }
3992       else
3993       {
3994          FreeType(source);
3995          FreeType(dest);
3996          if(backupSourceExpType)
3997          {
3998             // Failed to convert: revert previous exp type
3999             if(sourceExp.expType) FreeType(sourceExp.expType);
4000             sourceExp.expType = backupSourceExpType;
4001          }
4002          return false;
4003       }
4004
4005       if(!flag && !sourceExp.opDestType)
4006       {
4007          Expression newExp { };
4008          *newExp = *sourceExp;
4009          newExp.prev = null;
4010          newExp.next = null;
4011          if(sourceExp.destType) sourceExp.destType.refCount++;
4012          if(sourceExp.expType)  sourceExp.expType.refCount++;
4013
4014          sourceExp.type = castExp;
4015          if(realDest.kind == classType)
4016          {
4017             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
4018             FreeList(specs, FreeSpecifier);
4019          }
4020          else
4021             sourceExp.cast.typeName = MkTypeName(specs, null);
4022          if(newExp.type == opExp)
4023          {
4024             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
4025          }
4026          else
4027             sourceExp.cast.exp = newExp;
4028
4029          FreeType(sourceExp.expType);
4030          sourceExp.expType = null;
4031          ProcessExpressionType(sourceExp);
4032       }
4033       else
4034          FreeList(specs, FreeSpecifier);
4035
4036       FreeType(dest);
4037       FreeType(source);
4038       if(backupSourceExpType) FreeType(backupSourceExpType);
4039
4040       return true;
4041    }
4042    else
4043    {
4044       if(computedExp != nbExp)
4045       {
4046          FreeExpression(computedExp);
4047          computedExp = nbExp;
4048       }
4049
4050       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4051       if(sourceExp.type == identifierExp)
4052       {
4053          Identifier id = sourceExp.identifier;
4054          if(dest.kind == classType)
4055          {
4056             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4057             {
4058                Class _class = dest._class.registered;
4059                Class enumClass = eSystem_FindClass(privateModule, "enum");
4060                if(enumClass)
4061                {
4062                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4063                   {
4064                      NamedLink64 value;
4065                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4066                      for(value = e.values.first; value; value = value.next)
4067                      {
4068                         if(!strcmp(value.name, id.string))
4069                            break;
4070                      }
4071                      if(value)
4072                      {
4073                         FreeType(sourceExp.expType);
4074
4075                         sourceExp.isConstant = true;
4076                         sourceExp.expType = MkClassType(_class.fullName);
4077                         if(inCompiler || inPreCompiler || inDebugger)
4078                         {
4079                            FreeExpContents(sourceExp);
4080
4081                            sourceExp.type = constantExp;
4082                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4083                               sourceExp.constant = PrintInt64(value.data);
4084                            else
4085                               sourceExp.constant = PrintUInt64(value.data);
4086                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4087                         }
4088                         FreeType(dest);
4089                         return true;
4090                      }
4091                   }
4092                }
4093             }
4094          }
4095
4096          // Loop through all enum classes
4097          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4098          {
4099             FreeType(dest);
4100             return true;
4101          }
4102       }
4103       FreeType(dest);
4104    }
4105    return false;
4106 }
4107
4108 #define TERTIARY(o, name, m, t, p) \
4109    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4110    {                                                              \
4111       exp.type = constantExp;                                    \
4112       exp.string = p(op1.m ? op2.m : op3.m);                     \
4113       if(!exp.expType) \
4114          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4115       return true;                                                \
4116    }
4117
4118 #define BINARY(o, name, m, t, p) \
4119    static bool name(Expression exp, Operand op1, Operand op2)   \
4120    {                                                              \
4121       t value2 = op2.m;                                           \
4122       exp.type = constantExp;                                    \
4123       exp.string = p((t)(op1.m o value2));                     \
4124       if(!exp.expType) \
4125          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4126       return true;                                                \
4127    }
4128
4129 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4130    static bool name(Expression exp, Operand op1, Operand op2)   \
4131    {                                                              \
4132       t value2 = op2.m;                                           \
4133       exp.type = constantExp;                                    \
4134       exp.string = p(value2 ? ((t)(op1.m o value2)) : 0);             \
4135       if(!exp.expType) \
4136          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4137       return true;                                                \
4138    }
4139
4140 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4141    static bool name(Expression exp, Operand op1, Operand op2)   \
4142    {                                                              \
4143       t value2 = op2.m;                                           \
4144       exp.type = constantExp;                                    \
4145       exp.string = p((t)(op1.m o value2));             \
4146       if(!exp.expType) \
4147          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4148       return true;                                                \
4149    }
4150
4151 #define UNARY(o, name, m, t, p) \
4152    static bool name(Expression exp, Operand op1)                \
4153    {                                                              \
4154       exp.type = constantExp;                                    \
4155       exp.string = p((t)(o op1.m));                                   \
4156       if(!exp.expType) \
4157          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4158       return true;                                                \
4159    }
4160
4161 #define OPERATOR_ALL(macro, o, name) \
4162    macro(o, Int##name, i, int, PrintInt) \
4163    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4164    macro(o, Int64##name, i64, int64, PrintInt64) \
4165    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4166    macro(o, Short##name, s, short, PrintShort) \
4167    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4168    macro(o, Char##name, c, char, PrintChar) \
4169    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4170    macro(o, Float##name, f, float, PrintFloat) \
4171    macro(o, Double##name, d, double, PrintDouble)
4172
4173 #define OPERATOR_INTTYPES(macro, o, name) \
4174    macro(o, Int##name, i, int, PrintInt) \
4175    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4176    macro(o, Int64##name, i64, int64, PrintInt64) \
4177    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4178    macro(o, Short##name, s, short, PrintShort) \
4179    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4180    macro(o, Char##name, c, char, PrintChar) \
4181    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4182
4183 #define OPERATOR_REALTYPES(macro, o, name) \
4184    macro(o, Float##name, f, float, PrintFloat) \
4185    macro(o, Double##name, d, double, PrintDouble)
4186
4187 // binary arithmetic
4188 OPERATOR_ALL(BINARY, +, Add)
4189 OPERATOR_ALL(BINARY, -, Sub)
4190 OPERATOR_ALL(BINARY, *, Mul)
4191 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4192 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4193 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4194
4195 // unary arithmetic
4196 OPERATOR_ALL(UNARY, -, Neg)
4197
4198 // unary arithmetic increment and decrement
4199 OPERATOR_ALL(UNARY, ++, Inc)
4200 OPERATOR_ALL(UNARY, --, Dec)
4201
4202 // binary arithmetic assignment
4203 OPERATOR_ALL(BINARY, =, Asign)
4204 OPERATOR_ALL(BINARY, +=, AddAsign)
4205 OPERATOR_ALL(BINARY, -=, SubAsign)
4206 OPERATOR_ALL(BINARY, *=, MulAsign)
4207 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4208 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4209 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4210
4211 // binary bitwise
4212 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4213 OPERATOR_INTTYPES(BINARY, |, BitOr)
4214 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4215 OPERATOR_INTTYPES(BINARY, <<, LShift)
4216 OPERATOR_INTTYPES(BINARY, >>, RShift)
4217
4218 // unary bitwise
4219 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4220
4221 // binary bitwise assignment
4222 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4223 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4224 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4225 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4226 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4227
4228 // unary logical negation
4229 OPERATOR_INTTYPES(UNARY, !, Not)
4230
4231 // binary logical equality
4232 OPERATOR_ALL(BINARY, ==, Equ)
4233 OPERATOR_ALL(BINARY, !=, Nqu)
4234
4235 // binary logical
4236 OPERATOR_ALL(BINARY, &&, And)
4237 OPERATOR_ALL(BINARY, ||, Or)
4238
4239 // binary logical relational
4240 OPERATOR_ALL(BINARY, >, Grt)
4241 OPERATOR_ALL(BINARY, <, Sma)
4242 OPERATOR_ALL(BINARY, >=, GrtEqu)
4243 OPERATOR_ALL(BINARY, <=, SmaEqu)
4244
4245 // tertiary condition operator
4246 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4247
4248 //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
4249 #define OPERATOR_TABLE_ALL(name, type) \
4250     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4251                           type##Neg, \
4252                           type##Inc, type##Dec, \
4253                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4254                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4255                           type##BitNot, \
4256                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4257                           type##Not, \
4258                           type##Equ, type##Nqu, \
4259                           type##And, type##Or, \
4260                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4261                         }; \
4262
4263 #define OPERATOR_TABLE_INTTYPES(name, type) \
4264     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4265                           type##Neg, \
4266                           type##Inc, type##Dec, \
4267                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4268                           null, null, null, null, null, \
4269                           null, \
4270                           null, null, null, null, null, \
4271                           null, \
4272                           type##Equ, type##Nqu, \
4273                           type##And, type##Or, \
4274                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4275                         }; \
4276
4277 OPERATOR_TABLE_ALL(int, Int)
4278 OPERATOR_TABLE_ALL(uint, UInt)
4279 OPERATOR_TABLE_ALL(int64, Int64)
4280 OPERATOR_TABLE_ALL(uint64, UInt64)
4281 OPERATOR_TABLE_ALL(short, Short)
4282 OPERATOR_TABLE_ALL(ushort, UShort)
4283 OPERATOR_TABLE_INTTYPES(float, Float)
4284 OPERATOR_TABLE_INTTYPES(double, Double)
4285 OPERATOR_TABLE_ALL(char, Char)
4286 OPERATOR_TABLE_ALL(uchar, UChar)
4287
4288 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4289 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4290 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4291 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4292 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4293 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4294 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4295 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4296
4297 public void ReadString(char * output,  char * string)
4298 {
4299    int len = strlen(string);
4300    int c,d = 0;
4301    bool quoted = false, escaped = false;
4302    for(c = 0; c<len; c++)
4303    {
4304       char ch = string[c];
4305       if(escaped)
4306       {
4307          switch(ch)
4308          {
4309             case 'n': output[d] = '\n'; break;
4310             case 't': output[d] = '\t'; break;
4311             case 'a': output[d] = '\a'; break;
4312             case 'b': output[d] = '\b'; break;
4313             case 'f': output[d] = '\f'; break;
4314             case 'r': output[d] = '\r'; break;
4315             case 'v': output[d] = '\v'; break;
4316             case '\\': output[d] = '\\'; break;
4317             case '\"': output[d] = '\"'; break;
4318             case '\'': output[d] = '\''; break;
4319             default: output[d] = ch;
4320          }
4321          d++;
4322          escaped = false;
4323       }
4324       else
4325       {
4326          if(ch == '\"')
4327             quoted ^= true;
4328          else if(quoted)
4329          {
4330             if(ch == '\\')
4331                escaped = true;
4332             else
4333                output[d++] = ch;
4334          }
4335       }
4336    }
4337    output[d] = '\0';
4338 }
4339
4340 // String Unescape Copy
4341
4342 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4343 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4344 public int UnescapeString(char * d, char * s, int len)
4345 {
4346    int j = 0, k = 0;
4347    char ch;
4348    while(j < len && (ch = s[j]))
4349    {
4350       switch(ch)
4351       {
4352          case '\\':
4353             switch((ch = s[++j]))
4354             {
4355                case 'n': d[k] = '\n'; break;
4356                case 't': d[k] = '\t'; break;
4357                case 'a': d[k] = '\a'; break;
4358                case 'b': d[k] = '\b'; break;
4359                case 'f': d[k] = '\f'; break;
4360                case 'r': d[k] = '\r'; break;
4361                case 'v': d[k] = '\v'; break;
4362                case '\\': d[k] = '\\'; break;
4363                case '\"': d[k] = '\"'; break;
4364                case '\'': d[k] = '\''; break;
4365                default: d[k] = '\\'; d[k] = ch;
4366             }
4367             break;
4368          default:
4369             d[k] = ch;
4370       }
4371       j++, k++;
4372    }
4373    d[k] = '\0';
4374    return k;
4375 }
4376
4377 public char * OffsetEscapedString(char * s, int len, int offset)
4378 {
4379    char ch;
4380    int j = 0, k = 0;
4381    while(j < len && k < offset && (ch = s[j]))
4382    {
4383       if(ch == '\\') ++j;
4384       j++, k++;
4385    }
4386    return (k == offset) ? s + j : null;
4387 }
4388
4389 public Operand GetOperand(Expression exp)
4390 {
4391    Operand op { };
4392    Type type = exp.expType;
4393    if(type)
4394    {
4395       while(type.kind == classType && type._class &&
4396          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4397       {
4398          if(!type._class.registered.dataType)
4399             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4400          type = type._class.registered.dataType;
4401
4402       }
4403       if(exp.type == stringExp && op.kind == pointerType)
4404       {
4405          op.ui64 = (uint64)(uintptr)exp.string;
4406          op.kind = pointerType;
4407          op.ops = uint64Ops;
4408       }
4409       else if(exp.isConstant && exp.type == constantExp)
4410       {
4411          op.kind = type.kind;
4412          op.type = type;
4413
4414          switch(op.kind)
4415          {
4416             case _BoolType:
4417             case charType:
4418             {
4419                if(exp.constant[0] == '\'')
4420                {
4421                   op.c = exp.constant[1];
4422                   op.ops = charOps;
4423                }
4424                else if(type.isSigned)
4425                {
4426                   op.c = (char)strtol(exp.constant, null, 0);
4427                   op.ops = charOps;
4428                }
4429                else
4430                {
4431                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4432                   op.ops = ucharOps;
4433                }
4434                break;
4435             }
4436             case shortType:
4437                if(exp.constant[0] == '\'')
4438                {
4439                   op.s = exp.constant[1];
4440                   op.ops = shortOps;
4441                }
4442                else if(type.isSigned)
4443                {
4444                   op.s = (short)strtol(exp.constant, null, 0);
4445                   op.ops = shortOps;
4446                }
4447                else
4448                {
4449                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4450                   op.ops = ushortOps;
4451                }
4452                break;
4453             case intType:
4454             case longType:
4455                if(exp.constant[0] == '\'')
4456                {
4457                   op.i = exp.constant[1];
4458                   op.ops = intOps;
4459                }
4460                else if(type.isSigned)
4461                {
4462                   op.i = (int)strtol(exp.constant, null, 0);
4463                   op.ops = intOps;
4464                }
4465                else
4466                {
4467                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4468                   op.ops = uintOps;
4469                }
4470                op.kind = intType;
4471                break;
4472             case int64Type:
4473                if(type.isSigned)
4474                {
4475                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4476                   op.ops = int64Ops;
4477                }
4478                else
4479                {
4480                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4481                   op.ops = uint64Ops;
4482                }
4483                op.kind = int64Type;
4484                break;
4485             case intPtrType:
4486                if(type.isSigned)
4487                {
4488                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4489                   op.ops = int64Ops;
4490                }
4491                else
4492                {
4493                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4494                   op.ops = uint64Ops;
4495                }
4496                op.kind = int64Type;
4497                break;
4498             case intSizeType:
4499                if(type.isSigned)
4500                {
4501                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4502                   op.ops = int64Ops;
4503                }
4504                else
4505                {
4506                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4507                   op.ops = uint64Ops;
4508                }
4509                op.kind = int64Type;
4510                break;
4511             case floatType:
4512                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4513                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4514                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4515                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4516                else
4517                   op.f = (float)strtod(exp.constant, null);
4518                op.ops = floatOps;
4519                break;
4520             case doubleType:
4521                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4522                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4523                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4524                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4525                else
4526                   op.d = (double)strtod(exp.constant, null);
4527                op.ops = doubleOps;
4528                break;
4529             //case classType:    For when we have operator overloading...
4530             // Pointer additions
4531             //case functionType:
4532             case arrayType:
4533             case pointerType:
4534             case classType:
4535                op.ui64 = _strtoui64(exp.constant, null, 0);
4536                op.kind = pointerType;
4537                op.ops = uint64Ops;
4538                // op.ptrSize =
4539                break;
4540          }
4541       }
4542    }
4543    return op;
4544 }
4545
4546 static int64 GetEnumValue(Class _class, void * ptr)
4547 {
4548    int64 v = 0;
4549    switch(_class.typeSize)
4550    {
4551       case 8:
4552          if(!strcmp(_class.dataTypeString, "uint64"))
4553             v = (int64)*(uint64 *)ptr;
4554          else
4555             v = (int64)*(int64 *)ptr;
4556          break;
4557       case 4:
4558          if(!strcmp(_class.dataTypeString, "uint"))
4559             v = (int64)*(uint *)ptr;
4560          else
4561             v = (int64)*(int *)ptr;
4562          break;
4563       case 2:
4564          if(!strcmp(_class.dataTypeString, "uint16"))
4565             v = (int64)*(uint16 *)ptr;
4566          else
4567             v = (int64)*(short *)ptr;
4568          break;
4569       case 1:
4570          if(!strcmp(_class.dataTypeString, "byte"))
4571             v = (int64)*(byte *)ptr;
4572          else
4573             v = (int64)*(char *)ptr;
4574          break;
4575    }
4576    return v;
4577 }
4578
4579 static __attribute__((unused)) void UnusedFunction()
4580 {
4581    int a;
4582    a.OnGetString(0,0,0);
4583 }
4584 default:
4585 extern int __ecereVMethodID_class_OnGetString;
4586 public:
4587
4588 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4589 {
4590    DataMember dataMember;
4591    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4592    {
4593       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4594          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4595       else
4596       {
4597          Expression exp { };
4598          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4599          Type type;
4600          void * ptr = inst.data + dataMember.offset + offset;
4601          char * result = null;
4602          exp.loc = member.loc = inst.loc;
4603          ((Identifier)member.identifiers->first).loc = inst.loc;
4604
4605          if(!dataMember.dataType)
4606             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4607          type = dataMember.dataType;
4608          if(type.kind == classType)
4609          {
4610             Class _class = type._class.registered;
4611             if(_class.type == enumClass)
4612             {
4613                Class enumClass = eSystem_FindClass(privateModule, "enum");
4614                if(enumClass)
4615                {
4616                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4617                   NamedLink64 item;
4618                   for(item = e.values.first; item; item = item.next)
4619                   {
4620                      if(item.data == GetEnumValue(_class, ptr))
4621                      {
4622                         result = item.name;
4623                         break;
4624                      }
4625                   }
4626                   if(result)
4627                   {
4628                      exp.identifier = MkIdentifier(result);
4629                      exp.type = identifierExp;
4630                      exp.destType = MkClassType(_class.fullName);
4631                      ProcessExpressionType(exp);
4632                   }
4633                }
4634             }
4635             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4636             {
4637                if(!_class.dataType)
4638                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4639                type = _class.dataType;
4640             }
4641          }
4642          if(!result)
4643          {
4644             switch(type.kind)
4645             {
4646                case floatType:
4647                {
4648                   FreeExpContents(exp);
4649
4650                   exp.constant = PrintFloat(*(float*)ptr);
4651                   exp.type = constantExp;
4652                   break;
4653                }
4654                case doubleType:
4655                {
4656                   FreeExpContents(exp);
4657
4658                   exp.constant = PrintDouble(*(double*)ptr);
4659                   exp.type = constantExp;
4660                   break;
4661                }
4662                case intType:
4663                {
4664                   FreeExpContents(exp);
4665
4666                   exp.constant = PrintInt(*(int*)ptr);
4667                   exp.type = constantExp;
4668                   break;
4669                }
4670                case int64Type:
4671                {
4672                   FreeExpContents(exp);
4673
4674                   exp.constant = PrintInt64(*(int64*)ptr);
4675                   exp.type = constantExp;
4676                   break;
4677                }
4678                case intPtrType:
4679                {
4680                   FreeExpContents(exp);
4681                   // TODO: This should probably use proper type
4682                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4683                   exp.type = constantExp;
4684                   break;
4685                }
4686                case intSizeType:
4687                {
4688                   FreeExpContents(exp);
4689                   // TODO: This should probably use proper type
4690                   exp.constant = PrintInt64((int64)*(intsize*)ptr);
4691                   exp.type = constantExp;
4692                   break;
4693                }
4694                default:
4695                   Compiler_Error($"Unhandled type populating instance\n");
4696             }
4697          }
4698          ListAdd(memberList, member);
4699       }
4700
4701       if(parentDataMember.type == unionMember)
4702          break;
4703    }
4704 }
4705
4706 void PopulateInstance(Instantiation inst)
4707 {
4708    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4709    Class _class = classSym.registered;
4710    DataMember dataMember;
4711    OldList * memberList = MkList();
4712    // Added this check and ->Add to prevent memory leaks on bad code
4713    if(!inst.members)
4714       inst.members = MkListOne(MkMembersInitList(memberList));
4715    else
4716       inst.members->Add(MkMembersInitList(memberList));
4717    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4718    {
4719       if(!dataMember.isProperty)
4720       {
4721          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4722             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4723          else
4724          {
4725             Expression exp { };
4726             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4727             Type type;
4728             void * ptr = inst.data + dataMember.offset;
4729             char * result = null;
4730
4731             exp.loc = member.loc = inst.loc;
4732             ((Identifier)member.identifiers->first).loc = inst.loc;
4733
4734             if(!dataMember.dataType)
4735                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4736             type = dataMember.dataType;
4737             if(type.kind == classType)
4738             {
4739                Class _class = type._class.registered;
4740                if(_class.type == enumClass)
4741                {
4742                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4743                   if(enumClass)
4744                   {
4745                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4746                      NamedLink64 item;
4747                      for(item = e.values.first; item; item = item.next)
4748                      {
4749                         if(item.data == GetEnumValue(_class, ptr))
4750                         {
4751                            result = item.name;
4752                            break;
4753                         }
4754                      }
4755                   }
4756                   if(result)
4757                   {
4758                      exp.identifier = MkIdentifier(result);
4759                      exp.type = identifierExp;
4760                      exp.destType = MkClassType(_class.fullName);
4761                      ProcessExpressionType(exp);
4762                   }
4763                }
4764                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4765                {
4766                   if(!_class.dataType)
4767                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4768                   type = _class.dataType;
4769                }
4770             }
4771             if(!result)
4772             {
4773                switch(type.kind)
4774                {
4775                   case floatType:
4776                   {
4777                      exp.constant = PrintFloat(*(float*)ptr);
4778                      exp.type = constantExp;
4779                      break;
4780                   }
4781                   case doubleType:
4782                   {
4783                      exp.constant = PrintDouble(*(double*)ptr);
4784                      exp.type = constantExp;
4785                      break;
4786                   }
4787                   case intType:
4788                   {
4789                      exp.constant = PrintInt(*(int*)ptr);
4790                      exp.type = constantExp;
4791                      break;
4792                   }
4793                   case int64Type:
4794                   {
4795                      exp.constant = PrintInt64(*(int64*)ptr);
4796                      exp.type = constantExp;
4797                      break;
4798                   }
4799                   case intPtrType:
4800                   {
4801                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4802                      exp.type = constantExp;
4803                      break;
4804                   }
4805                   default:
4806                      Compiler_Error($"Unhandled type populating instance\n");
4807                }
4808             }
4809             ListAdd(memberList, member);
4810          }
4811       }
4812    }
4813 }
4814
4815 void ComputeInstantiation(Expression exp)
4816 {
4817    Instantiation inst = exp.instance;
4818    MembersInit members;
4819    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4820    Class _class = classSym ? classSym.registered : null;
4821    DataMember curMember = null;
4822    Class curClass = null;
4823    DataMember subMemberStack[256];
4824    int subMemberStackPos = 0;
4825    uint64 bits = 0;
4826
4827    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4828    {
4829       // Don't recompute the instantiation...
4830       // Non Simple classes will have become constants by now
4831       if(inst.data)
4832          return;
4833
4834       if(_class.type == normalClass || _class.type == noHeadClass)
4835       {
4836          inst.data = (byte *)eInstance_New(_class);
4837          if(_class.type == normalClass)
4838             ((Instance)inst.data)._refCount++;
4839       }
4840       else
4841          inst.data = new0 byte[_class.structSize];
4842    }
4843
4844    if(inst.members)
4845    {
4846       for(members = inst.members->first; members; members = members.next)
4847       {
4848          switch(members.type)
4849          {
4850             case dataMembersInit:
4851             {
4852                if(members.dataMembers)
4853                {
4854                   MemberInit member;
4855                   for(member = members.dataMembers->first; member; member = member.next)
4856                   {
4857                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4858                      bool found = false;
4859
4860                      Property prop = null;
4861                      DataMember dataMember = null;
4862                      uint dataMemberOffset;
4863
4864                      if(!ident)
4865                      {
4866                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4867                         if(curMember)
4868                         {
4869                            if(curMember.isProperty)
4870                               prop = (Property)curMember;
4871                            else
4872                            {
4873                               dataMember = curMember;
4874
4875                               // CHANGED THIS HERE
4876                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4877
4878                               // 2013/17/29 -- It seems that this was missing here!
4879                               if(_class.type == normalClass)
4880                                  dataMemberOffset += _class.base.structSize;
4881                               // dataMemberOffset = dataMember.offset;
4882                            }
4883                            found = true;
4884                         }
4885                      }
4886                      else
4887                      {
4888                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4889                         if(prop)
4890                         {
4891                            found = true;
4892                            if(prop.memberAccess == publicAccess)
4893                            {
4894                               curMember = (DataMember)prop;
4895                               curClass = prop._class;
4896                            }
4897                         }
4898                         else
4899                         {
4900                            DataMember _subMemberStack[256];
4901                            int _subMemberStackPos = 0;
4902
4903                            // FILL MEMBER STACK
4904                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4905
4906                            if(dataMember)
4907                            {
4908                               found = true;
4909                               if(dataMember.memberAccess == publicAccess)
4910                               {
4911                                  curMember = dataMember;
4912                                  curClass = dataMember._class;
4913                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
4914                                  subMemberStackPos = _subMemberStackPos;
4915                               }
4916                            }
4917                         }
4918                      }
4919
4920                      if(found && member.initializer && member.initializer.type == expInitializer)
4921                      {
4922                         Expression value = member.initializer.exp;
4923                         Type type = null;
4924                         bool deepMember = false;
4925                         if(prop)
4926                         {
4927                            type = prop.dataType;
4928                         }
4929                         else if(dataMember)
4930                         {
4931                            if(!dataMember.dataType)
4932                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4933
4934                            type = dataMember.dataType;
4935                         }
4936
4937                         if(ident && ident.next)
4938                         {
4939                            deepMember = true;
4940
4941                            // for(; ident && type; ident = ident.next)
4942                            for(ident = ident.next; ident && type; ident = ident.next)
4943                            {
4944                               if(type.kind == classType)
4945                               {
4946                                  prop = eClass_FindProperty(type._class.registered,
4947                                     ident.string, privateModule);
4948                                  if(prop)
4949                                     type = prop.dataType;
4950                                  else
4951                                  {
4952                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
4953                                        ident.string, &dataMemberOffset, privateModule, null, null);
4954                                     if(dataMember)
4955                                        type = dataMember.dataType;
4956                                  }
4957                               }
4958                               else if(type.kind == structType || type.kind == unionType)
4959                               {
4960                                  Type memberType;
4961                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
4962                                  {
4963                                     if(!strcmp(memberType.name, ident.string))
4964                                     {
4965                                        type = memberType;
4966                                        break;
4967                                     }
4968                                  }
4969                               }
4970                            }
4971                         }
4972                         if(value)
4973                         {
4974                            FreeType(value.destType);
4975                            value.destType = type;
4976                            if(type) type.refCount++;
4977                            ComputeExpression(value);
4978                         }
4979                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
4980                         {
4981                            if(type.kind == classType)
4982                            {
4983                               Class _class = type._class.registered;
4984                               if(_class && (_class.type == bitClass || _class.type == unitClass || _class.type == enumClass))
4985                               {
4986                                  if(!_class.dataType)
4987                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4988                                  type = _class.dataType;
4989                               }
4990                            }
4991
4992                            if(dataMember)
4993                            {
4994                               void * ptr = inst.data + dataMemberOffset;
4995
4996                               if(value.type == constantExp)
4997                               {
4998                                  switch(type.kind)
4999                                  {
5000                                     case intType:
5001                                     {
5002                                        GetInt(value, (int*)ptr);
5003                                        break;
5004                                     }
5005                                     case int64Type:
5006                                     {
5007                                        GetInt64(value, (int64*)ptr);
5008                                        break;
5009                                     }
5010                                     case intPtrType:
5011                                     {
5012                                        GetIntPtr(value, (intptr*)ptr);
5013                                        break;
5014                                     }
5015                                     case intSizeType:
5016                                     {
5017                                        GetIntSize(value, (intsize*)ptr);
5018                                        break;
5019                                     }
5020                                     case floatType:
5021                                     {
5022                                        GetFloat(value, (float*)ptr);
5023                                        break;
5024                                     }
5025                                     case doubleType:
5026                                     {
5027                                        GetDouble(value, (double *)ptr);
5028                                        break;
5029                                     }
5030                                  }
5031                               }
5032                               else if(value.type == instanceExp)
5033                               {
5034                                  if(type.kind == classType)
5035                                  {
5036                                     Class _class = type._class.registered;
5037                                     if(_class.type == structClass)
5038                                     {
5039                                        ComputeTypeSize(type);
5040                                        if(value.instance.data)
5041                                           memcpy(ptr, value.instance.data, type.size);
5042                                     }
5043                                  }
5044                               }
5045                            }
5046                            else if(prop && prop.Set != (void *)(intptr)1)
5047                            {
5048                               if(value.type == instanceExp && value.instance.data)
5049                               {
5050                                  if(type.kind == classType)
5051                                  {
5052                                     Class _class = type._class.registered;
5053                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5054                                     {
5055                                        void (*Set)(void *, void *) = (void *)prop.Set;
5056                                        Set(inst.data, value.instance.data);
5057                                        PopulateInstance(inst);
5058                                     }
5059                                  }
5060                               }
5061                               else if(value.type == constantExp)
5062                               {
5063                                  switch(type.kind)
5064                                  {
5065                                     case doubleType:
5066                                     {
5067                                        void (*Set)(void *, double) = (void *)prop.Set;
5068                                        Set(inst.data, strtod(value.constant, null) );
5069                                        break;
5070                                     }
5071                                     case floatType:
5072                                     {
5073                                        void (*Set)(void *, float) = (void *)prop.Set;
5074                                        Set(inst.data, (float)(strtod(value.constant, null)));
5075                                        break;
5076                                     }
5077                                     case intType:
5078                                     {
5079                                        void (*Set)(void *, int) = (void *)prop.Set;
5080                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5081                                        break;
5082                                     }
5083                                     case int64Type:
5084                                     {
5085                                        void (*Set)(void *, int64) = (void *)prop.Set;
5086                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5087                                        break;
5088                                     }
5089                                     case intPtrType:
5090                                     {
5091                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5092                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5093                                        break;
5094                                     }
5095                                     case intSizeType:
5096                                     {
5097                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5098                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5099                                        break;
5100                                     }
5101                                  }
5102                               }
5103                               else if(value.type == stringExp)
5104                               {
5105                                  char temp[1024];
5106                                  ReadString(temp, value.string);
5107                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5108                               }
5109                            }
5110                         }
5111                         else if(!deepMember && type && _class.type == unitClass)
5112                         {
5113                            if(prop)
5114                            {
5115                               // Only support converting units to units for now...
5116                               if(value.type == constantExp)
5117                               {
5118                                  if(type.kind == classType)
5119                                  {
5120                                     Class _class = type._class.registered;
5121                                     if(_class.type == unitClass)
5122                                     {
5123                                        if(!_class.dataType)
5124                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5125                                        type = _class.dataType;
5126                                     }
5127                                  }
5128                                  // TODO: Assuming same base type for units...
5129                                  switch(type.kind)
5130                                  {
5131                                     case floatType:
5132                                     {
5133                                        float fValue;
5134                                        float (*Set)(float) = (void *)prop.Set;
5135                                        GetFloat(member.initializer.exp, &fValue);
5136                                        exp.constant = PrintFloat(Set(fValue));
5137                                        exp.type = constantExp;
5138                                        break;
5139                                     }
5140                                     case doubleType:
5141                                     {
5142                                        double dValue;
5143                                        double (*Set)(double) = (void *)prop.Set;
5144                                        GetDouble(member.initializer.exp, &dValue);
5145                                        exp.constant = PrintDouble(Set(dValue));
5146                                        exp.type = constantExp;
5147                                        break;
5148                                     }
5149                                  }
5150                               }
5151                            }
5152                         }
5153                         else if(!deepMember && type && _class.type == bitClass)
5154                         {
5155                            if(prop)
5156                            {
5157                               if(value.type == instanceExp && value.instance.data)
5158                               {
5159                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5160                                  bits = Set(value.instance.data);
5161                               }
5162                               else if(value.type == constantExp)
5163                               {
5164                               }
5165                            }
5166                            else if(dataMember)
5167                            {
5168                               BitMember bitMember = (BitMember) dataMember;
5169                               Type type;
5170                               uint64 part = 0;
5171                               bits = (bits & ~bitMember.mask);
5172                               if(!bitMember.dataType)
5173                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5174                               type = bitMember.dataType;
5175                               if(type.kind == classType && type._class && type._class.registered)
5176                               {
5177                                  if(!type._class.registered.dataType)
5178                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5179                                  type = type._class.registered.dataType;
5180                               }
5181                               switch(type.kind)
5182                               {
5183                                  case _BoolType:
5184                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5185                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5186                                  case intType:
5187                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5188                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5189                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5190                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5191                               }
5192                               bits |= part << bitMember.pos;
5193                            }
5194                         }
5195                      }
5196                      else
5197                      {
5198                         if(_class && _class.type == unitClass)
5199                         {
5200                            ComputeExpression(member.initializer.exp);
5201                            exp.constant = member.initializer.exp.constant;
5202                            exp.type = constantExp;
5203
5204                            member.initializer.exp.constant = null;
5205                         }
5206                      }
5207                   }
5208                }
5209                break;
5210             }
5211          }
5212       }
5213    }
5214    if(_class && _class.type == bitClass)
5215    {
5216       exp.constant = PrintHexUInt(bits);
5217       exp.type = constantExp;
5218    }
5219    if(exp.type != instanceExp)
5220    {
5221       FreeInstance(inst);
5222    }
5223 }
5224
5225 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5226 {
5227    bool result = false;
5228    switch(kind)
5229    {
5230       case shortType:
5231          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5232             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5233          break;
5234       case intType:
5235       case longType:
5236          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5237             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5238          break;
5239       case int64Type:
5240          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5241             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5242             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5243          break;
5244       case floatType:
5245          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5246             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5247             result = GetOpFloat(op, &op.f);
5248          break;
5249       case doubleType:
5250          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5251             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5252             result = GetOpDouble(op, &op.d);
5253          break;
5254       case pointerType:
5255          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5256             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5257             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5258          break;
5259       case enumType:
5260          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5261             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5262             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5263          break;
5264       case intPtrType:
5265          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5266             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5267          break;
5268       case intSizeType:
5269          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5270             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5271          break;
5272    }
5273    return result;
5274 }
5275
5276 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5277 {
5278    if(exp.op.op == SIZEOF)
5279    {
5280       FreeExpContents(exp);
5281       exp.type = constantExp;
5282       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5283    }
5284    else
5285    {
5286       if(!exp.op.exp1)
5287       {
5288          switch(exp.op.op)
5289          {
5290             // unary arithmetic
5291             case '+':
5292             {
5293                // Provide default unary +
5294                Expression exp2 = exp.op.exp2;
5295                exp.op.exp2 = null;
5296                FreeExpContents(exp);
5297                FreeType(exp.expType);
5298                FreeType(exp.destType);
5299                *exp = *exp2;
5300                delete exp2;
5301                break;
5302             }
5303             case '-':
5304                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5305                break;
5306             // unary arithmetic increment and decrement
5307                   //OPERATOR_ALL(UNARY, ++, Inc)
5308                   //OPERATOR_ALL(UNARY, --, Dec)
5309             // unary bitwise
5310             case '~':
5311                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5312                break;
5313             // unary logical negation
5314             case '!':
5315                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5316                break;
5317          }
5318       }
5319       else
5320       {
5321          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5322          {
5323             if(Promote(op2, op1.kind, op1.type.isSigned))
5324                op2.kind = op1.kind, op2.ops = op1.ops;
5325             else if(Promote(op1, op2.kind, op2.type.isSigned))
5326                op1.kind = op2.kind, op1.ops = op2.ops;
5327          }
5328          switch(exp.op.op)
5329          {
5330             // binary arithmetic
5331             case '+':
5332                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5333                break;
5334             case '-':
5335                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5336                break;
5337             case '*':
5338                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5339                break;
5340             case '/':
5341                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5342                break;
5343             case '%':
5344                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5345                break;
5346             // binary arithmetic assignment
5347                   //OPERATOR_ALL(BINARY, =, Asign)
5348                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5349                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5350                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5351                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5352                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5353             // binary bitwise
5354             case '&':
5355                if(exp.op.exp2)
5356                {
5357                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5358                }
5359                break;
5360             case '|':
5361                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5362                break;
5363             case '^':
5364                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5365                break;
5366             case LEFT_OP:
5367                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5368                break;
5369             case RIGHT_OP:
5370                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5371                break;
5372             // binary bitwise assignment
5373                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5374                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5375                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5376                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5377                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5378             // binary logical equality
5379             case EQ_OP:
5380                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5381                break;
5382             case NE_OP:
5383                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5384                break;
5385             // binary logical
5386             case AND_OP:
5387                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5388                break;
5389             case OR_OP:
5390                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5391                break;
5392             // binary logical relational
5393             case '>':
5394                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5395                break;
5396             case '<':
5397                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5398                break;
5399             case GE_OP:
5400                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5401                break;
5402             case LE_OP:
5403                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5404                break;
5405          }
5406       }
5407    }
5408 }
5409
5410 void ComputeExpression(Expression exp)
5411 {
5412 #ifdef _DEBUG
5413    char expString[10240];
5414    expString[0] = '\0';
5415    PrintExpression(exp, expString);
5416 #endif
5417
5418    switch(exp.type)
5419    {
5420       case identifierExp:
5421       {
5422          Identifier id = exp.identifier;
5423          if(id && exp.isConstant && !inCompiler && !inPreCompiler && !inDebugger)
5424          {
5425             Class c = (exp.expType && exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
5426             if(c && c.type == enumClass)
5427             {
5428                Class enumClass = eSystem_FindClass(privateModule, "enum");
5429                if(enumClass)
5430                {
5431                   NamedLink64 value;
5432                   EnumClassData e = ACCESS_CLASSDATA(c, enumClass);
5433                   for(value = e.values.first; value; value = value.next)
5434                   {
5435                      if(!strcmp(value.name, id.string))
5436                         break;
5437                   }
5438                   if(value)
5439                   {
5440                      const String dts = c.dataTypeString;
5441                      FreeExpContents(exp);
5442                      exp.type = constantExp;
5443                      exp.constant = (dts && (!strcmp(dts, "int") || !strcmp(dts, "int64") || !strcmp(dts, "short") || !strcmp(dts, "char"))) ? PrintInt64(value.data) : PrintUInt64(value.data);
5444                   }
5445                }
5446             }
5447          }
5448          break;
5449       }
5450       case instanceExp:
5451       {
5452          ComputeInstantiation(exp);
5453          break;
5454       }
5455       /*
5456       case constantExp:
5457          break;
5458       */
5459       case opExp:
5460       {
5461          Expression exp1, exp2 = null;
5462          Operand op1 { };
5463          Operand op2 { };
5464
5465          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5466          if(exp.op.exp2)
5467          {
5468             Expression e = exp.op.exp2;
5469
5470             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5471             {
5472                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5473                {
5474                   if(e.type == extensionCompoundExp)
5475                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5476                   else
5477                      e = e.list->last;
5478                }
5479             }
5480             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5481             {
5482                if(e.type == stringExp && e.string)
5483                {
5484                   char * string = e.string;
5485                   int len = strlen(string);
5486                   char * tmp = new char[len-2+1];
5487                   len = UnescapeString(tmp, string + 1, len - 2);
5488                   delete tmp;
5489                   FreeExpContents(exp);
5490                   exp.type = constantExp;
5491                   exp.constant = PrintUInt(len + 1);
5492                }
5493                else
5494                {
5495                   Type type = e.expType;
5496                   type.refCount++;
5497                   FreeExpContents(exp);
5498                   exp.type = constantExp;
5499                   exp.constant = PrintUInt(ComputeTypeSize(type));
5500                   FreeType(type);
5501                }
5502                break;
5503             }
5504             else
5505                ComputeExpression(exp.op.exp2);
5506          }
5507          if(exp.op.exp1)
5508          {
5509             ComputeExpression(exp.op.exp1);
5510             exp1 = exp.op.exp1;
5511             exp2 = exp.op.exp2;
5512             op1 = GetOperand(exp1);
5513             if(op1.type) op1.type.refCount++;
5514             if(exp2)
5515             {
5516                op2 = GetOperand(exp2);
5517                if(op2.type) op2.type.refCount++;
5518             }
5519          }
5520          else
5521          {
5522             exp1 = exp.op.exp2;
5523             op1 = GetOperand(exp1);
5524             if(op1.type) op1.type.refCount++;
5525          }
5526
5527          CallOperator(exp, exp1, exp2, op1, op2);
5528          /*
5529          switch(exp.op.op)
5530          {
5531             // Unary operators
5532             case '&':
5533                // Also binary
5534                if(exp.op.exp1 && exp.op.exp2)
5535                {
5536                   // Binary And
5537                   if(op1.ops.BitAnd)
5538                   {
5539                      FreeExpContents(exp);
5540                      op1.ops.BitAnd(exp, op1, op2);
5541                   }
5542                }
5543                break;
5544             case '*':
5545                if(exp.op.exp1)
5546                {
5547                   if(op1.ops.Mul)
5548                   {
5549                      FreeExpContents(exp);
5550                      op1.ops.Mul(exp, op1, op2);
5551                   }
5552                }
5553                break;
5554             case '+':
5555                if(exp.op.exp1)
5556                {
5557                   if(op1.ops.Add)
5558                   {
5559                      FreeExpContents(exp);
5560                      op1.ops.Add(exp, op1, op2);
5561                   }
5562                }
5563                else
5564                {
5565                   // Provide default unary +
5566                   Expression exp2 = exp.op.exp2;
5567                   exp.op.exp2 = null;
5568                   FreeExpContents(exp);
5569                   FreeType(exp.expType);
5570                   FreeType(exp.destType);
5571
5572                   *exp = *exp2;
5573                   delete exp2;
5574                }
5575                break;
5576             case '-':
5577                if(exp.op.exp1)
5578                {
5579                   if(op1.ops.Sub)
5580                   {
5581                      FreeExpContents(exp);
5582                      op1.ops.Sub(exp, op1, op2);
5583                   }
5584                }
5585                else
5586                {
5587                   if(op1.ops.Neg)
5588                   {
5589                      FreeExpContents(exp);
5590                      op1.ops.Neg(exp, op1);
5591                   }
5592                }
5593                break;
5594             case '~':
5595                if(op1.ops.BitNot)
5596                {
5597                   FreeExpContents(exp);
5598                   op1.ops.BitNot(exp, op1);
5599                }
5600                break;
5601             case '!':
5602                if(op1.ops.Not)
5603                {
5604                   FreeExpContents(exp);
5605                   op1.ops.Not(exp, op1);
5606                }
5607                break;
5608             // Binary only operators
5609             case '/':
5610                if(op1.ops.Div)
5611                {
5612                   FreeExpContents(exp);
5613                   op1.ops.Div(exp, op1, op2);
5614                }
5615                break;
5616             case '%':
5617                if(op1.ops.Mod)
5618                {
5619                   FreeExpContents(exp);
5620                   op1.ops.Mod(exp, op1, op2);
5621                }
5622                break;
5623             case LEFT_OP:
5624                break;
5625             case RIGHT_OP:
5626                break;
5627             case '<':
5628                if(exp.op.exp1)
5629                {
5630                   if(op1.ops.Sma)
5631                   {
5632                      FreeExpContents(exp);
5633                      op1.ops.Sma(exp, op1, op2);
5634                   }
5635                }
5636                break;
5637             case '>':
5638                if(exp.op.exp1)
5639                {
5640                   if(op1.ops.Grt)
5641                   {
5642                      FreeExpContents(exp);
5643                      op1.ops.Grt(exp, op1, op2);
5644                   }
5645                }
5646                break;
5647             case LE_OP:
5648                if(exp.op.exp1)
5649                {
5650                   if(op1.ops.SmaEqu)
5651                   {
5652                      FreeExpContents(exp);
5653                      op1.ops.SmaEqu(exp, op1, op2);
5654                   }
5655                }
5656                break;
5657             case GE_OP:
5658                if(exp.op.exp1)
5659                {
5660                   if(op1.ops.GrtEqu)
5661                   {
5662                      FreeExpContents(exp);
5663                      op1.ops.GrtEqu(exp, op1, op2);
5664                   }
5665                }
5666                break;
5667             case EQ_OP:
5668                if(exp.op.exp1)
5669                {
5670                   if(op1.ops.Equ)
5671                   {
5672                      FreeExpContents(exp);
5673                      op1.ops.Equ(exp, op1, op2);
5674                   }
5675                }
5676                break;
5677             case NE_OP:
5678                if(exp.op.exp1)
5679                {
5680                   if(op1.ops.Nqu)
5681                   {
5682                      FreeExpContents(exp);
5683                      op1.ops.Nqu(exp, op1, op2);
5684                   }
5685                }
5686                break;
5687             case '|':
5688                if(op1.ops.BitOr)
5689                {
5690                   FreeExpContents(exp);
5691                   op1.ops.BitOr(exp, op1, op2);
5692                }
5693                break;
5694             case '^':
5695                if(op1.ops.BitXor)
5696                {
5697                   FreeExpContents(exp);
5698                   op1.ops.BitXor(exp, op1, op2);
5699                }
5700                break;
5701             case AND_OP:
5702                break;
5703             case OR_OP:
5704                break;
5705             case SIZEOF:
5706                FreeExpContents(exp);
5707                exp.type = constantExp;
5708                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5709                break;
5710          }
5711          */
5712          if(op1.type) FreeType(op1.type);
5713          if(op2.type) FreeType(op2.type);
5714          break;
5715       }
5716       case bracketsExp:
5717       case extensionExpressionExp:
5718       {
5719          Expression e, n;
5720          for(e = exp.list->first; e; e = n)
5721          {
5722             n = e.next;
5723             if(!n)
5724             {
5725                OldList * list = exp.list;
5726                Expression prev = exp.prev;
5727                Expression next = exp.next;
5728
5729                // For operations which set the exp type on brackets exp after the inner exp was processed...
5730                if(exp.expType && exp.expType.kind == classType && (!e.expType || e.expType.kind != classType))
5731                {
5732                   FreeType(e.expType);
5733                   e.expType = exp.expType;
5734                   e.expType.refCount++;
5735                }
5736                ComputeExpression(e);
5737                //FreeExpContents(exp);
5738                FreeType(exp.expType);
5739                FreeType(exp.destType);
5740                *exp = *e;
5741                exp.prev = prev;
5742                exp.next = next;
5743                delete e;
5744                delete list;
5745             }
5746             else
5747             {
5748                FreeExpression(e);
5749             }
5750          }
5751          break;
5752       }
5753       /*
5754
5755       case ExpIndex:
5756       {
5757          Expression e;
5758          exp.isConstant = true;
5759
5760          ComputeExpression(exp.index.exp);
5761          if(!exp.index.exp.isConstant)
5762             exp.isConstant = false;
5763
5764          for(e = exp.index.index->first; e; e = e.next)
5765          {
5766             ComputeExpression(e);
5767             if(!e.next)
5768             {
5769                // Check if this type is int
5770             }
5771             if(!e.isConstant)
5772                exp.isConstant = false;
5773          }
5774          exp.expType = Dereference(exp.index.exp.expType);
5775          break;
5776       }
5777       */
5778       case memberExp:
5779       {
5780          Expression memberExp = exp.member.exp;
5781          Identifier memberID = exp.member.member;
5782
5783          Type type;
5784          ComputeExpression(exp.member.exp);
5785          type = exp.member.exp.expType;
5786          if(type)
5787          {
5788             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);
5789             Property prop = null;
5790             DataMember member = null;
5791             Class convertTo = null;
5792             if(type.kind == subClassType && exp.member.exp.type == classExp)
5793                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5794
5795             if(!_class)
5796             {
5797                char string[256];
5798                Symbol classSym;
5799                string[0] = '\0';
5800                PrintTypeNoConst(type, string, false, true);
5801                classSym = FindClass(string);
5802                _class = classSym ? classSym.registered : null;
5803             }
5804
5805             if(exp.member.member)
5806             {
5807                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5808                if(!prop)
5809                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5810             }
5811             if(!prop && !member && _class && exp.member.member)
5812             {
5813                Symbol classSym = FindClass(exp.member.member.string);
5814                convertTo = _class;
5815                _class = classSym ? classSym.registered : null;
5816                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5817             }
5818
5819             if(prop)
5820             {
5821                if(prop.compiled)
5822                {
5823                   Type type = prop.dataType;
5824                   // TODO: Assuming same base type for units...
5825                   if(_class.type == unitClass)
5826                   {
5827                      if(type.kind == classType)
5828                      {
5829                         Class _class = type._class.registered;
5830                         if(_class.type == unitClass)
5831                         {
5832                            if(!_class.dataType)
5833                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5834                            type = _class.dataType;
5835                         }
5836                      }
5837                      switch(type.kind)
5838                      {
5839                         case floatType:
5840                         {
5841                            float value;
5842                            float (*Get)(float) = (void *)prop.Get;
5843                            GetFloat(exp.member.exp, &value);
5844                            exp.constant = PrintFloat(Get ? Get(value) : value);
5845                            exp.type = constantExp;
5846                            break;
5847                         }
5848                         case doubleType:
5849                         {
5850                            double value;
5851                            double (*Get)(double);
5852                            GetDouble(exp.member.exp, &value);
5853
5854                            if(convertTo)
5855                               Get = (void *)prop.Set;
5856                            else
5857                               Get = (void *)prop.Get;
5858                            exp.constant = PrintDouble(Get ? Get(value) : value);
5859                            exp.type = constantExp;
5860                            break;
5861                         }
5862                      }
5863                   }
5864                   else
5865                   {
5866                      if(convertTo)
5867                      {
5868                         Expression value = exp.member.exp;
5869                         Type type;
5870                         if(!prop.dataType)
5871                            ProcessPropertyType(prop);
5872
5873                         type = prop.dataType;
5874                         if(!type)
5875                         {
5876                             // printf("Investigate this\n");
5877                         }
5878                         else if(_class.type == structClass)
5879                         {
5880                            switch(type.kind)
5881                            {
5882                               case classType:
5883                               {
5884                                  Class propertyClass = type._class.registered;
5885                                  if(propertyClass.type == structClass && value.type == instanceExp)
5886                                  {
5887                                     void (*Set)(void *, void *) = (void *)prop.Set;
5888                                     exp.instance = Instantiation { };
5889                                     exp.instance.data = new0 byte[_class.structSize];
5890                                     exp.instance._class = MkSpecifierName(_class.fullName);
5891                                     exp.instance.loc = exp.loc;
5892                                     exp.type = instanceExp;
5893                                     Set(exp.instance.data, value.instance.data);
5894                                     PopulateInstance(exp.instance);
5895                                  }
5896                                  break;
5897                               }
5898                               case intType:
5899                               {
5900                                  int intValue;
5901                                  void (*Set)(void *, int) = (void *)prop.Set;
5902
5903                                  exp.instance = Instantiation { };
5904                                  exp.instance.data = new0 byte[_class.structSize];
5905                                  exp.instance._class = MkSpecifierName(_class.fullName);
5906                                  exp.instance.loc = exp.loc;
5907                                  exp.type = instanceExp;
5908
5909                                  GetInt(value, &intValue);
5910
5911                                  Set(exp.instance.data, intValue);
5912                                  PopulateInstance(exp.instance);
5913                                  break;
5914                               }
5915                               case int64Type:
5916                               {
5917                                  int64 intValue;
5918                                  void (*Set)(void *, int64) = (void *)prop.Set;
5919
5920                                  exp.instance = Instantiation { };
5921                                  exp.instance.data = new0 byte[_class.structSize];
5922                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5923                                  exp.instance.loc = exp.loc;
5924                                  exp.type = instanceExp;
5925
5926                                  GetInt64(value, &intValue);
5927
5928                                  Set(exp.instance.data, intValue);
5929                                  PopulateInstance(exp.instance);
5930                                  break;
5931                               }
5932                               case intPtrType:
5933                               {
5934                                  // TOFIX:
5935                                  intptr intValue;
5936                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5937
5938                                  exp.instance = Instantiation { };
5939                                  exp.instance.data = new0 byte[_class.structSize];
5940                                  exp.instance._class = MkSpecifierName(_class.fullName);
5941                                  exp.instance.loc = exp.loc;
5942                                  exp.type = instanceExp;
5943
5944                                  GetIntPtr(value, &intValue);
5945
5946                                  Set(exp.instance.data, intValue);
5947                                  PopulateInstance(exp.instance);
5948                                  break;
5949                               }
5950                               case intSizeType:
5951                               {
5952                                  // TOFIX:
5953                                  intsize intValue;
5954                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5955
5956                                  exp.instance = Instantiation { };
5957                                  exp.instance.data = new0 byte[_class.structSize];
5958                                  exp.instance._class = MkSpecifierName(_class.fullName);
5959                                  exp.instance.loc = exp.loc;
5960                                  exp.type = instanceExp;
5961
5962                                  GetIntSize(value, &intValue);
5963
5964                                  Set(exp.instance.data, intValue);
5965                                  PopulateInstance(exp.instance);
5966                                  break;
5967                               }
5968                               case floatType:
5969                               {
5970                                  float floatValue;
5971                                  void (*Set)(void *, float) = (void *)prop.Set;
5972
5973                                  exp.instance = Instantiation { };
5974                                  exp.instance.data = new0 byte[_class.structSize];
5975                                  exp.instance._class = MkSpecifierName(_class.fullName);
5976                                  exp.instance.loc = exp.loc;
5977                                  exp.type = instanceExp;
5978
5979                                  GetFloat(value, &floatValue);
5980
5981                                  Set(exp.instance.data, floatValue);
5982                                  PopulateInstance(exp.instance);
5983                                  break;
5984                               }
5985                               case doubleType:
5986                               {
5987                                  double doubleValue;
5988                                  void (*Set)(void *, double) = (void *)prop.Set;
5989
5990                                  exp.instance = Instantiation { };
5991                                  exp.instance.data = new0 byte[_class.structSize];
5992                                  exp.instance._class = MkSpecifierName(_class.fullName);
5993                                  exp.instance.loc = exp.loc;
5994                                  exp.type = instanceExp;
5995
5996                                  GetDouble(value, &doubleValue);
5997
5998                                  Set(exp.instance.data, doubleValue);
5999                                  PopulateInstance(exp.instance);
6000                                  break;
6001                               }
6002                            }
6003                         }
6004                         else if(_class.type == bitClass)
6005                         {
6006                            switch(type.kind)
6007                            {
6008                               case classType:
6009                               {
6010                                  Class propertyClass = type._class.registered;
6011                                  if(propertyClass.type == structClass && value.instance.data)
6012                                  {
6013                                     unsigned int (*Set)(void *) = (void *)prop.Set;
6014                                     unsigned int bits = Set(value.instance.data);
6015                                     exp.constant = PrintHexUInt(bits);
6016                                     exp.type = constantExp;
6017                                     break;
6018                                  }
6019                                  else if(_class.type == bitClass)
6020                                  {
6021                                     unsigned int value;
6022                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
6023                                     unsigned int bits;
6024
6025                                     GetUInt(exp.member.exp, &value);
6026                                     bits = Set(value);
6027                                     exp.constant = PrintHexUInt(bits);
6028                                     exp.type = constantExp;
6029                                  }
6030                               }
6031                            }
6032                         }
6033                      }
6034                      else
6035                      {
6036                         if(_class.type == bitClass)
6037                         {
6038                            unsigned int value;
6039                            GetUInt(exp.member.exp, &value);
6040
6041                            switch(type.kind)
6042                            {
6043                               case classType:
6044                               {
6045                                  Class _class = type._class.registered;
6046                                  if(_class.type == structClass)
6047                                  {
6048                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6049
6050                                     exp.instance = Instantiation { };
6051                                     exp.instance.data = new0 byte[_class.structSize];
6052                                     exp.instance._class = MkSpecifierName(_class.fullName);
6053                                     exp.instance.loc = exp.loc;
6054                                     //exp.instance.fullSet = true;
6055                                     exp.type = instanceExp;
6056                                     Get(value, exp.instance.data);
6057                                     PopulateInstance(exp.instance);
6058                                  }
6059                                  else if(_class.type == bitClass)
6060                                  {
6061                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6062                                     uint64 bits = Get(value);
6063                                     exp.constant = PrintHexUInt64(bits);
6064                                     exp.type = constantExp;
6065                                  }
6066                                  break;
6067                               }
6068                            }
6069                         }
6070                         else if(_class.type == structClass)
6071                         {
6072                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6073                            switch(type.kind)
6074                            {
6075                               case classType:
6076                               {
6077                                  Class _class = type._class.registered;
6078                                  if(_class.type == structClass && value)
6079                                  {
6080                                     void (*Get)(void *, void *) = (void *)prop.Get;
6081
6082                                     exp.instance = Instantiation { };
6083                                     exp.instance.data = new0 byte[_class.structSize];
6084                                     exp.instance._class = MkSpecifierName(_class.fullName);
6085                                     exp.instance.loc = exp.loc;
6086                                     //exp.instance.fullSet = true;
6087                                     exp.type = instanceExp;
6088                                     Get(value, exp.instance.data);
6089                                     PopulateInstance(exp.instance);
6090                                  }
6091                                  break;
6092                               }
6093                            }
6094                         }
6095                         /*else
6096                         {
6097                            char * value = exp.member.exp.instance.data;
6098                            switch(type.kind)
6099                            {
6100                               case classType:
6101                               {
6102                                  Class _class = type._class.registered;
6103                                  if(_class.type == normalClass)
6104                                  {
6105                                     void *(*Get)(void *) = (void *)prop.Get;
6106
6107                                     exp.instance = Instantiation { };
6108                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6109                                     exp.type = instanceExp;
6110                                     exp.instance.data = Get(value, exp.instance.data);
6111                                  }
6112                                  break;
6113                               }
6114                            }
6115                         }
6116                         */
6117                      }
6118                   }
6119                }
6120                else
6121                {
6122                   exp.isConstant = false;
6123                }
6124             }
6125             else if(member)
6126             {
6127             }
6128          }
6129
6130          if(exp.type != ExpressionType::memberExp)
6131          {
6132             FreeExpression(memberExp);
6133             FreeIdentifier(memberID);
6134          }
6135          break;
6136       }
6137       case typeSizeExp:
6138       {
6139          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6140          FreeExpContents(exp);
6141          exp.constant = PrintUInt(ComputeTypeSize(type));
6142          exp.type = constantExp;
6143          FreeType(type);
6144          break;
6145       }
6146       case classSizeExp:
6147       {
6148          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6149          if(classSym && classSym.registered)
6150          {
6151             if(classSym.registered.fixed)
6152             {
6153                FreeSpecifier(exp._class);
6154                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6155                exp.type = constantExp;
6156             }
6157             else
6158             {
6159                char className[1024];
6160                strcpy(className, "__ecereClass_");
6161                FullClassNameCat(className, classSym.string, true);
6162
6163                DeclareClass(curExternal, classSym, className);
6164
6165                FreeExpContents(exp);
6166                exp.type = pointerExp;
6167                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6168                exp.member.member = MkIdentifier("structSize");
6169             }
6170          }
6171          break;
6172       }
6173       case castExp:
6174       //case constantExp:
6175       {
6176          Type type;
6177          Expression e = exp;
6178          if(exp.type == castExp)
6179          {
6180             if(exp.cast.exp)
6181                ComputeExpression(exp.cast.exp);
6182             e = exp.cast.exp;
6183          }
6184          if(e && exp.expType)
6185          {
6186             /*if(exp.destType)
6187                type = exp.destType;
6188             else*/
6189                type = exp.expType;
6190             if(type.kind == classType)
6191             {
6192                Class _class = type._class.registered;
6193                if(_class && (_class.type == unitClass || _class.type == bitClass))
6194                {
6195                   if(!_class.dataType)
6196                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6197                   type = _class.dataType;
6198                }
6199             }
6200
6201             switch(type.kind)
6202             {
6203                case _BoolType:
6204                case charType:
6205                   if(type.isSigned)
6206                   {
6207                      char value = 0;
6208                      if(GetChar(e, &value))
6209                      {
6210                         FreeExpContents(exp);
6211                         exp.constant = PrintChar(value);
6212                         exp.type = constantExp;
6213                      }
6214                   }
6215                   else
6216                   {
6217                      unsigned char value = 0;
6218                      if(GetUChar(e, &value))
6219                      {
6220                         FreeExpContents(exp);
6221                         exp.constant = PrintUChar(value);
6222                         exp.type = constantExp;
6223                      }
6224                   }
6225                   break;
6226                case shortType:
6227                   if(type.isSigned)
6228                   {
6229                      short value = 0;
6230                      if(GetShort(e, &value))
6231                      {
6232                         FreeExpContents(exp);
6233                         exp.constant = PrintShort(value);
6234                         exp.type = constantExp;
6235                      }
6236                   }
6237                   else
6238                   {
6239                      unsigned short value = 0;
6240                      if(GetUShort(e, &value))
6241                      {
6242                         FreeExpContents(exp);
6243                         exp.constant = PrintUShort(value);
6244                         exp.type = constantExp;
6245                      }
6246                   }
6247                   break;
6248                case intType:
6249                   if(type.isSigned)
6250                   {
6251                      int value = 0;
6252                      if(GetInt(e, &value))
6253                      {
6254                         FreeExpContents(exp);
6255                         exp.constant = PrintInt(value);
6256                         exp.type = constantExp;
6257                      }
6258                   }
6259                   else
6260                   {
6261                      unsigned int value = 0;
6262                      if(GetUInt(e, &value))
6263                      {
6264                         FreeExpContents(exp);
6265                         exp.constant = PrintUInt(value);
6266                         exp.type = constantExp;
6267                      }
6268                   }
6269                   break;
6270                case int64Type:
6271                   if(type.isSigned)
6272                   {
6273                      int64 value = 0;
6274                      if(GetInt64(e, &value))
6275                      {
6276                         FreeExpContents(exp);
6277                         exp.constant = PrintInt64(value);
6278                         exp.type = constantExp;
6279                      }
6280                   }
6281                   else
6282                   {
6283                      uint64 value = 0;
6284                      if(GetUInt64(e, &value))
6285                      {
6286                         FreeExpContents(exp);
6287                         exp.constant = PrintUInt64(value);
6288                         exp.type = constantExp;
6289                      }
6290                   }
6291                   break;
6292                case intPtrType:
6293                   if(type.isSigned)
6294                   {
6295                      intptr value = 0;
6296                      if(GetIntPtr(e, &value))
6297                      {
6298                         FreeExpContents(exp);
6299                         exp.constant = PrintInt64((int64)value);
6300                         exp.type = constantExp;
6301                      }
6302                   }
6303                   else
6304                   {
6305                      uintptr value = 0;
6306                      if(GetUIntPtr(e, &value))
6307                      {
6308                         FreeExpContents(exp);
6309                         exp.constant = PrintUInt64((uint64)value);
6310                         exp.type = constantExp;
6311                      }
6312                   }
6313                   break;
6314                case intSizeType:
6315                   if(type.isSigned)
6316                   {
6317                      intsize value = 0;
6318                      if(GetIntSize(e, &value))
6319                      {
6320                         FreeExpContents(exp);
6321                         exp.constant = PrintInt64((int64)value);
6322                         exp.type = constantExp;
6323                      }
6324                   }
6325                   else
6326                   {
6327                      uintsize value = 0;
6328                      if(GetUIntSize(e, &value))
6329                      {
6330                         FreeExpContents(exp);
6331                         exp.constant = PrintUInt64((uint64)value);
6332                         exp.type = constantExp;
6333                      }
6334                   }
6335                   break;
6336                case floatType:
6337                {
6338                   float value = 0;
6339                   if(GetFloat(e, &value))
6340                   {
6341                      FreeExpContents(exp);
6342                      exp.constant = PrintFloat(value);
6343                      exp.type = constantExp;
6344                   }
6345                   break;
6346                }
6347                case doubleType:
6348                {
6349                   double value = 0;
6350                   if(GetDouble(e, &value))
6351                   {
6352                      FreeExpContents(exp);
6353                      exp.constant = PrintDouble(value);
6354                      exp.type = constantExp;
6355                   }
6356                   break;
6357                }
6358             }
6359          }
6360          break;
6361       }
6362       case conditionExp:
6363       {
6364          Operand op1 { };
6365          Operand op2 { };
6366          Operand op3 { };
6367
6368          if(exp.cond.exp)
6369             // Caring only about last expression for now...
6370             ComputeExpression(exp.cond.exp->last);
6371          if(exp.cond.elseExp)
6372             ComputeExpression(exp.cond.elseExp);
6373          if(exp.cond.cond)
6374             ComputeExpression(exp.cond.cond);
6375
6376          op1 = GetOperand(exp.cond.cond);
6377          if(op1.type) op1.type.refCount++;
6378          op2 = GetOperand(exp.cond.exp->last);
6379          if(op2.type) op2.type.refCount++;
6380          op3 = GetOperand(exp.cond.elseExp);
6381          if(op3.type) op3.type.refCount++;
6382
6383          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6384          if(op1.type) FreeType(op1.type);
6385          if(op2.type) FreeType(op2.type);
6386          if(op3.type) FreeType(op3.type);
6387          break;
6388       }
6389    }
6390 }
6391
6392 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6393 {
6394    bool result = true;
6395    if(destType)
6396    {
6397       OldList converts { };
6398       Conversion convert;
6399
6400       if(destType.kind == voidType)
6401          return false;
6402
6403       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6404          result = false;
6405       if(converts.count)
6406       {
6407          // for(convert = converts.last; convert; convert = convert.prev)
6408          for(convert = converts.first; convert; convert = convert.next)
6409          {
6410             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6411             if(!empty)
6412             {
6413                Expression newExp { };
6414                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6415
6416                // TODO: Check this...
6417                *newExp = *exp;
6418                newExp.prev = null;
6419                newExp.next = null;
6420                newExp.destType = null;
6421
6422                if(convert.isGet)
6423                {
6424                   // [exp].ColorRGB
6425                   exp.type = memberExp;
6426                   exp.addedThis = true;
6427                   exp.member.exp = newExp;
6428                   FreeType(exp.member.exp.expType);
6429
6430                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6431                   exp.member.exp.expType.classObjectType = objectType;
6432                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6433                   exp.member.memberType = propertyMember;
6434                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6435                   // TESTING THIS... for (int)degrees
6436                   exp.needCast = true;
6437                   if(exp.expType) exp.expType.refCount++;
6438                   ApplyAnyObjectLogic(exp.member.exp);
6439                }
6440                else
6441                {
6442
6443                   /*if(exp.isConstant)
6444                   {
6445                      // Color { ColorRGB = [exp] };
6446                      exp.type = instanceExp;
6447                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6448                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6449                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6450                   }
6451                   else*/
6452                   {
6453                      // If not constant, don't turn it yet into an instantiation
6454                      // (Go through the deep members system first)
6455                      exp.type = memberExp;
6456                      exp.addedThis = true;
6457                      exp.member.exp = newExp;
6458
6459                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6460                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6461                         newExp.expType._class.registered.type == noHeadClass)
6462                      {
6463                         newExp.byReference = true;
6464                      }
6465
6466                      FreeType(exp.member.exp.expType);
6467                      /*exp.member.exp.expType = convert.convert.dataType;
6468                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6469                      exp.member.exp.expType = null;
6470                      if(convert.convert.dataType)
6471                      {
6472                         exp.member.exp.expType = { };
6473                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6474                         exp.member.exp.expType.refCount = 1;
6475                         exp.member.exp.expType.classObjectType = objectType;
6476                         ApplyAnyObjectLogic(exp.member.exp);
6477                      }
6478
6479                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6480                      exp.member.memberType = reverseConversionMember;
6481                      exp.expType = convert.resultType ? convert.resultType :
6482                         MkClassType(convert.convert._class.fullName);
6483                      exp.needCast = true;
6484                      if(convert.resultType) convert.resultType.refCount++;
6485                   }
6486                }
6487             }
6488             else
6489             {
6490                FreeType(exp.expType);
6491                if(convert.isGet)
6492                {
6493                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6494                   if(exp.destType.casted)
6495                      exp.needCast = true;
6496                   if(exp.expType) exp.expType.refCount++;
6497                }
6498                else
6499                {
6500                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6501                   if(exp.destType.casted)
6502                      exp.needCast = true;
6503                   if(convert.resultType)
6504                      convert.resultType.refCount++;
6505                }
6506             }
6507          }
6508          if(exp.isConstant && inCompiler)
6509             ComputeExpression(exp);
6510
6511          converts.Free(FreeConvert);
6512       }
6513
6514       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6515       {
6516          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6517       }
6518       if(!result && exp.expType && exp.destType)
6519       {
6520          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6521              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6522             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6523             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6524             result = true;
6525       }
6526    }
6527    // if(result) CheckTemplateTypes(exp);
6528    return result;
6529 }
6530
6531 void CheckTemplateTypes(Expression exp)
6532 {
6533    /*
6534    bool et = exp.expType ? exp.expType.passAsTemplate : false;
6535    bool dt = exp.destType ? exp.destType.passAsTemplate : false;
6536    */
6537    Expression nbExp = GetNonBracketsExp(exp);
6538    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6539       (nbExp == exp || nbExp.type != castExp))
6540    {
6541       Expression newExp { };
6542       Context context;
6543       TypeKind kind = exp.expType.kind;
6544       *newExp = *exp;
6545       if(exp.destType) exp.destType.refCount++;
6546       if(exp.expType)  exp.expType.refCount++;
6547       newExp.prev = null;
6548       newExp.next = null;
6549
6550       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6551       {
6552          Class c = exp.expType._class.registered;
6553          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6554          {
6555             if(!c.dataType)
6556                c.dataType = ProcessTypeString(c.dataTypeString, false);
6557             kind = c.dataType.kind;
6558          }
6559       }
6560
6561       switch(kind)
6562       {
6563          case doubleType:
6564             if(exp.destType.classObjectType)
6565             {
6566                // We need to pass the address, just pass it along (Undo what was done above)
6567                if(exp.destType) exp.destType.refCount--;
6568                if(exp.expType)  exp.expType.refCount--;
6569                delete newExp;
6570             }
6571             else
6572             {
6573                // If we're looking for value:
6574                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6575                OldList * specs;
6576                OldList * unionDefs = MkList();
6577                OldList * statements = MkList();
6578                context = PushContext();
6579                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6580                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6581                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6582                exp.type = extensionCompoundExp;
6583                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6584                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6585                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6586                exp.compound.compound.context = context;
6587                PopContext(context);
6588             }
6589             break;
6590          default:
6591             exp.type = castExp;
6592             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6593             if((exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass) || exp.expType.isPointerType)
6594                exp.cast.exp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), MkExpBrackets(MkListOne(newExp)));
6595             else
6596                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6597             exp.needCast = true;
6598             break;
6599       }
6600    }
6601    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6602    {
6603       Expression newExp { };
6604       Context context;
6605       TypeKind kind = exp.expType.kind;
6606       *newExp = *exp;
6607       if(exp.destType) exp.destType.refCount++;
6608       if(exp.expType)  exp.expType.refCount++;
6609       newExp.prev = null;
6610       newExp.next = null;
6611
6612       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6613       {
6614          Class c = exp.expType._class.registered;
6615          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6616          {
6617             if(!c.dataType)
6618                c.dataType = ProcessTypeString(c.dataTypeString, false);
6619             kind = c.dataType.kind;
6620          }
6621       }
6622
6623       switch(kind)
6624       {
6625          case doubleType:
6626             if(exp.destType.classObjectType)
6627             {
6628                // We need to pass the address, just pass it along (Undo what was done above)
6629                if(exp.destType) exp.destType.refCount--;
6630                if(exp.expType)  exp.expType.refCount--;
6631                delete newExp;
6632             }
6633             else
6634             {
6635                // If we're looking for value:
6636                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6637                OldList * specs;
6638                OldList * unionDefs = MkList();
6639                OldList * statements = MkList();
6640                context = PushContext();
6641                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6642                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6643                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6644                exp.type = extensionCompoundExp;
6645                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6646                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6647                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6648                exp.compound.compound.context = context;
6649                PopContext(context);
6650             }
6651             break;
6652          case classType:
6653          {
6654             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6655             {
6656                exp.type = bracketsExp;
6657
6658                newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6659                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6660                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6661                ProcessExpressionType(exp.list->first);
6662                break;
6663             }
6664             else
6665             {
6666                exp.type = bracketsExp;
6667                if(exp.expType.isPointerType)
6668                {
6669                   exp.needTemplateCast = 2;
6670                   newExp.needCast = true;
6671                   newExp.needTemplateCast = 2;
6672                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6673                }
6674
6675                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6676                exp.needTemplateCast = 2;
6677                newExp.needCast = true;
6678                newExp.needTemplateCast = 2;
6679                ProcessExpressionType(exp.list->first);
6680                break;
6681             }
6682          }
6683          default:
6684          {
6685             if(exp.expType.kind == templateType)
6686             {
6687                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6688                if(type)
6689                {
6690                   FreeType(exp.destType);
6691                   FreeType(exp.expType);
6692                   delete newExp;
6693                   break;
6694                }
6695             }
6696             /*if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6697             {
6698                // When was this required?    Removed to address using templated values to pass to printf()
6699                exp.type = opExp;
6700                exp.op.op = '*';
6701                exp.op.exp1 = null;
6702                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6703                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6704             }
6705             else*/
6706             {
6707                char typeString[1024];
6708                Declarator decl;
6709                OldList * specs = MkList();
6710                typeString[0] = '\0';
6711                PrintType(exp.expType, typeString, false, false);
6712                decl = SpecDeclFromString(typeString, specs, null);
6713
6714                exp.type = castExp;
6715                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6716                exp.cast.typeName = MkTypeName(specs, decl);
6717                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6718                exp.cast.exp.needCast = true;
6719                exp.needTemplateCast = 2;
6720                newExp.needTemplateCast = 2;
6721             }
6722             break;
6723          }
6724       }
6725    }
6726 }
6727 // TODO: The Symbol tree should be reorganized by namespaces
6728 // Name Space:
6729 //    - Tree of all symbols within (stored without namespace)
6730 //    - Tree of sub-namespaces
6731
6732 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6733 {
6734    int nsLen = strlen(nameSpace);
6735    Symbol symbol;
6736    // Start at the name space prefix
6737    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6738    {
6739       char * s = symbol.string;
6740       if(!strncmp(s, nameSpace, nsLen))
6741       {
6742          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6743          int c;
6744          char * namePart;
6745          for(c = strlen(s)-1; c >= 0; c--)
6746             if(s[c] == ':')
6747                break;
6748
6749          namePart = s+c+1;
6750          if(!strcmp(namePart, name))
6751          {
6752             // TODO: Error on ambiguity
6753             return symbol;
6754          }
6755       }
6756       else
6757          break;
6758    }
6759    return null;
6760 }
6761
6762 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6763 {
6764    int c;
6765    char nameSpace[1024];
6766    const char * namePart;
6767    bool gotColon = false;
6768
6769    nameSpace[0] = '\0';
6770    for(c = strlen(name)-1; c >= 0; c--)
6771       if(name[c] == ':')
6772       {
6773          gotColon = true;
6774          break;
6775       }
6776
6777    namePart = name+c+1;
6778    while(c >= 0 && name[c] == ':') c--;
6779    if(c >= 0)
6780    {
6781       // Try an exact match first
6782       Symbol symbol = (Symbol)tree.FindString(name);
6783       if(symbol)
6784          return symbol;
6785
6786       // Namespace specified
6787       memcpy(nameSpace, name, c + 1);
6788       nameSpace[c+1] = 0;
6789
6790       return ScanWithNameSpace(tree, nameSpace, namePart);
6791    }
6792    else if(gotColon)
6793    {
6794       // Looking for a global symbol, e.g. ::Sleep()
6795       Symbol symbol = (Symbol)tree.FindString(namePart);
6796       return symbol;
6797    }
6798    else
6799    {
6800       // Name only (no namespace specified)
6801       Symbol symbol = (Symbol)tree.FindString(namePart);
6802       if(symbol)
6803          return symbol;
6804       return ScanWithNameSpace(tree, "", namePart);
6805    }
6806    return null;
6807 }
6808
6809 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6810 {
6811 #ifdef _DEBUG
6812    //Time startTime = GetTime();
6813 #endif
6814    // Optimize this later? Do this before/less?
6815    Context ctx;
6816    Symbol symbol = null;
6817
6818    // First, check if the identifier is declared inside the function
6819    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6820
6821    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6822    {
6823       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6824       {
6825          symbol = null;
6826          if(thisNameSpace)
6827          {
6828             char curName[1024];
6829             strcpy(curName, thisNameSpace);
6830             strcat(curName, "::");
6831             strcat(curName, name);
6832             // Try to resolve in current namespace first
6833             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6834          }
6835          if(!symbol)
6836             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6837       }
6838       else
6839          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6840
6841       if(symbol || ctx == endContext) break;
6842    }
6843    if(inCompiler && symbol && ctx == globalContext && symbol.pointerExternal && curExternal && symbol.pointerExternal != curExternal)
6844       curExternal.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
6845 #ifdef _DEBUG
6846    //findSymbolTotalTime += GetTime() - startTime;
6847 #endif
6848    return symbol;
6849 }
6850
6851 static void GetTypeSpecs(Type type, OldList * specs)
6852 {
6853    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6854    switch(type.kind)
6855    {
6856       case classType:
6857       {
6858          if(type._class.registered)
6859          {
6860             if(!type._class.registered.dataType)
6861                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6862             GetTypeSpecs(type._class.registered.dataType, specs);
6863          }
6864          break;
6865       }
6866       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6867       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6868       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6869       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6870       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6871       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6872       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6873       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6874       case intType:
6875       default:
6876          ListAdd(specs, MkSpecifier(INT)); break;
6877    }
6878 }
6879
6880 static void PrintArraySize(Type arrayType, char * string)
6881 {
6882    char size[256];
6883    size[0] = '\0';
6884    strcat(size, "[");
6885    if(arrayType.enumClass)
6886       strcat(size, arrayType.enumClass.string);
6887    else if(arrayType.arraySizeExp)
6888       PrintExpression(arrayType.arraySizeExp, size);
6889    strcat(size, "]");
6890    strcat(string, size);
6891 }
6892
6893 // WARNING : This function expects a null terminated string since it recursively concatenate...
6894 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6895 {
6896    if(type)
6897    {
6898       if(printConst && type.constant)
6899          strcat(string, "const ");
6900       switch(type.kind)
6901       {
6902          case classType:
6903          {
6904             Symbol c = type._class;
6905             bool isObjectBaseClass = !c || !c.string || !strcmp(c.string, "class");
6906             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6907             //       look into merging with thisclass ?
6908             if(type.classObjectType == typedObject && isObjectBaseClass)
6909                strcat(string, "typed_object");
6910             else if(type.classObjectType == anyObject && isObjectBaseClass)
6911                strcat(string, "any_object");
6912             else
6913             {
6914                if(c && c.string)
6915                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6916             }
6917             if(type.byReference)
6918                strcat(string, " &");
6919             break;
6920          }
6921          case voidType: strcat(string, "void"); break;
6922          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6923          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6924          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6925          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6926          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6927          case _BoolType: strcat(string, "_Bool"); break;
6928          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6929          case floatType: strcat(string, "float"); break;
6930          case doubleType: strcat(string, "double"); break;
6931          case structType:
6932             if(type.enumName)
6933             {
6934                strcat(string, "struct ");
6935                strcat(string, type.enumName);
6936             }
6937             else if(type.typeName)
6938                strcat(string, type.typeName);
6939             else
6940             {
6941                Type member;
6942                strcat(string, "struct { ");
6943                for(member = type.members.first; member; member = member.next)
6944                {
6945                   PrintType(member, string, true, fullName);
6946                   strcat(string,"; ");
6947                }
6948                strcat(string,"}");
6949             }
6950             break;
6951          case unionType:
6952             if(type.enumName)
6953             {
6954                strcat(string, "union ");
6955                strcat(string, type.enumName);
6956             }
6957             else if(type.typeName)
6958                strcat(string, type.typeName);
6959             else
6960             {
6961                strcat(string, "union ");
6962                strcat(string,"(unnamed)");
6963             }
6964             break;
6965          case enumType:
6966             if(type.enumName)
6967             {
6968                strcat(string, "enum ");
6969                strcat(string, type.enumName);
6970             }
6971             else if(type.typeName)
6972                strcat(string, type.typeName);
6973             else
6974                strcat(string, "int"); // "enum");
6975             break;
6976          case ellipsisType:
6977             strcat(string, "...");
6978             break;
6979          case subClassType:
6980             strcat(string, "subclass(");
6981             strcat(string, type._class ? type._class.string : "int");
6982             strcat(string, ")");
6983             break;
6984          case templateType:
6985             strcat(string, type.templateParameter.identifier.string);
6986             break;
6987          case thisClassType:
6988             strcat(string, "thisclass");
6989             break;
6990          case vaListType:
6991             strcat(string, "__builtin_va_list");
6992             break;
6993       }
6994    }
6995 }
6996
6997 static void PrintName(Type type, char * string, bool fullName)
6998 {
6999    if(type.name && type.name[0])
7000    {
7001       if(fullName)
7002          strcat(string, type.name);
7003       else
7004       {
7005          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
7006          if(name) name += 2; else name = type.name;
7007          strcat(string, name);
7008       }
7009    }
7010 }
7011
7012 static void PrintAttribs(Type type, char * string)
7013 {
7014    if(type)
7015    {
7016       if(type.dllExport)   strcat(string, "dllexport ");
7017       if(type.attrStdcall) strcat(string, "stdcall ");
7018    }
7019 }
7020
7021 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
7022 {
7023    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7024    {
7025       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
7026          PrintAttribs(type, string);
7027       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
7028          strcat(string, " const");
7029       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
7030       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7031          strcat(string, " (");
7032       if(type.kind == pointerType)
7033       {
7034          if(type.type.kind == functionType || type.type.kind == methodType)
7035             PrintAttribs(type.type, string);
7036       }
7037       if(type.kind == pointerType)
7038       {
7039          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7040             strcat(string, "*");
7041          else
7042             strcat(string, " *");
7043       }
7044       if(printConst && type.constant && type.kind == pointerType)
7045          strcat(string, " const");
7046    }
7047    else
7048       PrintTypeSpecs(type, string, fullName, printConst);
7049 }
7050
7051 static void PostPrintType(Type type, char * string, bool fullName)
7052 {
7053    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7054       strcat(string, ")");
7055    if(type.kind == arrayType)
7056       PrintArraySize(type, string);
7057    else if(type.kind == functionType)
7058    {
7059       Type param;
7060       strcat(string, "(");
7061       for(param = type.params.first; param; param = param.next)
7062       {
7063          PrintType(param, string, true, fullName);
7064          if(param.next) strcat(string, ", ");
7065       }
7066       strcat(string, ")");
7067    }
7068    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7069       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7070 }
7071
7072 // *****
7073 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7074 // *****
7075 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7076 {
7077    PrePrintType(type, string, fullName, null, printConst);
7078
7079    if(type.thisClass || (printName && type.name && type.name[0]))
7080       strcat(string, " ");
7081    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7082    {
7083       Symbol _class = type.thisClass;
7084       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7085       {
7086          if(type.classObjectType == classPointer)
7087             strcat(string, "class");
7088          else
7089             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7090       }
7091       else if(_class && _class.string)
7092       {
7093          String s = _class.string;
7094          if(fullName)
7095             strcat(string, s);
7096          else
7097          {
7098             char * name = RSearchString(s, "::", strlen(s), true, false);
7099             if(name) name += 2; else name = s;
7100             strcat(string, name);
7101          }
7102       }
7103       strcat(string, "::");
7104    }
7105
7106    if(printName && type.name)
7107       PrintName(type, string, fullName);
7108    PostPrintType(type, string, fullName);
7109    if(type.bitFieldCount)
7110    {
7111       char count[100];
7112       sprintf(count, ":%d", type.bitFieldCount);
7113       strcat(string, count);
7114    }
7115 }
7116
7117 void PrintType(Type type, char * string, bool printName, bool fullName)
7118 {
7119    _PrintType(type, string, printName, fullName, true);
7120 }
7121
7122 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7123 {
7124    _PrintType(type, string, printName, fullName, false);
7125 }
7126
7127 static Type FindMember(Type type, char * string)
7128 {
7129    Type memberType;
7130    for(memberType = type.members.first; memberType; memberType = memberType.next)
7131    {
7132       if(!memberType.name)
7133       {
7134          Type subType = FindMember(memberType, string);
7135          if(subType)
7136             return subType;
7137       }
7138       else if(!strcmp(memberType.name, string))
7139          return memberType;
7140    }
7141    return null;
7142 }
7143
7144 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7145 {
7146    Type memberType;
7147    for(memberType = type.members.first; memberType; memberType = memberType.next)
7148    {
7149       if(!memberType.name)
7150       {
7151          Type subType = FindMember(memberType, string);
7152          if(subType)
7153          {
7154             *offset += memberType.offset;
7155             return subType;
7156          }
7157       }
7158       else if(!strcmp(memberType.name, string))
7159       {
7160          *offset += memberType.offset;
7161          return memberType;
7162       }
7163    }
7164    return null;
7165 }
7166
7167 public bool GetParseError() { return parseError; }
7168
7169 Expression ParseExpressionString(char * expression)
7170 {
7171    parseError = false;
7172
7173    fileInput = TempFile { };
7174    fileInput.Write(expression, 1, strlen(expression));
7175    fileInput.Seek(0, start);
7176
7177    echoOn = false;
7178    parsedExpression = null;
7179    resetScanner();
7180    expression_yyparse();
7181    delete fileInput;
7182
7183    return parsedExpression;
7184 }
7185
7186 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7187 {
7188    Identifier id = exp.identifier;
7189    Method method = null;
7190    Property prop = null;
7191    DataMember member = null;
7192    ClassProperty classProp = null;
7193
7194    if(_class && _class.type == enumClass)
7195    {
7196       NamedLink64 value = null;
7197       Class enumClass = eSystem_FindClass(privateModule, "enum");
7198       if(enumClass)
7199       {
7200          Class baseClass;
7201          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7202          {
7203             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7204             for(value = e.values.first; value; value = value.next)
7205             {
7206                if(!strcmp(value.name, id.string))
7207                   break;
7208             }
7209             if(value)
7210             {
7211                exp.isConstant = true;
7212                if(inCompiler || inPreCompiler || inDebugger)
7213                {
7214                   char constant[256];
7215                   FreeExpContents(exp);
7216
7217                   exp.type = constantExp;
7218                   if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7219                      sprintf(constant, FORMAT64D, value.data);
7220                   else
7221                      sprintf(constant, FORMAT64HEX, value.data);
7222                   exp.constant = CopyString(constant);
7223                }
7224                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7225                exp.expType = MkClassType(baseClass.fullName);
7226                break;
7227             }
7228          }
7229       }
7230       if(value)
7231          return true;
7232    }
7233    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7234    {
7235       ProcessMethodType(method);
7236       exp.expType = Type
7237       {
7238          refCount = 1;
7239          kind = methodType;
7240          method = method;
7241          // Crash here?
7242          // TOCHECK: Put it back to what it was...
7243          // methodClass = _class;
7244          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7245       };
7246       //id._class = null;
7247       return true;
7248    }
7249    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7250    {
7251       if(!prop.dataType)
7252          ProcessPropertyType(prop);
7253       exp.expType = prop.dataType;
7254       if(prop.dataType) prop.dataType.refCount++;
7255       return true;
7256    }
7257    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7258    {
7259       if(!member.dataType)
7260          member.dataType = ProcessTypeString(member.dataTypeString, false);
7261       exp.expType = member.dataType;
7262       if(member.dataType) member.dataType.refCount++;
7263       return true;
7264    }
7265    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7266    {
7267       if(!classProp.dataType)
7268          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7269
7270       if(classProp.constant)
7271       {
7272          FreeExpContents(exp);
7273
7274          exp.isConstant = true;
7275          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7276          {
7277             //char constant[256];
7278             exp.type = stringExp;
7279             exp.constant = QMkString((char *)(uintptr)classProp.Get(_class));
7280          }
7281          else
7282          {
7283             char constant[256];
7284             exp.type = constantExp;
7285             sprintf(constant, "%d", (int)classProp.Get(_class));
7286             exp.constant = CopyString(constant);
7287          }
7288       }
7289       else
7290       {
7291          // TO IMPLEMENT...
7292       }
7293
7294       exp.expType = classProp.dataType;
7295       if(classProp.dataType) classProp.dataType.refCount++;
7296       return true;
7297    }
7298    return false;
7299 }
7300
7301 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7302 {
7303    BinaryTree * tree = &nameSpace.functions;
7304    GlobalData data = (GlobalData)tree->FindString(name);
7305    NameSpace * child;
7306    if(!data)
7307    {
7308       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7309       {
7310          data = ScanGlobalData(child, name);
7311          if(data)
7312             break;
7313       }
7314    }
7315    return data;
7316 }
7317
7318 static GlobalData FindGlobalData(char * name)
7319 {
7320    int start = 0, c;
7321    NameSpace * nameSpace;
7322    nameSpace = globalData;
7323    for(c = 0; name[c]; c++)
7324    {
7325       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7326       {
7327          NameSpace * newSpace;
7328          char * spaceName = new char[c - start + 1];
7329          strncpy(spaceName, name + start, c - start);
7330          spaceName[c-start] = '\0';
7331          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7332          delete spaceName;
7333          if(!newSpace)
7334             return null;
7335          nameSpace = newSpace;
7336          if(name[c] == ':') c++;
7337          start = c+1;
7338       }
7339    }
7340    if(c - start)
7341    {
7342       return ScanGlobalData(nameSpace, name + start);
7343    }
7344    return null;
7345 }
7346
7347 static int definedExpStackPos;
7348 static void * definedExpStack[512];
7349
7350 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7351 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7352 {
7353    Expression prev = checkedExp.prev, next = checkedExp.next;
7354
7355    FreeExpContents(checkedExp);
7356    FreeType(checkedExp.expType);
7357    FreeType(checkedExp.destType);
7358
7359    *checkedExp = *newExp;
7360
7361    delete newExp;
7362
7363    checkedExp.prev = prev;
7364    checkedExp.next = next;
7365 }
7366
7367 void ApplyAnyObjectLogic(Expression e)
7368 {
7369    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7370 #ifdef _DEBUG
7371    char debugExpString[4096];
7372    debugExpString[0] = '\0';
7373    PrintExpression(e, debugExpString);
7374 #endif
7375
7376    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7377    {
7378       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7379       //ellipsisDestType = destType;
7380       if(e && e.expType)
7381       {
7382          Type type = e.expType;
7383          Class _class = null;
7384          //Type destType = e.destType;
7385
7386          if(type.kind == classType && type._class && type._class.registered)
7387          {
7388             _class = type._class.registered;
7389          }
7390          else if(type.kind == subClassType)
7391          {
7392             _class = FindClass("ecere::com::Class").registered;
7393          }
7394          else
7395          {
7396             char string[1024] = "";
7397             Symbol classSym;
7398
7399             PrintTypeNoConst(type, string, false, true);
7400             classSym = FindClass(string);
7401             if(classSym) _class = classSym.registered;
7402          }
7403
7404          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...
7405             (!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))) ||
7406             destType.byReference)))
7407          {
7408             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7409             {
7410                Expression checkedExp = e, newExp;
7411
7412                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7413                {
7414                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7415                   {
7416                      if(checkedExp.type == extensionCompoundExp)
7417                      {
7418                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7419                      }
7420                      else
7421                         checkedExp = checkedExp.list->last;
7422                   }
7423                   else if(checkedExp.type == castExp)
7424                      checkedExp = checkedExp.cast.exp;
7425                }
7426
7427                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7428                {
7429                   newExp = checkedExp.op.exp2;
7430                   checkedExp.op.exp2 = null;
7431                   FreeExpContents(checkedExp);
7432
7433                   if(e.expType && e.expType.passAsTemplate)
7434                   {
7435                      char size[100];
7436                      ComputeTypeSize(e.expType);
7437                      sprintf(size, "%d", e.expType.size);   // Potential 32/64 Bootstrap issue
7438                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7439                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7440                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7441                   }
7442
7443                   ReplaceExpContents(checkedExp, newExp);
7444                   e.byReference = true;
7445                }
7446                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7447                {
7448                   Expression checkedExp; //, newExp;
7449
7450                   {
7451                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7452                      bool hasAddress =
7453                         e.type == identifierExp ||
7454                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7455                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7456                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7457                         e.type == indexExp;
7458
7459                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7460                      {
7461                         Context context = PushContext();
7462                         Declarator decl;
7463                         OldList * specs = MkList();
7464                         char typeString[1024];
7465                         Expression newExp { };
7466
7467                         typeString[0] = '\0';
7468                         *newExp = *e;
7469
7470                         //if(e.destType) e.destType.refCount++;
7471                         // if(exp.expType) exp.expType.refCount++;
7472                         newExp.prev = null;
7473                         newExp.next = null;
7474                         newExp.expType = null;
7475
7476                         PrintTypeNoConst(e.expType, typeString, false, true);
7477                         decl = SpecDeclFromString(typeString, specs, null);
7478                         newExp.destType = ProcessType(specs, decl);
7479
7480                         curContext = context;
7481
7482                         // We need a current compound for this
7483                         if(curCompound)
7484                         {
7485                            char name[100];
7486                            OldList * stmts = MkList();
7487                            e.type = extensionCompoundExp;
7488                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7489                            if(!curCompound.compound.declarations)
7490                               curCompound.compound.declarations = MkList();
7491                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7492                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7493                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7494                            e.compound = MkCompoundStmt(null, stmts);
7495                         }
7496                         else
7497                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7498
7499                         /*
7500                         e.compound = MkCompoundStmt(
7501                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7502                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7503
7504                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7505                         */
7506
7507                         {
7508                            Type type = e.destType;
7509                            e.destType = { };
7510                            CopyTypeInto(e.destType, type);
7511                            e.destType.refCount = 1;
7512                            e.destType.classObjectType = none;
7513                            FreeType(type);
7514                         }
7515
7516                         e.compound.compound.context = context;
7517                         PopContext(context);
7518                         curContext = context.parent;
7519                      }
7520                   }
7521
7522                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7523                   checkedExp = e;
7524                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7525                   {
7526                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7527                      {
7528                         if(checkedExp.type == extensionCompoundExp)
7529                         {
7530                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7531                         }
7532                         else
7533                            checkedExp = checkedExp.list->last;
7534                      }
7535                      else if(checkedExp.type == castExp)
7536                         checkedExp = checkedExp.cast.exp;
7537                   }
7538                   {
7539                      Expression operand { };
7540                      operand = *checkedExp;
7541                      checkedExp.Clear();
7542                      checkedExp.destType = ProcessTypeString("void *", false);
7543                      checkedExp.expType = checkedExp.destType;
7544                      checkedExp.destType.refCount++;
7545
7546                      checkedExp.type = opExp;
7547                      checkedExp.op.op = '&';
7548                      checkedExp.op.exp1 = null;
7549                      checkedExp.op.exp2 = operand;
7550
7551                      //newExp = MkExpOp(null, '&', checkedExp);
7552                   }
7553                   //ReplaceExpContents(checkedExp, newExp);
7554                }
7555             }
7556          }
7557       }
7558    }
7559    {
7560       // If expression type is a simple class, make it an address
7561       // FixReference(e, true);
7562    }
7563 //#if 0
7564    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7565       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7566          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7567    {
7568       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"))
7569       {
7570          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7571       }
7572       else
7573       {
7574          Expression thisExp { };
7575
7576          *thisExp = *e;
7577          thisExp.prev = null;
7578          thisExp.next = null;
7579          e.Clear();
7580
7581          e.type = bracketsExp;
7582          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7583          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7584             ((Expression)e.list->first).byReference = true;
7585
7586          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7587          {
7588             e.expType = thisExp.expType;
7589             e.expType.refCount++;
7590          }
7591          else*/
7592          {
7593             e.expType = { };
7594             CopyTypeInto(e.expType, thisExp.expType);
7595             e.expType.byReference = false;
7596             e.expType.refCount = 1;
7597
7598             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7599                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7600             {
7601                e.expType.classObjectType = none;
7602             }
7603          }
7604       }
7605    }
7606 // TOFIX: Try this for a nice IDE crash!
7607 //#endif
7608    // The other way around
7609    else
7610 //#endif
7611    if(destType && e.expType &&
7612          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7613          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7614          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7615    {
7616       if(destType.kind == ellipsisType)
7617       {
7618          Compiler_Error($"Unspecified type\n");
7619       }
7620       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7621       {
7622          bool byReference = e.expType.byReference;
7623          Expression thisExp { };
7624          Declarator decl;
7625          OldList * specs = MkList();
7626          char typeString[1024]; // Watch buffer overruns
7627          Type type;
7628          ClassObjectType backupClassObjectType;
7629          bool backupByReference;
7630
7631          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7632             type = e.expType;
7633          else
7634             type = destType;
7635
7636          backupClassObjectType = type.classObjectType;
7637          backupByReference = type.byReference;
7638
7639          type.classObjectType = none;
7640          type.byReference = false;
7641
7642          typeString[0] = '\0';
7643          PrintType(type, typeString, false, true);
7644          decl = SpecDeclFromString(typeString, specs, null);
7645
7646          type.classObjectType = backupClassObjectType;
7647          type.byReference = backupByReference;
7648
7649          *thisExp = *e;
7650          thisExp.prev = null;
7651          thisExp.next = null;
7652          e.Clear();
7653
7654          if( ( type.kind == classType && type._class && type._class.registered &&
7655                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7656                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7657              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7658              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7659          {
7660             bool passAsTemplate = thisExp.destType.passAsTemplate;
7661             Type t;
7662
7663             destType.refCount++;
7664
7665             e.type = opExp;
7666             e.op.op = '*';
7667             e.op.exp1 = null;
7668             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7669
7670             t = { };
7671             CopyTypeInto(t, thisExp.destType);
7672             t.passAsTemplate = false;
7673             FreeType(thisExp.destType);
7674             thisExp.destType = t;
7675
7676             t = { };
7677             CopyTypeInto(t, destType);
7678             t.passAsTemplate = passAsTemplate;
7679             FreeType(destType);
7680             destType = t;
7681             destType.refCount = 0;
7682
7683             e.expType = { };
7684             CopyTypeInto(e.expType, type);
7685             if(type.passAsTemplate)
7686             {
7687                e.expType.classObjectType = none;
7688                e.expType.passAsTemplate = false;
7689             }
7690             e.expType.byReference = false;
7691             e.expType.refCount = 1;
7692          }
7693          else
7694          {
7695             e.type = castExp;
7696             e.cast.typeName = MkTypeName(specs, decl);
7697             e.cast.exp = thisExp;
7698             e.byReference = true;
7699             e.expType = type;
7700             type.refCount++;
7701          }
7702
7703          if(e.destType)
7704             FreeType(e.destType);
7705
7706          e.destType = destType;
7707          destType.refCount++;
7708       }
7709    }
7710 }
7711
7712 void ApplyLocation(Expression exp, Location loc)
7713 {
7714    exp.loc = loc;
7715    switch(exp.type)
7716    {
7717       case opExp:
7718          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7719          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7720          break;
7721       case bracketsExp:
7722          if(exp.list)
7723          {
7724             Expression e;
7725             for(e = exp.list->first; e; e = e.next)
7726                ApplyLocation(e, loc);
7727          }
7728          break;
7729       case indexExp:
7730          if(exp.index.index)
7731          {
7732             Expression e;
7733             for(e = exp.index.index->first; e; e = e.next)
7734                ApplyLocation(e, loc);
7735          }
7736          if(exp.index.exp)
7737             ApplyLocation(exp.index.exp, loc);
7738          break;
7739       case callExp:
7740          if(exp.call.arguments)
7741          {
7742             Expression arg;
7743             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7744                ApplyLocation(arg, loc);
7745          }
7746          if(exp.call.exp)
7747             ApplyLocation(exp.call.exp, loc);
7748          break;
7749       case memberExp:
7750       case pointerExp:
7751          if(exp.member.exp)
7752             ApplyLocation(exp.member.exp, loc);
7753          break;
7754       case castExp:
7755          if(exp.cast.exp)
7756             ApplyLocation(exp.cast.exp, loc);
7757          break;
7758       case conditionExp:
7759          if(exp.cond.exp)
7760          {
7761             Expression e;
7762             for(e = exp.cond.exp->first; e; e = e.next)
7763                ApplyLocation(e, loc);
7764          }
7765          if(exp.cond.cond)
7766             ApplyLocation(exp.cond.cond, loc);
7767          if(exp.cond.elseExp)
7768             ApplyLocation(exp.cond.elseExp, loc);
7769          break;
7770       case vaArgExp:
7771          if(exp.vaArg.exp)
7772             ApplyLocation(exp.vaArg.exp, loc);
7773          break;
7774       default:
7775          break;
7776    }
7777 }
7778
7779 bool RelatedUnits(Class c1, Class c2)
7780 {
7781    if(c1.base.type == unitClass) c1 = c1.base;
7782    if(c2.base.type == unitClass) c2 = c2.base;
7783    return c1 == c2;
7784 }
7785
7786 void ProcessExpressionType(Expression exp)
7787 {
7788    bool unresolved = false;
7789    Location oldyylloc = yylloc;
7790    bool notByReference = false;
7791 #ifdef _DEBUG
7792    char debugExpString[4096];
7793    debugExpString[0] = '\0';
7794    PrintExpression(exp, debugExpString);
7795 #endif
7796    if(!exp || exp.expType)
7797       return;
7798
7799    //eSystem_Logf("%s\n", expString);
7800
7801    // Testing this here
7802    yylloc = exp.loc;
7803    switch(exp.type)
7804    {
7805       case identifierExp:
7806       {
7807          Identifier id = exp.identifier;
7808          if(!id || !topContext) return;
7809
7810          // DOING THIS LATER NOW...
7811          if(id._class && id._class.name)
7812          {
7813             id.classSym = id._class.symbol; // FindClass(id._class.name);
7814             /* TODO: Name Space Fix ups
7815             if(!id.classSym)
7816                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7817             */
7818          }
7819
7820          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7821          {
7822             exp.expType = ProcessTypeString("Module", true);
7823             break;
7824          }
7825          else */
7826          if(!strcmp(id.string, "__runtimePlatform"))
7827          {
7828             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7829             break;
7830          }
7831          else if(strstr(id.string, "__ecereClass") == id.string)
7832          {
7833             exp.expType = ProcessTypeString("ecere::com::Class", true);
7834             break;
7835          }
7836          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7837          {
7838             // Added this here as well
7839             ReplaceClassMembers(exp, thisClass);
7840             if(exp.type != identifierExp)
7841             {
7842                ProcessExpressionType(exp);
7843                break;
7844             }
7845
7846             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7847                break;
7848          }
7849          else
7850          {
7851             Symbol symbol = null;
7852             bool findInGlobal = false;
7853             if(!topContext.parent && exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == enumClass)
7854                findInGlobal = true;  // In global context, look at enum values first
7855             else
7856                symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7857
7858             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7859             if(!symbol/* && exp.destType*/)
7860             {
7861                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7862                   break;
7863                else
7864                {
7865                   if(thisClass)
7866                   {
7867                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7868                      if(exp.type != identifierExp)
7869                      {
7870                         ProcessExpressionType(exp);
7871                         break;
7872                      }
7873                   }
7874                   // Static methods called from inside the _class
7875                   else if(currentClass && !id._class)
7876                   {
7877                      if(ResolveIdWithClass(exp, currentClass, true))
7878                         break;
7879                   }
7880                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7881                }
7882             }
7883             if(findInGlobal)
7884                symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
7885
7886             // If we manage to resolve this symbol
7887             if(symbol)
7888             {
7889                Type type = symbol.type;
7890                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7891
7892                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7893                {
7894                   Context context = SetupTemplatesContext(_class);
7895                   type = ReplaceThisClassType(_class);
7896                   FinishTemplatesContext(context);
7897                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7898                }
7899
7900                FreeSpecifier(id._class);
7901                id._class = null;
7902                delete id.string;
7903                id.string = CopyString(symbol.string);
7904
7905                id.classSym = null;
7906                exp.expType = type;
7907                if(type)
7908                   type.refCount++;
7909
7910                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7911                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7912                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7913                   // Add missing cases here... enum Classes...
7914                   exp.isConstant = true;
7915
7916                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7917                if(symbol.isParam || !strcmp(id.string, "this"))
7918                {
7919                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7920                      exp.byReference = true;
7921
7922                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7923                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7924                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7925                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7926                   {
7927                      Identifier id = exp.identifier;
7928                      exp.type = bracketsExp;
7929                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7930                   }*/
7931                }
7932
7933                if(symbol.isIterator)
7934                {
7935                   if(symbol.isIterator == 3)
7936                   {
7937                      exp.type = bracketsExp;
7938                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7939                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7940                      exp.expType = null;
7941                      ProcessExpressionType(exp);
7942                   }
7943                   else if(symbol.isIterator != 4)
7944                   {
7945                      exp.type = memberExp;
7946                      exp.member.exp = MkExpIdentifier(exp.identifier);
7947                      exp.member.exp.expType = exp.expType;
7948                      /*if(symbol.isIterator == 6)
7949                         exp.member.member = MkIdentifier("key");
7950                      else*/
7951                         exp.member.member = MkIdentifier("data");
7952                      exp.expType = null;
7953                      ProcessExpressionType(exp);
7954                   }
7955                }
7956                break;
7957             }
7958             else
7959             {
7960                DefinedExpression definedExp = null;
7961                if(thisNameSpace && !(id._class && !id._class.name))
7962                {
7963                   char name[1024];
7964                   strcpy(name, thisNameSpace);
7965                   strcat(name, "::");
7966                   strcat(name, id.string);
7967                   definedExp = eSystem_FindDefine(privateModule, name);
7968                }
7969                if(!definedExp)
7970                   definedExp = eSystem_FindDefine(privateModule, id.string);
7971                if(definedExp)
7972                {
7973                   int c;
7974                   for(c = 0; c<definedExpStackPos; c++)
7975                      if(definedExpStack[c] == definedExp)
7976                         break;
7977                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7978                   {
7979                      Location backupYylloc = yylloc;
7980                      File backInput = fileInput;
7981                      definedExpStack[definedExpStackPos++] = definedExp;
7982
7983                      fileInput = TempFile { };
7984                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7985                      fileInput.Seek(0, start);
7986
7987                      echoOn = false;
7988                      parsedExpression = null;
7989                      resetScanner();
7990                      expression_yyparse();
7991                      delete fileInput;
7992                      if(backInput)
7993                         fileInput = backInput;
7994
7995                      yylloc = backupYylloc;
7996
7997                      if(parsedExpression)
7998                      {
7999                         FreeIdentifier(id);
8000                         exp.type = bracketsExp;
8001                         exp.list = MkListOne(parsedExpression);
8002                         ApplyLocation(parsedExpression, yylloc);
8003                         ProcessExpressionType(exp);
8004                         definedExpStackPos--;
8005                         return;
8006                      }
8007                      definedExpStackPos--;
8008                   }
8009                   else
8010                   {
8011                      if(inCompiler)
8012                      {
8013                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
8014                      }
8015                   }
8016                }
8017                else
8018                {
8019                   GlobalData data = null;
8020                   if(thisNameSpace && !(id._class && !id._class.name))
8021                   {
8022                      char name[1024];
8023                      strcpy(name, thisNameSpace);
8024                      strcat(name, "::");
8025                      strcat(name, id.string);
8026                      data = FindGlobalData(name);
8027                   }
8028                   if(!data)
8029                      data = FindGlobalData(id.string);
8030                   if(data)
8031                   {
8032                      DeclareGlobalData(curExternal, data);
8033                      exp.expType = data.dataType;
8034                      if(data.dataType) data.dataType.refCount++;
8035
8036                      delete id.string;
8037                      id.string = CopyString(data.fullName);
8038                      FreeSpecifier(id._class);
8039                      id._class = null;
8040
8041                      break;
8042                   }
8043                   else
8044                   {
8045                      GlobalFunction function = null;
8046                      if(thisNameSpace && !(id._class && !id._class.name))
8047                      {
8048                         char name[1024];
8049                         strcpy(name, thisNameSpace);
8050                         strcat(name, "::");
8051                         strcat(name, id.string);
8052                         function = eSystem_FindFunction(privateModule, name);
8053                      }
8054                      if(!function)
8055                         function = eSystem_FindFunction(privateModule, id.string);
8056                      if(function)
8057                      {
8058                         char name[1024];
8059                         delete id.string;
8060                         id.string = CopyString(function.name);
8061                         name[0] = 0;
8062
8063                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8064                            strcpy(name, "__ecereFunction_");
8065                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8066                         if(DeclareFunction(curExternal, function, name))
8067                         {
8068                            delete id.string;
8069                            id.string = CopyString(name);
8070                         }
8071                         exp.expType = function.dataType;
8072                         if(function.dataType) function.dataType.refCount++;
8073
8074                         FreeSpecifier(id._class);
8075                         id._class = null;
8076
8077                         break;
8078                      }
8079                   }
8080                }
8081             }
8082          }
8083          unresolved = true;
8084          break;
8085       }
8086       case instanceExp:
8087       {
8088          // Class _class;
8089          // Symbol classSym;
8090
8091          if(!exp.instance._class)
8092          {
8093             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8094             {
8095                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8096             }
8097          }
8098
8099          //classSym = FindClass(exp.instance._class.fullName);
8100          //_class = classSym ? classSym.registered : null;
8101
8102          ProcessInstantiationType(exp.instance);
8103
8104          exp.isConstant = exp.instance.isConstant;
8105
8106          /*
8107          if(_class.type == unitClass && _class.base.type != systemClass)
8108          {
8109             {
8110                Type destType = exp.destType;
8111
8112                exp.destType = MkClassType(_class.base.fullName);
8113                exp.expType = MkClassType(_class.fullName);
8114                CheckExpressionType(exp, exp.destType, true);
8115
8116                exp.destType = destType;
8117             }
8118             exp.expType = MkClassType(_class.fullName);
8119          }
8120          else*/
8121          if(exp.instance._class)
8122          {
8123             exp.expType = MkClassType(exp.instance._class.name);
8124             /*if(exp.expType._class && exp.expType._class.registered &&
8125                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8126                exp.expType.byReference = true;*/
8127          }
8128          break;
8129       }
8130       case constantExp:
8131       {
8132          if(!exp.expType)
8133          {
8134             char * constant = exp.constant;
8135             Type type
8136             {
8137                refCount = 1;
8138                constant = true;
8139             };
8140             exp.expType = type;
8141
8142             if(constant[0] == '\'')
8143             {
8144                if((int)((byte *)constant)[1] > 127)
8145                {
8146                   int nb;
8147                   unichar ch = UTF8GetChar(constant + 1, &nb);
8148                   if(nb < 2) ch = constant[1];
8149                   delete constant;
8150                   exp.constant = PrintUInt(ch);
8151                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8152                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8153                   type._class = FindClass("unichar");
8154
8155                   type.isSigned = false;
8156                }
8157                else
8158                {
8159                   type.kind = charType;
8160                   type.isSigned = true;
8161                }
8162             }
8163             else
8164             {
8165                char * dot = strchr(constant, '.');
8166                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8167                char * exponent;
8168                if(isHex)
8169                {
8170                   exponent = strchr(constant, 'p');
8171                   if(!exponent) exponent = strchr(constant, 'P');
8172                }
8173                else
8174                {
8175                   exponent = strchr(constant, 'e');
8176                   if(!exponent) exponent = strchr(constant, 'E');
8177                }
8178
8179                if(dot || exponent)
8180                {
8181                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8182                      type.kind = floatType;
8183                   else
8184                      type.kind = doubleType;
8185                   type.isSigned = true;
8186                }
8187                else
8188                {
8189                   bool isSigned = constant[0] == '-';
8190                   char * endP = null;
8191                   int64 i64 = strtoll(constant, &endP, 0);
8192                   uint64 ui64 = strtoull(constant, &endP, 0);
8193                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8194                   bool forceUnsigned = endP && (!strcmp(endP, "U") || !strcmp(endP, "u") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8195                   if(isSigned)
8196                   {
8197                      if(i64 < MININT)
8198                         is64Bit = true;
8199                   }
8200                   else
8201                   {
8202                      if(ui64 > MAXINT)
8203                      {
8204                         if(ui64 > MAXDWORD)
8205                         {
8206                            is64Bit = true;
8207                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8208                               isSigned = true;
8209                         }
8210                      }
8211                      else if(constant[0] != '0' || !constant[1])
8212                         isSigned = true;
8213                   }
8214                   if(forceUnsigned)
8215                      isSigned = false;
8216                   type.kind = is64Bit ? int64Type : intType;
8217                   type.isSigned = isSigned;
8218                }
8219             }
8220             exp.isConstant = true;
8221             if(exp.destType && exp.destType.kind == doubleType)
8222                type.kind = doubleType;
8223             else if(exp.destType && exp.destType.kind == floatType)
8224                type.kind = floatType;
8225             else if(exp.destType && exp.destType.kind == int64Type)
8226                type.kind = int64Type;
8227          }
8228          break;
8229       }
8230       case stringExp:
8231       {
8232          exp.isConstant = true;      // Why wasn't this constant?
8233          exp.expType = Type
8234          {
8235             refCount = 1;
8236             kind = pointerType;
8237             type = Type
8238             {
8239                refCount = 1;
8240                kind = exp.wideString ? shortType : charType;
8241                constant = true;
8242                isSigned = exp.wideString ? false : true;
8243             }
8244          };
8245          break;
8246       }
8247       case newExp:
8248       case new0Exp:
8249          ProcessExpressionType(exp._new.size);
8250          exp.expType = Type
8251          {
8252             refCount = 1;
8253             kind = pointerType;
8254             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8255          };
8256          DeclareType(curExternal, exp.expType.type, true, false);
8257          break;
8258       case renewExp:
8259       case renew0Exp:
8260          ProcessExpressionType(exp._renew.size);
8261          ProcessExpressionType(exp._renew.exp);
8262          exp.expType = Type
8263          {
8264             refCount = 1;
8265             kind = pointerType;
8266             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8267          };
8268          DeclareType(curExternal, exp.expType.type, true, false);
8269          break;
8270       case opExp:
8271       {
8272          bool assign = false, boolResult = false, boolOps = false;
8273          Type type1 = null, type2 = null;
8274          bool useDestType = false, useSideType = false;
8275          Location oldyylloc = yylloc;
8276          bool useSideUnit = false;
8277          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8278          bool powerOp = false, relationOp = false;
8279          Class c1 = null, c2 = null;
8280
8281          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8282          Type dummy
8283          {
8284             count = 1;
8285             refCount = 1;
8286          };
8287
8288          switch(exp.op.op)
8289          {
8290             // Assignment Operators
8291             case '=':
8292             case MUL_ASSIGN:
8293             case DIV_ASSIGN:
8294             case MOD_ASSIGN:
8295             case ADD_ASSIGN:
8296             case SUB_ASSIGN:
8297             case LEFT_ASSIGN:
8298             case RIGHT_ASSIGN:
8299             case AND_ASSIGN:
8300             case XOR_ASSIGN:
8301             case OR_ASSIGN:
8302                assign = true;
8303                break;
8304             // boolean Operators
8305             case '!':
8306                // Expect boolean operators
8307                //boolOps = true;
8308                //boolResult = true;
8309                break;
8310             case AND_OP:
8311             case OR_OP:
8312                // Expect boolean operands
8313                boolOps = true;
8314                boolResult = true;
8315                break;
8316             // Comparisons
8317             case EQ_OP:
8318             case '<':
8319             case '>':
8320             case LE_OP:
8321             case GE_OP:
8322             case NE_OP:
8323                // Gives boolean result
8324                boolResult = true;
8325                useSideType = true;
8326                relationOp = true;
8327                break;
8328             case '+':
8329             case '-':
8330                useSideUnit = true;
8331                useSideType = true;
8332                useDestType = true;
8333                break;
8334
8335             case LEFT_OP:
8336             case RIGHT_OP:
8337                // useSideType = true;
8338                // useDestType = true;
8339                break;
8340
8341             case '|':
8342             case '^':
8343                useSideType = true;
8344                useDestType = true;
8345                break;
8346
8347             case '/':
8348             case '%':
8349                useSideType = true;
8350                useDestType = true;
8351                if(exp.op.op == '/') powerOp = true;
8352                break;
8353             case '&':
8354             case '*':
8355                if(exp.op.exp1)
8356                {
8357                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8358                   useSideType = true;
8359                   useDestType = true;
8360                   if(exp.op.op == '*') powerOp = true;
8361                }
8362                break;
8363
8364             /*// Implement speed etc.
8365             case '*':
8366             case '/':
8367                break;
8368             */
8369          }
8370          if(exp.op.op == '&')
8371          {
8372             // Added this here earlier for Iterator address as key
8373             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8374             {
8375                Identifier id = exp.op.exp2.identifier;
8376                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8377                if(symbol && symbol.isIterator == 2)
8378                {
8379                   exp.type = memberExp;
8380                   exp.member.exp = exp.op.exp2;
8381                   exp.member.member = MkIdentifier("key");
8382                   exp.expType = null;
8383                   exp.op.exp2.expType = symbol.type;
8384                   symbol.type.refCount++;
8385                   ProcessExpressionType(exp);
8386                   FreeType(dummy);
8387                   break;
8388                }
8389                // exp.op.exp2.usage.usageRef = true;
8390             }
8391          }
8392
8393          //dummy.kind = TypeDummy;
8394          if(exp.op.exp1)
8395          {
8396             // Added this check here to use the dest type only for units derived from the base unit
8397             // So that untyped units will use the side unit as opposed to the untyped destination unit
8398             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8399             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8400                useDestType = false;
8401
8402             if(destClass && useDestType &&
8403               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8404
8405               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8406             {
8407                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8408                exp.op.exp1.destType = exp.destType;
8409                exp.op.exp1.opDestType = true;
8410                if(exp.destType)
8411                   exp.destType.refCount++;
8412             }
8413             else if(!assign)
8414             {
8415                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8416                exp.op.exp1.destType = dummy;
8417                dummy.refCount++;
8418                if(powerOp)
8419                   exp.op.exp1.opDestType = true;
8420                if(relationOp)
8421                   exp.op.exp1.usedInComparison = true;
8422             }
8423             if(exp.op.op == '+' || exp.op.op == '-')
8424             {
8425                if(exp.opDestType)
8426                   exp.op.exp1.parentOpDestType = true;
8427                if(exp.usedInComparison)
8428                   exp.op.exp1.usedInComparison = true;
8429             }
8430
8431             // TESTING THIS HERE...
8432             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8433                ProcessExpressionType(exp.op.exp1);
8434             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8435
8436             exp.op.exp1.opDestType = false;
8437             exp.op.exp1.usedInComparison = false;
8438
8439             // Fix for unit and ++ / --
8440             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8441                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8442             {
8443                exp.op.exp2 = MkExpConstant("1");
8444                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8445                assign = true;
8446             }
8447
8448             if(exp.op.exp1.destType == dummy)
8449             {
8450                FreeType(dummy);
8451                exp.op.exp1.destType = null;
8452             }
8453
8454             if(exp.op.exp2)
8455             {
8456                if(!assign && exp.op.exp1.expType && (exp.op.exp1.expType.kind == charType || exp.op.exp1.expType.kind == shortType))
8457                {
8458                   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 };
8459                   FreeType(exp.op.exp1.expType);
8460                   exp.op.exp1.expType = type;
8461                }
8462             }
8463
8464             type1 = exp.op.exp1.expType;
8465          }
8466
8467          if(exp.op.exp2)
8468          {
8469             char expString[10240];
8470             expString[0] = '\0';
8471             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8472             {
8473                if(exp.op.exp1)
8474                {
8475                   exp.op.exp2.destType = exp.op.exp1.expType;
8476                   if(exp.op.exp1.expType)
8477                      exp.op.exp1.expType.refCount++;
8478                }
8479                else
8480                {
8481                   exp.op.exp2.destType = exp.destType;
8482                   if(!exp.op.exp1 || (exp.op.op != '&' && exp.op.op != '^'))
8483                      exp.op.exp2.opDestType = true;
8484                   if(exp.destType)
8485                      exp.destType.refCount++;
8486                }
8487
8488                if(type1) type1.refCount++;
8489                exp.expType = type1;
8490             }
8491             else if(assign)
8492             {
8493                if(inCompiler)
8494                   PrintExpression(exp.op.exp2, expString);
8495
8496                if(type1 && type1.kind == pointerType)
8497                {
8498                   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 ||
8499                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8500                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8501                   else if(exp.op.op == '=')
8502                   {
8503                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8504                      exp.op.exp2.destType = type1;
8505                      if(type1)
8506                         type1.refCount++;
8507                   }
8508                }
8509                else
8510                {
8511                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8512                   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/* ||
8513                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8514                   else
8515                   {
8516                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8517                      exp.op.exp2.destType = type1;
8518                      if(type1)
8519                         type1.refCount++;
8520                   }
8521                }
8522                if(type1) type1.refCount++;
8523                exp.expType = type1;
8524             }
8525             else if(destClass &&
8526                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8527                   (destClass.type == enumClass && useDestType)))
8528             {
8529                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8530                exp.op.exp2.destType = exp.destType;
8531                if(exp.op.op != '&' && exp.op.op != '^')
8532                   exp.op.exp2.opDestType = true;
8533                if(exp.destType)
8534                   exp.destType.refCount++;
8535             }
8536             else
8537             {
8538                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8539                exp.op.exp2.destType = dummy;
8540                dummy.refCount++;
8541                if(powerOp)
8542                   exp.op.exp2.opDestType = true;
8543                if(relationOp)
8544                   exp.op.exp2.usedInComparison = true;
8545             }
8546
8547             // TESTING THIS HERE... (DANGEROUS)
8548             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8549                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8550             {
8551                FreeType(exp.op.exp2.destType);
8552                exp.op.exp2.destType = type1;
8553                type1.refCount++;
8554             }
8555             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8556             // Cannot lose the cast on a sizeof
8557             if(exp.op.op == SIZEOF)
8558             {
8559                Expression e = exp.op.exp2;
8560                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8561                {
8562                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8563                   {
8564                      if(e.type == extensionCompoundExp)
8565                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8566                      else
8567                         e = e.list->last;
8568                   }
8569                }
8570                if(e.type == castExp && e.cast.exp)
8571                   e.cast.exp.needCast = true;
8572             }
8573             if(exp.op.op == '+' || exp.op.op == '-')
8574             {
8575                if(exp.opDestType)
8576                   exp.op.exp2.parentOpDestType = true;
8577                if(exp.usedInComparison)
8578                   exp.op.exp2.usedInComparison = true;
8579             }
8580             ProcessExpressionType(exp.op.exp2);
8581             exp.op.exp2.opDestType = false;
8582             exp.op.exp2.usedInComparison = false;
8583             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8584
8585             if(!assign && (exp.op.exp1 || exp.op.op == '~'))
8586             {
8587                if(exp.op.exp2.expType && (exp.op.exp2.expType.kind == charType || exp.op.exp2.expType.kind == shortType))
8588                {
8589                   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 };
8590                   FreeType(exp.op.exp2.expType);
8591                   exp.op.exp2.expType = type;
8592                }
8593             }
8594
8595             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8596             {
8597                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)
8598                {
8599                   if(exp.op.op != '=' && type1.type.kind == voidType)
8600                      Compiler_Error($"void *: unknown size\n");
8601                }
8602                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||
8603                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8604                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8605                               exp.op.exp2.expType._class.registered.type == structClass ||
8606                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8607                {
8608                   if(exp.op.op == ADD_ASSIGN)
8609                      Compiler_Error($"cannot add two pointers\n");
8610                }
8611                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8612                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8613                {
8614                   if(exp.op.op == ADD_ASSIGN)
8615                      Compiler_Error($"cannot add two pointers\n");
8616                }
8617                else if(inCompiler)
8618                {
8619                   char type1String[1024];
8620                   char type2String[1024];
8621                   type1String[0] = '\0';
8622                   type2String[0] = '\0';
8623
8624                   PrintType(exp.op.exp2.expType, type1String, false, true);
8625                   PrintType(type1, type2String, false, true);
8626                   ChangeCh(expString, '\n', ' ');
8627                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8628                }
8629             }
8630
8631             if(exp.op.exp2.destType == dummy)
8632             {
8633                FreeType(dummy);
8634                exp.op.exp2.destType = null;
8635             }
8636
8637             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8638             {
8639                type2 = { };
8640                type2.refCount = 1;
8641                CopyTypeInto(type2, exp.op.exp2.expType);
8642                type2.isSigned = true;
8643             }
8644             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8645             {
8646                type2 = { kind = intType };
8647                type2.refCount = 1;
8648                type2.isSigned = true;
8649             }
8650             else
8651             {
8652                type2 = exp.op.exp2.expType;
8653                if(type2) type2.refCount++;
8654             }
8655          }
8656          c1 = type1 && type1.kind == classType && type1._class ? type1._class.registered : null;
8657          c2 = type2 && type2.kind == classType && type2._class ? type2._class.registered : null;
8658
8659          if(relationOp &&
8660             ( (exp.op.exp1 && exp.op.exp1.ambiguousUnits && (!c2 || c2.type != unitClass)) ||
8661                (exp.op.exp2 && exp.op.exp2.ambiguousUnits && (!c1 || c1.type != unitClass))) )
8662             Compiler_Warning($"ambiguous units in relation operation\n");
8663
8664          if(!relationOp &&
8665             ((exp.op.exp1 && exp.op.exp1.ambiguousUnits) ||
8666              (exp.op.exp2 && exp.op.exp2.ambiguousUnits)) &&
8667              (!powerOp || !c1 || c1.type != unitClass || !c2 || c2.type != unitClass || !RelatedUnits(c1, c2)))
8668          {
8669             if(exp.opDestType || exp.usedInComparison)
8670                exp.ambiguousUnits = true;
8671             else
8672                Compiler_Warning($"ambiguous units\n");
8673          }
8674
8675          dummy.kind = voidType;
8676
8677          if(exp.op.op == SIZEOF)
8678          {
8679             exp.expType = Type
8680             {
8681                refCount = 1;
8682                kind = intSizeType;
8683             };
8684             exp.isConstant = true;
8685          }
8686          // Get type of dereferenced pointer
8687          else if(exp.op.op == '*' && !exp.op.exp1)
8688          {
8689             exp.expType = Dereference(type2);
8690             if(type2 && type2.kind == classType)
8691                notByReference = true;
8692          }
8693          else if(exp.op.op == '&' && !exp.op.exp1)
8694             exp.expType = Reference(type2);
8695          else if(exp.op.op == LEFT_OP || exp.op.op == RIGHT_OP)
8696          {
8697             if(exp.op.exp1.expType)
8698             {
8699                exp.expType = exp.op.exp1.expType;
8700                exp.expType.refCount++;
8701             }
8702          }
8703          else if(!assign)
8704          {
8705             if(c1 && !c1.dataType)
8706                c1.dataType = ProcessTypeString(c1.dataTypeString, false);
8707             if(c2 && !c2.dataType)
8708                c2.dataType = ProcessTypeString(c2.dataTypeString, false);
8709
8710             if(boolOps)
8711             {
8712                if(exp.op.exp1)
8713                {
8714                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8715                   exp.op.exp1.destType = MkClassType("bool");
8716                   exp.op.exp1.destType.truth = true;
8717                   if(!exp.op.exp1.expType)
8718                      ProcessExpressionType(exp.op.exp1);
8719                   else
8720                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8721                   FreeType(exp.op.exp1.expType);
8722                   exp.op.exp1.expType = MkClassType("bool");
8723                   exp.op.exp1.expType.truth = true;
8724                }
8725                if(exp.op.exp2)
8726                {
8727                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8728                   exp.op.exp2.destType = MkClassType("bool");
8729                   exp.op.exp2.destType.truth = true;
8730                   if(!exp.op.exp2.expType)
8731                      ProcessExpressionType(exp.op.exp2);
8732                   else
8733                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8734                   FreeType(exp.op.exp2.expType);
8735                   exp.op.exp2.expType = MkClassType("bool");
8736                   exp.op.exp2.expType.truth = true;
8737                }
8738             }
8739             else if(powerOp && exp.op.exp1 && exp.op.exp2 && ((c1 && c1.type == unitClass) || (c2 && c2.type == unitClass)))
8740             {
8741                // * or / with at least one unit operand
8742                if(c1 && c1.type == unitClass && c2 && c2.type == unitClass)
8743                {
8744                   // This is where we'd handle unit powers e.g. square meters or meters/seconds
8745                   // For now using base types
8746                   if(c1.dataType.kind == doubleType)        exp.expType = c1.dataType;
8747                   else if(c2.dataType.kind == doubleType)   exp.expType = c2.dataType;
8748                   else if(c1.dataType.kind == floatType)    exp.expType = c1.dataType;
8749                   else if(c2.dataType.kind == floatType)    exp.expType = c2.dataType;
8750                   else
8751                      exp.expType = c1.dataType;
8752                }
8753                else if((c1 && c1.type == unitClass) || exp.op.op == '/')   // 1/units should not be typed with unit
8754                   exp.expType = type1;
8755                else
8756                   exp.expType = type2;
8757
8758                if(exp.expType)
8759                   exp.expType.refCount++;
8760             }
8761             else if(exp.op.exp1 && exp.op.exp2 &&
8762                ((useSideType /*&&
8763                      (useSideUnit ||
8764                         ((!c1 || c1.type != unitClass) &&
8765                          (!c2 || c2.type != unitClass)))*/) ||
8766                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8767                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8768             {
8769                if(type1 && type2 &&
8770                   // If either both are class or both are not class
8771                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8772                {
8773                   // Added this check for enum subtraction to result in an int type:
8774                   if(exp.op.op == '-' && ((c1 && c1.type == enumClass) || (c2 && c2.type == enumClass)) )
8775                   {
8776                      Type intType = ProcessTypeString((c1 && c1.dataType.kind == int64Type) || (c2 && c2.dataType.kind == int64Type) ? "int64" : "int", false);
8777
8778                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8779                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8780                      exp.op.exp1.destType = intType;
8781                      exp.op.exp2.destType = intType;
8782                      intType.refCount++;
8783                   }
8784                   else
8785                   {
8786                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8787                      exp.op.exp2.destType = type1;
8788                      type1.refCount++;
8789                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8790                      exp.op.exp1.destType = type2;
8791                      type2.refCount++;
8792                   }
8793
8794                   // Warning here for adding Radians + Degrees with no destination type
8795                   if(!boolResult && !exp.opDestType && (!exp.destType || exp.destType.kind != classType) &&
8796                      c1 && c1.type == unitClass &&
8797                      c2 && c2.type == unitClass &&
8798                      c1 != c2)
8799                   {
8800                      if(exp.usedInComparison || exp.parentOpDestType)
8801                         exp.ambiguousUnits = true;
8802                      else
8803                         Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8804                            type1._class.string, type2._class.string, type1._class.string);
8805                   }
8806
8807                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8808                   {
8809                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8810                      if(argExp)
8811                      {
8812                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8813
8814                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8815                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8816                            exp.op.exp1)));
8817
8818                         ProcessExpressionType(exp.op.exp1);
8819
8820                         if(type2.kind != pointerType)
8821                         {
8822                            ProcessExpressionType(classExp);
8823
8824                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8825
8826                            if(!exp.op.exp2.expType)
8827                            {
8828                               if(type2)
8829                                  FreeType(type2);
8830                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false); c2 = null;
8831                               type2.refCount++;
8832                            }
8833
8834                            ProcessExpressionType(exp.op.exp2);
8835                         }
8836                      }
8837                   }
8838
8839                   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)))
8840                   {
8841                      if(type1.kind != classType && type1.type.kind == voidType)
8842                         Compiler_Error($"void *: unknown size\n");
8843                      exp.expType = type1;
8844                      if(type1) type1.refCount++;
8845                   }
8846                   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)))
8847                   {
8848                      if(type2.kind != classType && type2.type.kind == voidType)
8849                         Compiler_Error($"void *: unknown size\n");
8850                      exp.expType = type2;
8851                      if(type2) type2.refCount++;
8852                   }
8853                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8854                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8855                   {
8856                      Compiler_Warning($"different levels of indirection\n");
8857                   }
8858                   else
8859                   {
8860                      bool success = false;
8861                      if(type1.kind == pointerType && type2.kind == pointerType)
8862                      {
8863                         if(exp.op.op == '+')
8864                            Compiler_Error($"cannot add two pointers\n");
8865                         else if(exp.op.op == '-')
8866                         {
8867                            // Pointer Subtraction gives integer
8868                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8869                            {
8870                               exp.expType = Type
8871                               {
8872                                  kind = intType;
8873                                  refCount = 1;
8874                               };
8875                               success = true;
8876
8877                               if(type1.type.kind == templateType)
8878                               {
8879                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8880                                  if(argExp)
8881                                  {
8882                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8883
8884                                     ProcessExpressionType(classExp);
8885
8886                                     exp.type = bracketsExp;
8887                                     exp.list = MkListOne(MkExpOp(
8888                                        MkExpBrackets(MkListOne(MkExpOp(
8889                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8890                                              , exp.op.op,
8891                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8892                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8893
8894                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8895                                     FreeType(dummy);
8896                                     return;
8897                                  }
8898                               }
8899                            }
8900                         }
8901                      }
8902
8903                      if(!success && exp.op.exp1.type == constantExp)
8904                      {
8905                         // If first expression is constant, try to match that first
8906                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8907                         {
8908                            if(exp.expType) FreeType(exp.expType);
8909                            exp.expType = exp.op.exp1.destType;
8910                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8911                            success = true;
8912                         }
8913                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8914                         {
8915                            if(exp.expType) FreeType(exp.expType);
8916                            exp.expType = exp.op.exp2.destType;
8917                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8918                            success = true;
8919                         }
8920                      }
8921                      else if(!success)
8922                      {
8923                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8924                         {
8925                            if(exp.expType) FreeType(exp.expType);
8926                            exp.expType = exp.op.exp2.destType;
8927                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8928                            success = true;
8929                         }
8930                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8931                         {
8932                            if(exp.expType) FreeType(exp.expType);
8933                            exp.expType = exp.op.exp1.destType;
8934                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8935                            success = true;
8936                         }
8937                      }
8938                      if(!success)
8939                      {
8940                         char expString1[10240];
8941                         char expString2[10240];
8942                         char type1[1024];
8943                         char type2[1024];
8944                         expString1[0] = '\0';
8945                         expString2[0] = '\0';
8946                         type1[0] = '\0';
8947                         type2[0] = '\0';
8948                         if(inCompiler)
8949                         {
8950                            PrintExpression(exp.op.exp1, expString1);
8951                            ChangeCh(expString1, '\n', ' ');
8952                            PrintExpression(exp.op.exp2, expString2);
8953                            ChangeCh(expString2, '\n', ' ');
8954                            PrintType(exp.op.exp1.expType, type1, false, true);
8955                            PrintType(exp.op.exp2.expType, type2, false, true);
8956                         }
8957
8958                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8959                      }
8960                   }
8961                }
8962                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8963                else if(!boolResult && !useSideUnit && c2 && c2.type == unitClass && type1 && type1.kind != classType)
8964                {
8965                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8966                   // Convert e.g. / 4 into / 4.0
8967                   exp.op.exp1.destType = type2._class.registered.dataType;
8968                   if(type2._class.registered.dataType)
8969                      type2._class.registered.dataType.refCount++;
8970                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8971                   exp.expType = type2;
8972                   if(type2) type2.refCount++;
8973                }
8974                else if(!boolResult && !useSideUnit && c1 && c1.type == unitClass && type2 && type2.kind != classType)
8975                {
8976                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8977                   // Convert e.g. / 4 into / 4.0
8978                   exp.op.exp2.destType = type1._class.registered.dataType;
8979                   if(type1._class.registered.dataType)
8980                      type1._class.registered.dataType.refCount++;
8981                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8982                   exp.expType = type1;
8983                   if(type1) type1.refCount++;
8984                }
8985                else if(type1)
8986                {
8987                   bool valid = false;
8988
8989                   if(!boolResult && useSideUnit && c1 && c1.type == unitClass && type2 && type2.kind != classType)
8990                   {
8991                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8992
8993                      exp.op.exp2.destType = c1.dataType;
8994                      exp.op.exp2.destType.refCount++;
8995
8996                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8997                      if(type2)
8998                         FreeType(type2);
8999                      type2 = exp.op.exp2.destType;
9000                      c2 = type2 && type2.kind == classType && type2._class ? type2._class.registered : null;
9001                      if(type2) type2.refCount++;
9002
9003                      exp.expType = type2;
9004                      type2.refCount++;
9005                   }
9006
9007                   if(!boolResult && useSideUnit && c2 && c2.type == unitClass && type1 && type1.kind != classType)
9008                   {
9009                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9010
9011                      exp.op.exp1.destType = c2.dataType;
9012                      exp.op.exp1.destType.refCount++;
9013
9014                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9015                      type1 = exp.op.exp1.destType;
9016                      c1 = type1 && type1.kind == classType && type1._class ? type1._class.registered : null;
9017                      exp.expType = type1;
9018                      type1.refCount++;
9019                   }
9020
9021                   // TESTING THIS NEW CODE
9022                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
9023                   {
9024                      bool op1IsEnum = c1 && c1.type == enumClass;
9025                      bool op2IsEnum = c2 && c2.type == enumClass;
9026                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
9027                      {
9028                         // Convert the enum to an int instead for these operators
9029                         if(op1IsEnum && exp.op.exp2.expType)
9030                         {
9031                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
9032                            {
9033                               if(exp.expType) FreeType(exp.expType);
9034                               exp.expType = exp.op.exp2.expType;
9035                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9036                               valid = true;
9037                            }
9038                         }
9039                         else if(op2IsEnum && exp.op.exp1.expType)
9040                         {
9041                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
9042                            {
9043                               if(exp.expType) FreeType(exp.expType);
9044                               exp.expType = exp.op.exp1.expType;
9045                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9046                               valid = true;
9047                            }
9048                         }
9049                      }
9050                      else
9051                      {
9052                         if(op1IsEnum && exp.op.exp2.expType)
9053                         {
9054                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
9055                            {
9056                               if(exp.expType) FreeType(exp.expType);
9057                               exp.expType = exp.op.exp1.expType;
9058                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9059                               valid = true;
9060                            }
9061                         }
9062                         else if(op2IsEnum && exp.op.exp1.expType)
9063                         {
9064                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
9065                            {
9066                               if(exp.expType) FreeType(exp.expType);
9067                               exp.expType = exp.op.exp2.expType;
9068                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9069                               valid = true;
9070                            }
9071                         }
9072                      }
9073                   }
9074
9075                   if(!valid)
9076                   {
9077                      // 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
9078                      if(c2 && c2.type == unitClass && (!c1 || c1.type != unitClass))
9079                      {
9080                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9081                         exp.op.exp1.destType = type2;
9082                         type2.refCount++;
9083
9084                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9085                         {
9086                            if(exp.expType) FreeType(exp.expType);
9087                            exp.expType = exp.op.exp1.destType;
9088                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9089                         }
9090                      }
9091                      else
9092                      {
9093                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9094                         exp.op.exp2.destType = type1;
9095                         type1.refCount++;
9096
9097                      /*
9098                      // Maybe this was meant to be an enum...
9099                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9100                      {
9101                         Type oldType = exp.op.exp2.expType;
9102                         exp.op.exp2.expType = null;
9103                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
9104                            FreeType(oldType);
9105                         else
9106                            exp.op.exp2.expType = oldType;
9107                      }
9108                      */
9109
9110                      /*
9111                      // TESTING THIS HERE... LATEST ADDITION
9112                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9113                      {
9114                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9115                         exp.op.exp2.destType = type2._class.registered.dataType;
9116                         if(type2._class.registered.dataType)
9117                            type2._class.registered.dataType.refCount++;
9118                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9119
9120                         //exp.expType = type2._class.registered.dataType; //type2;
9121                         //if(type2) type2.refCount++;
9122                      }
9123
9124                      // TESTING THIS HERE... LATEST ADDITION
9125                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9126                      {
9127                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9128                         exp.op.exp1.destType = type1._class.registered.dataType;
9129                         if(type1._class.registered.dataType)
9130                            type1._class.registered.dataType.refCount++;
9131                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9132                         exp.expType = type1._class.registered.dataType; //type1;
9133                         if(type1) type1.refCount++;
9134                      }
9135                      */
9136
9137                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9138                         {
9139                            if(exp.expType) FreeType(exp.expType);
9140                            exp.expType = exp.op.exp2.destType;
9141                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9142                         }
9143                         else if(type1 && type2)
9144                         {
9145                            char expString1[10240];
9146                            char expString2[10240];
9147                            char type1String[1024];
9148                            char type2String[1024];
9149                            expString1[0] = '\0';
9150                            expString2[0] = '\0';
9151                            type1String[0] = '\0';
9152                            type2String[0] = '\0';
9153                            if(inCompiler)
9154                            {
9155                               PrintExpression(exp.op.exp1, expString1);
9156                               ChangeCh(expString1, '\n', ' ');
9157                               PrintExpression(exp.op.exp2, expString2);
9158                               ChangeCh(expString2, '\n', ' ');
9159                               PrintType(exp.op.exp1.expType, type1String, false, true);
9160                               PrintType(exp.op.exp2.expType, type2String, false, true);
9161                            }
9162
9163                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9164
9165                            if(c1 && c1.type == enumClass)
9166                            {
9167                               exp.expType = exp.op.exp1.expType;
9168                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9169                            }
9170                            else if(c2 && c2.type == enumClass)
9171                            {
9172                               exp.expType = exp.op.exp2.expType;
9173                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9174                            }
9175                         }
9176                      }
9177                   }
9178                }
9179                else if(type2)
9180                {
9181                   // Maybe this was meant to be an enum...
9182                   if(c2 && c2.type == enumClass)
9183                   {
9184                      Type oldType = exp.op.exp1.expType;
9185                      exp.op.exp1.expType = null;
9186                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9187                         FreeType(oldType);
9188                      else
9189                         exp.op.exp1.expType = oldType;
9190                   }
9191
9192                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9193                   exp.op.exp1.destType = type2;
9194                   type2.refCount++;
9195                   /*
9196                   // TESTING THIS HERE... LATEST ADDITION
9197                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9198                   {
9199                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9200                      exp.op.exp1.destType = type1._class.registered.dataType;
9201                      if(type1._class.registered.dataType)
9202                         type1._class.registered.dataType.refCount++;
9203                   }
9204
9205                   // TESTING THIS HERE... LATEST ADDITION
9206                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9207                   {
9208                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9209                      exp.op.exp2.destType = type2._class.registered.dataType;
9210                      if(type2._class.registered.dataType)
9211                         type2._class.registered.dataType.refCount++;
9212                   }
9213                   */
9214
9215                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9216                   {
9217                      if(exp.expType) FreeType(exp.expType);
9218                      exp.expType = exp.op.exp1.destType;
9219                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9220                   }
9221                }
9222             }
9223             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9224             {
9225                if(type1 && c2 && c2.type == unitClass)
9226                {
9227                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9228                   // Convert e.g. / 4 into / 4.0
9229                   exp.op.exp1.destType = type2._class.registered.dataType;
9230                   if(type2._class.registered.dataType)
9231                      type2._class.registered.dataType.refCount++;
9232                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9233                }
9234                if(exp.op.op == '!')
9235                {
9236                   exp.expType = MkClassType("bool");
9237                   exp.expType.truth = true;
9238                }
9239                else
9240                {
9241                   exp.expType = type2;
9242                   if(type2) type2.refCount++;
9243                }
9244             }
9245             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9246             {
9247                if(c2 && c2.type == unitClass)
9248                {
9249                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9250                   // Convert e.g. / 4 into / 4.0
9251                   exp.op.exp2.destType = type1._class.registered.dataType;
9252                   if(type1._class.registered.dataType)
9253                      type1._class.registered.dataType.refCount++;
9254                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9255                }
9256                exp.expType = type1;
9257                if(type1) type1.refCount++;
9258             }
9259          }
9260
9261          yylloc = exp.loc;
9262          if(exp.op.exp1 && !exp.op.exp1.expType)
9263          {
9264             char expString[10000];
9265             expString[0] = '\0';
9266             if(inCompiler)
9267             {
9268                PrintExpression(exp.op.exp1, expString);
9269                ChangeCh(expString, '\n', ' ');
9270             }
9271             if(expString[0])
9272                Compiler_Error($"couldn't determine type of %s\n", expString);
9273          }
9274          if(exp.op.exp2 && !exp.op.exp2.expType)
9275          {
9276             char expString[10240];
9277             expString[0] = '\0';
9278             if(inCompiler)
9279             {
9280                PrintExpression(exp.op.exp2, expString);
9281                ChangeCh(expString, '\n', ' ');
9282             }
9283             if(expString[0])
9284                Compiler_Error($"couldn't determine type of %s\n", expString);
9285          }
9286
9287          if(boolResult)
9288          {
9289             FreeType(exp.expType);
9290             exp.expType = MkClassType("bool");
9291             exp.expType.truth = true;
9292          }
9293
9294          if(exp.op.op != SIZEOF)
9295             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9296                (!exp.op.exp2 || exp.op.exp2.isConstant);
9297
9298          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9299          {
9300             DeclareType(curExternal, exp.op.exp2.expType, true, false);
9301          }
9302
9303          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9304             Compiler_Warning($"deleting const qualified object\n");
9305
9306          yylloc = oldyylloc;
9307
9308          FreeType(dummy);
9309          if(type2)
9310             FreeType(type2);
9311          break;
9312       }
9313       case bracketsExp:
9314       case extensionExpressionExp:
9315       {
9316          Expression e;
9317          exp.isConstant = true;
9318          for(e = exp.list->first; e; e = e.next)
9319          {
9320             //bool inced = false;
9321             if(!e.next)
9322             {
9323                FreeType(e.destType);
9324                e.opDestType = exp.opDestType;
9325                e.usedInComparison = exp.usedInComparison;
9326                e.parentOpDestType = exp.parentOpDestType;
9327                e.destType = exp.destType;
9328                if(e.destType) { exp.destType.refCount++; /*e.destType.count++; inced = true;*/ }
9329             }
9330             ProcessExpressionType(e);
9331             if(e.ambiguousUnits)
9332                exp.ambiguousUnits = true;
9333             /*if(inced)
9334                exp.destType.count--;*/
9335             if(!exp.expType && !e.next)
9336             {
9337                exp.expType = e.expType;
9338                if(e.expType) e.expType.refCount++;
9339                exp.needCast = e.needCast;
9340             }
9341             if(!e.isConstant)
9342                exp.isConstant = false;
9343          }
9344
9345          // In case a cast became a member...
9346          e = exp.list->first;
9347          if(!e.next && e.type == memberExp)
9348          {
9349             // Preserve prev, next
9350             Expression next = exp.next, prev = exp.prev;
9351
9352
9353             FreeType(exp.expType);
9354             FreeType(exp.destType);
9355             delete exp.list;
9356
9357             *exp = *e;
9358
9359             exp.prev = prev;
9360             exp.next = next;
9361
9362             delete e;
9363
9364             ProcessExpressionType(exp);
9365          }
9366          break;
9367       }
9368       case indexExp:
9369       {
9370          Expression e;
9371          exp.isConstant = true;
9372
9373          ProcessExpressionType(exp.index.exp);
9374          if(!exp.index.exp.isConstant)
9375             exp.isConstant = false;
9376
9377          if(exp.index.exp.expType)
9378          {
9379             Type source = exp.index.exp.expType;
9380             if(source.kind == classType && source._class && source._class.registered)
9381             {
9382                Class _class = source._class.registered;
9383                Class c = _class.templateClass ? _class.templateClass : _class;
9384                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9385                {
9386                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9387
9388                   if(exp.index.index && exp.index.index->last)
9389                   {
9390                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9391
9392                      if(type.kind == classType) type.constant = true;
9393                      else if(type.kind == pointerType)
9394                      {
9395                         Type t = type;
9396                         while(t.kind == pointerType) t = t.type;
9397                         t.constant = true;
9398                      }
9399
9400                      ((Expression)exp.index.index->last).destType = type;
9401                   }
9402                }
9403             }
9404          }
9405
9406          for(e = exp.index.index->first; e; e = e.next)
9407          {
9408             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9409             {
9410                if(e.destType) FreeType(e.destType);
9411                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9412             }
9413             ProcessExpressionType(e);
9414             if(!e.next)
9415             {
9416                // Check if this type is int
9417             }
9418             if(!e.isConstant)
9419                exp.isConstant = false;
9420          }
9421
9422          if(!exp.expType)
9423             exp.expType = Dereference(exp.index.exp.expType);
9424          if(exp.expType)
9425             DeclareType(curExternal, exp.expType, true, false);
9426          break;
9427       }
9428       case callExp:
9429       {
9430          Expression e;
9431          Type functionType;
9432          Type methodType = null;
9433          char name[1024];
9434          name[0] = '\0';
9435
9436          if(inCompiler)
9437          {
9438             PrintExpression(exp.call.exp,  name);
9439             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9440             {
9441                //exp.call.exp.expType = null;
9442                PrintExpression(exp.call.exp,  name);
9443             }
9444          }
9445          if(exp.call.exp.type == identifierExp)
9446          {
9447             Expression idExp = exp.call.exp;
9448             Identifier id = idExp.identifier;
9449             if(!strcmp(id.string, "__builtin_frame_address"))
9450             {
9451                exp.expType = ProcessTypeString("void *", true);
9452                if(exp.call.arguments && exp.call.arguments->first)
9453                   ProcessExpressionType(exp.call.arguments->first);
9454                break;
9455             }
9456             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9457             {
9458                exp.expType = ProcessTypeString("int", true);
9459                if(exp.call.arguments && exp.call.arguments->first)
9460                   ProcessExpressionType(exp.call.arguments->first);
9461                break;
9462             }
9463             else if(!strcmp(id.string, "Max") ||
9464                !strcmp(id.string, "Min") ||
9465                !strcmp(id.string, "Sgn") ||
9466                !strcmp(id.string, "Abs"))
9467             {
9468                Expression a = null;
9469                Expression b = null;
9470                Expression tempExp1 = null, tempExp2 = null;
9471                if((!strcmp(id.string, "Max") ||
9472                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9473                {
9474                   a = exp.call.arguments->first;
9475                   b = exp.call.arguments->last;
9476                   tempExp1 = a;
9477                   tempExp2 = b;
9478                }
9479                else if(exp.call.arguments->count == 1)
9480                {
9481                   a = exp.call.arguments->first;
9482                   tempExp1 = a;
9483                }
9484
9485                if(a)
9486                {
9487                   exp.call.arguments->Clear();
9488                   idExp.identifier = null;
9489
9490                   FreeExpContents(exp);
9491
9492                   ProcessExpressionType(a);
9493                   if(b)
9494                      ProcessExpressionType(b);
9495
9496                   exp.type = bracketsExp;
9497                   exp.list = MkList();
9498
9499                   if(a.expType && (!b || b.expType))
9500                   {
9501                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9502                      {
9503                         // Use the simpleStruct name/ids for now...
9504                         if(inCompiler)
9505                         {
9506                            OldList * specs = MkList();
9507                            OldList * decls = MkList();
9508                            Declaration decl;
9509                            char temp1[1024], temp2[1024];
9510
9511                            GetTypeSpecs(a.expType, specs);
9512
9513                            if(a && !a.isConstant && a.type != identifierExp)
9514                            {
9515                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9516                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9517                               tempExp1 = QMkExpId(temp1);
9518                               tempExp1.expType = a.expType;
9519                               if(a.expType)
9520                                  a.expType.refCount++;
9521                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9522                            }
9523                            if(b && !b.isConstant && b.type != identifierExp)
9524                            {
9525                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9526                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9527                               tempExp2 = QMkExpId(temp2);
9528                               tempExp2.expType = b.expType;
9529                               if(b.expType)
9530                                  b.expType.refCount++;
9531                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9532                            }
9533
9534                            decl = MkDeclaration(specs, decls);
9535                            if(!curCompound.compound.declarations)
9536                               curCompound.compound.declarations = MkList();
9537                            curCompound.compound.declarations->Insert(null, decl);
9538                         }
9539                      }
9540                   }
9541
9542                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9543                   {
9544                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9545                      ListAdd(exp.list,
9546                         MkExpCondition(MkExpBrackets(MkListOne(
9547                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9548                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9549                      exp.expType = a.expType;
9550                      if(a.expType)
9551                         a.expType.refCount++;
9552                   }
9553                   else if(!strcmp(id.string, "Abs"))
9554                   {
9555                      ListAdd(exp.list,
9556                         MkExpCondition(MkExpBrackets(MkListOne(
9557                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9558                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9559                      exp.expType = a.expType;
9560                      if(a.expType)
9561                         a.expType.refCount++;
9562                   }
9563                   else if(!strcmp(id.string, "Sgn"))
9564                   {
9565                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9566                      ListAdd(exp.list,
9567                         MkExpCondition(MkExpBrackets(MkListOne(
9568                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9569                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9570                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9571                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9572                      exp.expType = ProcessTypeString("int", false);
9573                   }
9574
9575                   FreeExpression(tempExp1);
9576                   if(tempExp2) FreeExpression(tempExp2);
9577
9578                   FreeIdentifier(id);
9579                   break;
9580                }
9581             }
9582          }
9583
9584          {
9585             Type dummy
9586             {
9587                count = 1;
9588                refCount = 1;
9589             };
9590             if(!exp.call.exp.destType)
9591             {
9592                exp.call.exp.destType = dummy;
9593                dummy.refCount++;
9594             }
9595             ProcessExpressionType(exp.call.exp);
9596             if(exp.call.exp.destType == dummy)
9597             {
9598                FreeType(dummy);
9599                exp.call.exp.destType = null;
9600             }
9601             FreeType(dummy);
9602          }
9603
9604          // Check argument types against parameter types
9605          functionType = exp.call.exp.expType;
9606
9607          if(functionType && functionType.kind == TypeKind::methodType)
9608          {
9609             methodType = functionType;
9610             functionType = methodType.method.dataType;
9611
9612             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9613             // TOCHECK: Instead of doing this here could this be done per param?
9614             if(exp.call.exp.expType.usedClass)
9615             {
9616                char typeString[1024];
9617                typeString[0] = '\0';
9618                {
9619                   Symbol back = functionType.thisClass;
9620                   // Do not output class specifier here (thisclass was added to this)
9621                   functionType.thisClass = null;
9622                   PrintType(functionType, typeString, true, true);
9623                   functionType.thisClass = back;
9624                }
9625                if(strstr(typeString, "thisclass"))
9626                {
9627                   OldList * specs = MkList();
9628                   Declarator decl;
9629                   {
9630                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9631
9632                      decl = SpecDeclFromString(typeString, specs, null);
9633
9634                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9635                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9636                         exp.call.exp.expType.usedClass))
9637                         thisClassParams = false;
9638
9639                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9640                      {
9641                         Class backupThisClass = thisClass;
9642                         thisClass = exp.call.exp.expType.usedClass;
9643                         ProcessDeclarator(decl, true);
9644                         thisClass = backupThisClass;
9645                      }
9646
9647                      thisClassParams = true;
9648
9649                      functionType = ProcessType(specs, decl);
9650                      functionType.refCount = 0;
9651                      FinishTemplatesContext(context);
9652
9653                      // Mark parameters that were 'thisclass'
9654                      {
9655                         Type p, op;
9656                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9657                         {
9658                            //p.wasThisClass = op.kind == thisClassType;
9659                            if(op.kind == thisClassType)
9660                               p.thisClassFrom = methodType.method._class;
9661                         }
9662                      }
9663                      if(methodType.method.dataType.returnType.kind == thisClassType)
9664                      {
9665                         // functionType.returnType.wasThisClass = true;
9666                         functionType.returnType.thisClassFrom = methodType.method._class;
9667                      }
9668                   }
9669
9670                   FreeList(specs, FreeSpecifier);
9671                   FreeDeclarator(decl);
9672                 }
9673             }
9674          }
9675          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9676          {
9677             Type type = functionType.type;
9678             if(!functionType.refCount)
9679             {
9680                functionType.type = null;
9681                FreeType(functionType);
9682             }
9683             //methodType = functionType;
9684             functionType = type;
9685          }
9686          if(functionType && functionType.kind != TypeKind::functionType)
9687          {
9688             Compiler_Error($"called object %s is not a function\n", name);
9689          }
9690          else if(functionType)
9691          {
9692             bool emptyParams = false, noParams = false;
9693             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9694             Type type = functionType.params.first;
9695             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9696             int extra = 0;
9697             Location oldyylloc = yylloc;
9698
9699             if(!type) emptyParams = true;
9700
9701             // WORKING ON THIS:
9702             if(functionType.extraParam && e && functionType.thisClass)
9703             {
9704                e.destType = MkClassType(functionType.thisClass.string);
9705                e = e.next;
9706             }
9707
9708             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9709             // Fixed #141 by adding '&& !functionType.extraParam'
9710             if(!functionType.staticMethod && !functionType.extraParam)
9711             {
9712                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9713                   memberExp.member.exp.expType._class)
9714                {
9715                   type = MkClassType(memberExp.member.exp.expType._class.string);
9716                   if(e)
9717                   {
9718                      e.destType = type;
9719                      e = e.next;
9720                      type = functionType.params.first;
9721                   }
9722                   else
9723                      type.refCount = 0;
9724                }
9725                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9726                {
9727                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9728                   type.byReference = functionType.byReference;
9729                   type.typedByReference = functionType.typedByReference;
9730                   if(e)
9731                   {
9732                      // Allow manually passing a class for typed object
9733                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9734                         e = e.next;
9735                      e.destType = type;
9736                      e = e.next;
9737                      type = functionType.params.first;
9738                   }
9739                   else
9740                      type.refCount = 0;
9741                   //extra = 1;
9742                }
9743             }
9744
9745             if(type && type.kind == voidType)
9746             {
9747                noParams = true;
9748                if(!type.refCount) FreeType(type);
9749                type = null;
9750             }
9751
9752             for( ; e; e = e.next)
9753             {
9754                if(!type && !emptyParams)
9755                {
9756                   yylloc = e.loc;
9757                   if(methodType && methodType.methodClass)
9758                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9759                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9760                         noParams ? 0 : functionType.params.count);
9761                   else
9762                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9763                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9764                         noParams ? 0 : functionType.params.count);
9765                   break;
9766                }
9767
9768                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9769                {
9770                   Type templatedType = null;
9771                   Class _class = methodType.usedClass;
9772                   ClassTemplateParameter curParam = null;
9773                   int id = 0;
9774                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9775                   {
9776                      Class sClass;
9777                      for(sClass = _class; sClass; sClass = sClass.base)
9778                      {
9779                         if(sClass.templateClass) sClass = sClass.templateClass;
9780                         id = 0;
9781                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9782                         {
9783                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9784                            {
9785                               Class nextClass;
9786                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9787                               {
9788                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9789                                  id += nextClass.templateParams.count;
9790                               }
9791                               break;
9792                            }
9793                            id++;
9794                         }
9795                         if(curParam) break;
9796                      }
9797                   }
9798                   if(curParam && _class.templateArgs[id].dataTypeString)
9799                   {
9800                      bool constant = type.constant;
9801                      ClassTemplateArgument arg = _class.templateArgs[id];
9802                      {
9803                         Context context = SetupTemplatesContext(_class);
9804
9805                         /*if(!arg.dataType)
9806                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9807                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9808                         FinishTemplatesContext(context);
9809                      }
9810
9811                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9812                      else if(templatedType.kind == pointerType)
9813                      {
9814                         Type t = templatedType.type;
9815                         while(t.kind == pointerType) t = t.type;
9816                         if(constant) t.constant = constant;
9817                      }
9818
9819                      e.destType = templatedType;
9820                      if(templatedType)
9821                      {
9822                         templatedType.passAsTemplate = true;
9823                         // templatedType.refCount++;
9824                      }
9825                   }
9826                   else
9827                   {
9828                      e.destType = type;
9829                      if(type) type.refCount++;
9830                   }
9831                }
9832                else
9833                {
9834                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9835                   {
9836                      e.destType = type.prev;
9837                      e.destType.refCount++;
9838                   }
9839                   else
9840                   {
9841                      e.destType = type;
9842                      if(type) type.refCount++;
9843                   }
9844                }
9845                // Don't reach the end for the ellipsis
9846                if(type && type.kind != ellipsisType)
9847                {
9848                   Type next = type.next;
9849                   if(!type.refCount) FreeType(type);
9850                   type = next;
9851                }
9852             }
9853
9854             if(type && type.kind != ellipsisType)
9855             {
9856                if(methodType && methodType.methodClass)
9857                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9858                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9859                      functionType.params.count + extra);
9860                else
9861                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9862                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9863                      functionType.params.count + extra);
9864             }
9865             yylloc = oldyylloc;
9866             if(type && !type.refCount) FreeType(type);
9867          }
9868          else
9869          {
9870             functionType = Type
9871             {
9872                refCount = 0;
9873                kind = TypeKind::functionType;
9874             };
9875
9876             if(exp.call.exp.type == identifierExp)
9877             {
9878                char * string = exp.call.exp.identifier.string;
9879                if(inCompiler)
9880                {
9881                   Symbol symbol;
9882                   Location oldyylloc = yylloc;
9883
9884                   yylloc = exp.call.exp.identifier.loc;
9885                   if(strstr(string, "__builtin_") == string)
9886                   {
9887                      if(exp.destType)
9888                      {
9889                         functionType.returnType = exp.destType;
9890                         exp.destType.refCount++;
9891                      }
9892                   }
9893                   else
9894                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9895                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9896                   globalContext.symbols.Add((BTNode)symbol);
9897                   if(strstr(symbol.string, "::"))
9898                      globalContext.hasNameSpace = true;
9899
9900                   yylloc = oldyylloc;
9901                }
9902             }
9903             else if(exp.call.exp.type == memberExp)
9904             {
9905                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9906                   exp.call.exp.member.member.string);*/
9907             }
9908             else
9909                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9910
9911             if(!functionType.returnType)
9912             {
9913                functionType.returnType = Type
9914                {
9915                   refCount = 1;
9916                   kind = intType;
9917                };
9918             }
9919          }
9920          if(functionType && functionType.kind == TypeKind::functionType)
9921          {
9922             exp.expType = functionType.returnType;
9923
9924             if(functionType.returnType)
9925                functionType.returnType.refCount++;
9926
9927             if(!functionType.refCount)
9928                FreeType(functionType);
9929          }
9930
9931          if(exp.call.arguments)
9932          {
9933             for(e = exp.call.arguments->first; e; e = e.next)
9934                ProcessExpressionType(e);
9935          }
9936          break;
9937       }
9938       case memberExp:
9939       {
9940          Type type;
9941          Location oldyylloc = yylloc;
9942          bool thisPtr;
9943          Expression checkExp = exp.member.exp;
9944          while(checkExp)
9945          {
9946             if(checkExp.type == castExp)
9947                checkExp = checkExp.cast.exp;
9948             else if(checkExp.type == bracketsExp)
9949                checkExp = checkExp.list ? checkExp.list->first : null;
9950             else
9951                break;
9952          }
9953
9954          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9955          exp.thisPtr = thisPtr;
9956
9957          // DOING THIS LATER NOW...
9958          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9959          {
9960             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9961             /* TODO: Name Space Fix ups
9962             if(!exp.member.member.classSym)
9963                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9964             */
9965          }
9966
9967          ProcessExpressionType(exp.member.exp);
9968          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9969             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9970          {
9971             exp.isConstant = false;
9972          }
9973          else
9974             exp.isConstant = exp.member.exp.isConstant;
9975          type = exp.member.exp.expType;
9976
9977          yylloc = exp.loc;
9978
9979          if(type && (type.kind == templateType))
9980          {
9981             Class _class = thisClass ? thisClass : currentClass;
9982             ClassTemplateParameter param = null;
9983             if(_class)
9984             {
9985                for(param = _class.templateParams.first; param; param = param.next)
9986                {
9987                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9988                      break;
9989                }
9990             }
9991             if(param && param.defaultArg.member)
9992             {
9993                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9994                if(argExp)
9995                {
9996                   Expression expMember = exp.member.exp;
9997                   Declarator decl;
9998                   OldList * specs = MkList();
9999                   char thisClassTypeString[1024];
10000
10001                   FreeIdentifier(exp.member.member);
10002
10003                   ProcessExpressionType(argExp);
10004
10005                   {
10006                      char * colon = strstr(param.defaultArg.memberString, "::");
10007                      if(colon)
10008                      {
10009                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
10010                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
10011                      }
10012                      else
10013                         strcpy(thisClassTypeString, _class.fullName);
10014                   }
10015
10016                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
10017
10018                   exp.expType = ProcessType(specs, decl);
10019                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
10020                   {
10021                      Class expClass = exp.expType._class.registered;
10022                      Class cClass = null;
10023                      int paramCount = 0;
10024                      int lastParam = -1;
10025
10026                      char templateString[1024];
10027                      ClassTemplateParameter param;
10028                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
10029                      for(cClass = expClass; cClass; cClass = cClass.base)
10030                      {
10031                         int p = 0;
10032                         for(param = cClass.templateParams.first; param; param = param.next)
10033                         {
10034                            int id = p;
10035                            Class sClass;
10036                            ClassTemplateArgument arg;
10037                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
10038                            arg = expClass.templateArgs[id];
10039
10040                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
10041                            {
10042                               ClassTemplateParameter cParam;
10043                               //int p = numParams - sClass.templateParams.count;
10044                               int p = 0;
10045                               Class nextClass;
10046                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
10047
10048                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
10049                               {
10050                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
10051                                  {
10052                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10053                                     {
10054                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
10055                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
10056                                        break;
10057                                     }
10058                                  }
10059                               }
10060                            }
10061
10062                            {
10063                               char argument[256];
10064                               argument[0] = '\0';
10065                               /*if(arg.name)
10066                               {
10067                                  strcat(argument, arg.name.string);
10068                                  strcat(argument, " = ");
10069                               }*/
10070                               switch(param.type)
10071                               {
10072                                  case expression:
10073                                  {
10074                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10075                                     char expString[1024];
10076                                     OldList * specs = MkList();
10077                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10078                                     Expression exp;
10079                                     char * string = PrintHexUInt64(arg.expression.ui64);
10080                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10081                                     delete string;
10082
10083                                     ProcessExpressionType(exp);
10084                                     ComputeExpression(exp);
10085                                     expString[0] = '\0';
10086                                     PrintExpression(exp, expString);
10087                                     strcat(argument, expString);
10088                                     // delete exp;
10089                                     FreeExpression(exp);
10090                                     break;
10091                                  }
10092                                  case identifier:
10093                                  {
10094                                     strcat(argument, arg.member.name);
10095                                     break;
10096                                  }
10097                                  case TemplateParameterType::type:
10098                                  {
10099                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10100                                     {
10101                                        if(!strcmp(arg.dataTypeString, "thisclass"))
10102                                           strcat(argument, thisClassTypeString);
10103                                        else
10104                                           strcat(argument, arg.dataTypeString);
10105                                     }
10106                                     break;
10107                                  }
10108                               }
10109                               if(argument[0])
10110                               {
10111                                  if(paramCount) strcat(templateString, ", ");
10112                                  if(lastParam != p - 1)
10113                                  {
10114                                     strcat(templateString, param.name);
10115                                     strcat(templateString, " = ");
10116                                  }
10117                                  strcat(templateString, argument);
10118                                  paramCount++;
10119                                  lastParam = p;
10120                               }
10121                               p++;
10122                            }
10123                         }
10124                      }
10125                      {
10126                         int len = strlen(templateString);
10127                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10128                         templateString[len++] = '>';
10129                         templateString[len++] = '\0';
10130                      }
10131                      {
10132                         Context context = SetupTemplatesContext(_class);
10133                         FreeType(exp.expType);
10134                         exp.expType = ProcessTypeString(templateString, false);
10135                         FinishTemplatesContext(context);
10136                      }
10137                   }
10138
10139                   if(!expMember.expType.isPointerType)
10140                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10141                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10142                   exp.type = bracketsExp;
10143                   exp.list = MkListOne(MkExpOp(null, '*',
10144                   /*opExp;
10145                   exp.op.op = '*';
10146                   exp.op.exp1 = null;
10147                   exp.op.exp2 = */
10148                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10149                      MkExpBrackets(MkListOne(
10150                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10151                            expMember))),
10152                               '+',
10153                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10154                               '+',
10155                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10156
10157                            ));
10158                }
10159             }
10160             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10161                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10162             {
10163                type = ProcessTemplateParameterType(type.templateParameter);
10164             }
10165          }
10166          // TODO: *** This seems to be where we should add method support for all basic types ***
10167          if(type && (type.kind == templateType));
10168          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10169                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10170                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10171                           (type.kind == pointerType && type.type.kind == charType)))
10172          {
10173             Identifier id = exp.member.member;
10174             TypeKind typeKind = type.kind;
10175             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10176             if(typeKind == subClassType && exp.member.exp.type == classExp)
10177             {
10178                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10179                typeKind = classType;
10180             }
10181
10182             if(id)
10183             {
10184                if(typeKind == intType || typeKind == enumType)
10185                   _class = eSystem_FindClass(privateModule, "int");
10186                else if(!_class)
10187                {
10188                   if(type.kind == classType && type._class && type._class.registered)
10189                   {
10190                      _class = type._class.registered;
10191                   }
10192                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10193                   {
10194                      _class = FindClass("char *").registered;
10195                   }
10196                   else if(type.kind == pointerType)
10197                   {
10198                      _class = eSystem_FindClass(privateModule, "uintptr");
10199                      FreeType(exp.expType);
10200                      exp.expType = ProcessTypeString("uintptr", false);
10201                      exp.byReference = true;
10202                   }
10203                   else
10204                   {
10205                      char string[1024] = "";
10206                      Symbol classSym;
10207                      PrintTypeNoConst(type, string, false, true);
10208                      classSym = FindClass(string);
10209                      if(classSym) _class = classSym.registered;
10210                   }
10211                }
10212             }
10213
10214             if(_class && id)
10215             {
10216                /*bool thisPtr =
10217                   (exp.member.exp.type == identifierExp &&
10218                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10219                Property prop = null;
10220                Method method = null;
10221                DataMember member = null;
10222                Property revConvert = null;
10223                ClassProperty classProp = null;
10224
10225                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10226                   exp.member.memberType = propertyMember;
10227
10228                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10229                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10230
10231                if(typeKind != subClassType)
10232                {
10233                   // Prioritize data members over properties for "this"
10234                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10235                   {
10236                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10237                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10238                      {
10239                         prop = eClass_FindProperty(_class, id.string, privateModule);
10240                         if(prop)
10241                            member = null;
10242                      }
10243                      if(!member && !prop)
10244                         prop = eClass_FindProperty(_class, id.string, privateModule);
10245                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10246                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10247                         exp.member.thisPtr = true;
10248                   }
10249                   // Prioritize properties over data members otherwise
10250                   else
10251                   {
10252                      bool useMemberForNonConst = false;
10253                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10254                      if(!id.classSym)
10255                      {
10256                         prop = eClass_FindProperty(_class, id.string, null);
10257
10258                         useMemberForNonConst = prop && exp.destType &&
10259                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10260                               !strncmp(prop.dataTypeString, "const ", 6);
10261
10262                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10263                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10264                      }
10265
10266                      if((!prop || useMemberForNonConst) && !member)
10267                      {
10268                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10269                         if(!method)
10270                         {
10271                            prop = eClass_FindProperty(_class, id.string, privateModule);
10272
10273                            useMemberForNonConst |= prop && exp.destType &&
10274                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10275                                  !strncmp(prop.dataTypeString, "const ", 6);
10276
10277                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10278                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10279                         }
10280                      }
10281
10282                      if(member && prop)
10283                      {
10284                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10285                            prop = null;
10286                         else
10287                            member = null;
10288                      }
10289                   }
10290                }
10291                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10292                   method = eClass_FindMethod(_class, id.string, privateModule);
10293                if(!prop && !member && !method)
10294                {
10295                   if(typeKind == subClassType)
10296                   {
10297                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10298                      if(classProp)
10299                      {
10300                         exp.member.memberType = classPropertyMember;
10301                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10302                      }
10303                      else
10304                      {
10305                         // Assume this is a class_data member
10306                         char structName[1024];
10307                         Identifier id = exp.member.member;
10308                         Expression classExp = exp.member.exp;
10309                         type.refCount++;
10310
10311                         FreeType(classExp.expType);
10312                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10313
10314                         strcpy(structName, "__ecereClassData_");
10315                         FullClassNameCat(structName, type._class.string, false);
10316                         exp.type = pointerExp;
10317                         exp.member.member = id;
10318
10319                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10320                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10321                               MkExpBrackets(MkListOne(MkExpOp(
10322                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10323                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10324                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10325                                  )));
10326
10327                         FreeType(type);
10328
10329                         ProcessExpressionType(exp);
10330                         return;
10331                      }
10332                   }
10333                   else
10334                   {
10335                      // Check for reverse conversion
10336                      // (Convert in an instantiation later, so that we can use
10337                      //  deep properties system)
10338                      Symbol classSym = FindClass(id.string);
10339                      if(classSym)
10340                      {
10341                         Class convertClass = classSym.registered;
10342                         if(convertClass)
10343                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10344                      }
10345                   }
10346                }
10347
10348                //if(!exp.member.exp.destType)
10349                if(exp.member.exp.destType)
10350                   FreeType(exp.member.exp.destType);
10351                {
10352                   if(method && !method._class.symbol)
10353                      method._class.symbol = FindClass(method._class.fullName);
10354                   if(prop && !prop._class.symbol)
10355                      prop._class.symbol = FindClass(prop._class.fullName);
10356
10357                   exp.member.exp.destType = Type
10358                   {
10359                      refCount = 1;
10360                      kind = classType;
10361                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10362                      // wasThisClass = type ? type.wasThisClass : false;
10363                      thisClassFrom = type ? type.thisClassFrom : null;
10364                   };
10365                }
10366
10367                if(prop)
10368                {
10369                   exp.member.memberType = propertyMember;
10370                   if(!prop.dataType)
10371                      ProcessPropertyType(prop);
10372                   exp.expType = prop.dataType;
10373                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10374                   {
10375                      Type type { };
10376                      CopyTypeInto(type, exp.expType);
10377                      type.refCount = 1;
10378                      type.constant = true;
10379                      exp.expType = type;
10380                   }
10381                   else if(prop.dataType)
10382                      prop.dataType.refCount++;
10383                }
10384                else if(member)
10385                {
10386                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10387                   {
10388                      FreeExpContents(exp);
10389                      exp.type = identifierExp;
10390                      exp.identifier = MkIdentifier("class");
10391                      ProcessExpressionType(exp);
10392                      return;
10393                   }
10394
10395                   exp.member.memberType = dataMember;
10396                   DeclareStruct(curExternal, _class.fullName, false, true);
10397                   if(member._class != _class)
10398                      DeclareStruct(curExternal, member._class.fullName, false, true);
10399
10400                   if(!member.dataType)
10401                   {
10402                      Context context = SetupTemplatesContext(_class);
10403                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10404                      FinishTemplatesContext(context);
10405                   }
10406                   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)
10407                      member.dataType.bitMemberSize = ((BitMember)member).size;
10408                   exp.expType = member.dataType;
10409                   if(member.dataType) member.dataType.refCount++;
10410                }
10411                else if(revConvert)
10412                {
10413                   exp.member.memberType = reverseConversionMember;
10414                   exp.expType = MkClassType(revConvert._class.fullName);
10415                }
10416                else if(method)
10417                {
10418                   //if(inCompiler)
10419                   {
10420                      /*if(id._class)
10421                      {
10422                         exp.type = identifierExp;
10423                         exp.identifier = exp.member.member;
10424                      }
10425                      else*/
10426                         exp.member.memberType = methodMember;
10427                   }
10428                   if(!method.dataType)
10429                      ProcessMethodType(method);
10430                   exp.expType = Type
10431                   {
10432                      refCount = 1;
10433                      kind = methodType;
10434                      method = method;
10435                   };
10436
10437                   // Tricky spot here... To use instance versus class virtual table
10438                   // Put it back to what it was... What did we break?
10439
10440                   // Had to put it back for overriding Main of Thread global instance
10441
10442                   //exp.expType.methodClass = _class;
10443                   exp.expType.methodClass = (id && id._class) ? _class : null;
10444
10445                   // Need the actual class used for templated classes
10446                   exp.expType.usedClass = _class;
10447                }
10448                else if(!classProp)
10449                {
10450                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10451                   {
10452                      FreeExpContents(exp);
10453                      exp.type = identifierExp;
10454                      exp.identifier = MkIdentifier("class");
10455                      FreeType(exp.expType);
10456                      exp.expType = MkClassType("ecere::com::Class");
10457                      return;
10458                   }
10459                   yylloc = exp.member.member.loc;
10460                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10461                   if(inCompiler)
10462                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10463                }
10464
10465                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10466                {
10467                   Class tClass;
10468
10469                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10470                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10471
10472                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10473                   {
10474                      int id = 0;
10475                      ClassTemplateParameter curParam = null;
10476                      Class sClass;
10477
10478                      for(sClass = tClass; sClass; sClass = sClass.base)
10479                      {
10480                         id = 0;
10481                         if(sClass.templateClass) sClass = sClass.templateClass;
10482                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10483                         {
10484                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10485                            {
10486                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10487                                  id += sClass.templateParams.count;
10488                               break;
10489                            }
10490                            id++;
10491                         }
10492                         if(curParam) break;
10493                      }
10494
10495                      if(curParam && tClass.templateArgs[id].dataTypeString)
10496                      {
10497                         ClassTemplateArgument arg = tClass.templateArgs[id];
10498                         Context context = SetupTemplatesContext(tClass);
10499                         bool constant = exp.expType.constant;
10500                         bool passAsTemplate = false;
10501                         Class thisClassFrom = null;
10502                         Type t = ProcessTypeString(exp.expType.templateParameter.dataTypeString, false);
10503                         if(t && t.kind == classType && t._class)
10504                            thisClassFrom = t._class.registered;
10505                         else
10506                            // Mark that 'thisClassFrom' was set to something
10507                            thisClassFrom = eSystem_FindClass(GetPrivateModule(), "class");
10508
10509                         FreeType(t);
10510
10511                         passAsTemplate = tClass.templateClass && (exp.expType.kind != templateType ||
10512                            (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType)));
10513
10514                         /*if(!arg.dataType)
10515                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10516                         FreeType(exp.expType);
10517
10518                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10519                         exp.expType.thisClassFrom = thisClassFrom;
10520                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10521                         else if(exp.expType.kind == pointerType)
10522                         {
10523                            Type t = exp.expType.type;
10524                            while(t.kind == pointerType) t = t.type;
10525                            if(constant) t.constant = constant;
10526                         }
10527                         if(exp.expType)
10528                         {
10529                            if(exp.expType.kind == thisClassType)
10530                            {
10531                               FreeType(exp.expType);
10532                               exp.expType = ReplaceThisClassType(_class);
10533                            }
10534
10535                            if(passAsTemplate)
10536                               exp.expType.passAsTemplate = true;
10537                            //exp.expType.refCount++;
10538                            if(!exp.destType)
10539                            {
10540                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10541                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10542                               else if(exp.destType.kind == pointerType)
10543                               {
10544                                  Type t = exp.destType.type;
10545                                  while(t.kind == pointerType) t = t.type;
10546                                  if(constant) t.constant = constant;
10547                               }
10548
10549                               //exp.destType.refCount++;
10550
10551                               if(exp.destType.kind == thisClassType)
10552                               {
10553                                  FreeType(exp.destType);
10554                                  exp.destType = ReplaceThisClassType(_class);
10555                               }
10556                            }
10557                         }
10558                         FinishTemplatesContext(context);
10559                      }
10560                   }
10561                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10562                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10563                   {
10564                      int id = 0;
10565                      ClassTemplateParameter curParam = null;
10566                      Class sClass;
10567
10568                      for(sClass = tClass; sClass; sClass = sClass.base)
10569                      {
10570                         id = 0;
10571                         if(sClass.templateClass) sClass = sClass.templateClass;
10572                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10573                         {
10574                            if(curParam.type == TemplateParameterType::type &&
10575                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10576                            {
10577                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10578                                  id += sClass.templateParams.count;
10579                               break;
10580                            }
10581                            id++;
10582                         }
10583                         if(curParam) break;
10584                      }
10585
10586                      if(curParam)
10587                      {
10588                         ClassTemplateArgument arg = tClass.templateArgs[id];
10589                         Context context = SetupTemplatesContext(tClass);
10590                         Type basicType;
10591                         /*if(!arg.dataType)
10592                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10593
10594                         basicType = ProcessTypeString(arg.dataTypeString, false);
10595                         if(basicType)
10596                         {
10597                            if(basicType.kind == thisClassType)
10598                            {
10599                               FreeType(basicType);
10600                               basicType = ReplaceThisClassType(_class);
10601                            }
10602
10603                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10604                            if(tClass.templateClass)
10605                               basicType.passAsTemplate = true;
10606                            */
10607
10608                            FreeType(exp.expType);
10609
10610                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10611                            //exp.expType.refCount++;
10612                            if(!exp.destType)
10613                            {
10614                               exp.destType = exp.expType;
10615                               exp.destType.refCount++;
10616                            }
10617
10618                            {
10619                               Expression newExp { };
10620                               OldList * specs = MkList();
10621                               Declarator decl;
10622                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10623                               *newExp = *exp;
10624                               if(exp.destType) exp.destType.refCount++;
10625                               if(exp.expType)  exp.expType.refCount++;
10626                               exp.type = castExp;
10627                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10628                               exp.cast.exp = newExp;
10629                               //FreeType(exp.expType);
10630                               //exp.expType = null;
10631                               //ProcessExpressionType(sourceExp);
10632                            }
10633                         }
10634                         FinishTemplatesContext(context);
10635                      }
10636                   }
10637                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10638                   {
10639                      Class expClass = exp.expType._class.registered;
10640                      if(expClass)
10641                      {
10642                         Class cClass = null;
10643                         int p = 0;
10644                         int paramCount = 0;
10645                         int lastParam = -1;
10646                         char templateString[1024];
10647                         ClassTemplateParameter param;
10648                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10649                         while(cClass != expClass)
10650                         {
10651                            Class sClass;
10652                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10653                            cClass = sClass;
10654
10655                            for(param = cClass.templateParams.first; param; param = param.next)
10656                            {
10657                               Class cClassCur = null;
10658                               int cp = 0;
10659                               ClassTemplateParameter paramCur = null;
10660                               ClassTemplateArgument arg;
10661                               while(cClassCur != tClass && !paramCur)
10662                               {
10663                                  Class sClassCur;
10664                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10665                                  cClassCur = sClassCur;
10666
10667                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10668                                  {
10669                                     if(!strcmp(paramCur.name, param.name))
10670                                     {
10671
10672                                        break;
10673                                     }
10674                                     cp++;
10675                                  }
10676                               }
10677                               if(paramCur && paramCur.type == TemplateParameterType::type)
10678                                  arg = tClass.templateArgs[cp];
10679                               else
10680                                  arg = expClass.templateArgs[p];
10681
10682                               {
10683                                  char argument[256];
10684                                  argument[0] = '\0';
10685                                  /*if(arg.name)
10686                                  {
10687                                     strcat(argument, arg.name.string);
10688                                     strcat(argument, " = ");
10689                                  }*/
10690                                  switch(param.type)
10691                                  {
10692                                     case expression:
10693                                     {
10694                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10695                                        char expString[1024];
10696                                        OldList * specs = MkList();
10697                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10698                                        Expression exp;
10699                                        char * string = PrintHexUInt64(arg.expression.ui64);
10700                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10701                                        delete string;
10702
10703                                        ProcessExpressionType(exp);
10704                                        ComputeExpression(exp);
10705                                        expString[0] = '\0';
10706                                        PrintExpression(exp, expString);
10707                                        strcat(argument, expString);
10708                                        // delete exp;
10709                                        FreeExpression(exp);
10710                                        break;
10711                                     }
10712                                     case identifier:
10713                                     {
10714                                        strcat(argument, arg.member.name);
10715                                        break;
10716                                     }
10717                                     case TemplateParameterType::type:
10718                                     {
10719                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10720                                           strcat(argument, arg.dataTypeString);
10721                                        break;
10722                                     }
10723                                  }
10724                                  if(argument[0])
10725                                  {
10726                                     if(paramCount) strcat(templateString, ", ");
10727                                     if(lastParam != p - 1)
10728                                     {
10729                                        strcat(templateString, param.name);
10730                                        strcat(templateString, " = ");
10731                                     }
10732                                     strcat(templateString, argument);
10733                                     paramCount++;
10734                                     lastParam = p;
10735                                  }
10736                               }
10737                               p++;
10738                            }
10739                         }
10740                         {
10741                            int len = strlen(templateString);
10742                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10743                            templateString[len++] = '>';
10744                            templateString[len++] = '\0';
10745                         }
10746
10747                         FreeType(exp.expType);
10748                         {
10749                            Context context = SetupTemplatesContext(tClass);
10750                            exp.expType = ProcessTypeString(templateString, false);
10751                            FinishTemplatesContext(context);
10752                         }
10753                      }
10754                   }
10755                }
10756             }
10757             else
10758                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10759          }
10760          else if(type && (type.kind == structType || type.kind == unionType))
10761          {
10762             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10763             if(memberType)
10764             {
10765                exp.expType = memberType;
10766                if(memberType)
10767                   memberType.refCount++;
10768             }
10769          }
10770          else
10771          {
10772             char expString[10240];
10773             expString[0] = '\0';
10774             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10775             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10776          }
10777
10778          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10779          {
10780             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10781             {
10782                Identifier id = exp.member.member;
10783                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10784                if(_class)
10785                {
10786                   FreeType(exp.expType);
10787                   exp.expType = ReplaceThisClassType(_class);
10788                }
10789             }
10790          }
10791          yylloc = oldyylloc;
10792          break;
10793       }
10794       // Convert x->y into (*x).y
10795       case pointerExp:
10796       {
10797          Type destType = exp.destType;
10798
10799          // DOING THIS LATER NOW...
10800          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10801          {
10802             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10803             /* TODO: Name Space Fix ups
10804             if(!exp.member.member.classSym)
10805                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10806             */
10807          }
10808
10809          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10810          exp.type = memberExp;
10811          if(destType)
10812             destType.count++;
10813          ProcessExpressionType(exp);
10814          if(destType)
10815             destType.count--;
10816          break;
10817       }
10818       case classSizeExp:
10819       {
10820          //ComputeExpression(exp);
10821
10822          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10823          if(classSym && classSym.registered)
10824          {
10825             if(classSym.registered.type == noHeadClass || (classSym.registered.fixed && classSym.registered.structSize))
10826             {
10827                char name[1024];
10828                Class b = classSym.registered;
10829                name[0] = '\0';
10830                DeclareStruct(curExternal, classSym.string, false, true);
10831                FreeSpecifier(exp._class);
10832                FullClassNameCat(name, classSym.string, false);
10833
10834                if(b.offset == 0)
10835                {
10836                   exp.type = typeSizeExp;
10837                   exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10838                }
10839                else
10840                {
10841                   Expression e;
10842                   exp.type = opExp;
10843                   if(b.structSize == b.offset)
10844                      exp.op.exp1 = MkExpConstant("0");
10845                   else
10846                      exp.op.exp1 = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10847                   exp.op.op = '+';
10848                   e = exp;
10849                   while(b.offset != 0)
10850                   {
10851                      Symbol sym;
10852                      Expression typeSize;
10853
10854                      b = b.base;
10855                      sym = FindClass(b.fullName);
10856
10857                      name[0] = '\0';
10858                      DeclareStruct(curExternal, sym.string, false, true);
10859                      FullClassNameCat(name, sym.string, false);
10860
10861                      if(b.structSize == b.offset)
10862                         typeSize = MkExpConstant("0");
10863                      else
10864                         typeSize = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10865                      e.op.exp2 = b.offset ? MkExpOp(typeSize, '+', null) : typeSize;
10866                      e = e.op.exp2;
10867                   }
10868                }
10869             }
10870             else
10871             {
10872                if(classSym.registered.fixed && !classSym.registered.structSize)
10873                {
10874                   FreeSpecifier(exp._class);
10875                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10876                   exp.type = constantExp;
10877                }
10878                else
10879                {
10880                   char className[1024];
10881                   strcpy(className, "__ecereClass_");
10882                   FullClassNameCat(className, classSym.string, true);
10883
10884                   DeclareClass(curExternal, classSym, className);
10885
10886                   FreeExpContents(exp);
10887                   exp.type = pointerExp;
10888                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10889                   exp.member.member = MkIdentifier("structSize");
10890                }
10891             }
10892          }
10893
10894          exp.expType = Type
10895          {
10896             refCount = 1;
10897             kind = intSizeType;
10898          };
10899          // exp.isConstant = true;
10900          break;
10901       }
10902       case typeSizeExp:
10903       {
10904          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10905
10906          exp.expType = Type
10907          {
10908             refCount = 1;
10909             kind = intSizeType;
10910          };
10911          exp.isConstant = true;
10912
10913          DeclareType(curExternal, type, true, false);
10914          FreeType(type);
10915          break;
10916       }
10917       case castExp:
10918       {
10919          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10920          type.count = 1;
10921          FreeType(exp.cast.exp.destType);
10922          exp.cast.exp.destType = type;
10923          type.refCount++;
10924          type.casted = true;
10925          ProcessExpressionType(exp.cast.exp);
10926          type.casted = false;
10927          type.count = 0;
10928          exp.expType = type;
10929          //type.refCount++;
10930
10931          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10932          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10933          {
10934             void * prev = exp.prev, * next = exp.next;
10935             Type expType = exp.cast.exp.destType;
10936             Expression castExp = exp.cast.exp;
10937             Type destType = exp.destType;
10938
10939             if(expType) expType.refCount++;
10940
10941             //FreeType(exp.destType);
10942             FreeType(exp.expType);
10943             FreeTypeName(exp.cast.typeName);
10944
10945             *exp = *castExp;
10946             FreeType(exp.expType);
10947             FreeType(exp.destType);
10948
10949             exp.expType = expType;
10950             exp.destType = destType;
10951
10952             delete castExp;
10953
10954             exp.prev = prev;
10955             exp.next = next;
10956
10957          }
10958          else
10959          {
10960             exp.isConstant = exp.cast.exp.isConstant;
10961          }
10962          //FreeType(type);
10963          break;
10964       }
10965       case extensionInitializerExp:
10966       {
10967          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10968          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10969          // ProcessInitializer(exp.initializer.initializer, type);
10970          exp.expType = type;
10971          break;
10972       }
10973       case vaArgExp:
10974       {
10975          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10976          ProcessExpressionType(exp.vaArg.exp);
10977          exp.expType = type;
10978          break;
10979       }
10980       case conditionExp:
10981       {
10982          Expression e;
10983          Type t = exp.destType;
10984          if(t && !exp.destType.casted)
10985          {
10986             t = { };
10987             CopyTypeInto(t, exp.destType);
10988             t.count = 0;
10989          }
10990          else if(t)
10991             t.refCount++;
10992
10993          exp.isConstant = true;
10994
10995          FreeType(exp.cond.cond.destType);
10996          exp.cond.cond.destType = MkClassType("bool");
10997          exp.cond.cond.destType.truth = true;
10998          ProcessExpressionType(exp.cond.cond);
10999          if(!exp.cond.cond.isConstant)
11000             exp.isConstant = false;
11001          for(e = exp.cond.exp->first; e; e = e.next)
11002          {
11003             if(!e.next)
11004             {
11005                FreeType(e.destType);
11006                e.destType = t;
11007                if(e.destType) e.destType.refCount++;
11008             }
11009             ProcessExpressionType(e);
11010             if(!e.next)
11011             {
11012                exp.expType = e.expType;
11013                if(e.expType) e.expType.refCount++;
11014             }
11015             if(!e.isConstant)
11016                exp.isConstant = false;
11017          }
11018
11019          FreeType(exp.cond.elseExp.destType);
11020          // Added this check if we failed to find an expType
11021          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
11022
11023          // Reversed it...
11024          exp.cond.elseExp.destType = t ? t : exp.expType;
11025
11026          if(exp.cond.elseExp.destType)
11027             exp.cond.elseExp.destType.refCount++;
11028          ProcessExpressionType(exp.cond.elseExp);
11029
11030          // FIXED THIS: Was done before calling process on elseExp
11031          if(!exp.cond.elseExp.isConstant)
11032             exp.isConstant = false;
11033
11034          FreeType(t);
11035          break;
11036       }
11037       case extensionCompoundExp:
11038       {
11039          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
11040          {
11041             Statement last = exp.compound.compound.statements->last;
11042             if(last.type == expressionStmt && last.expressions && last.expressions->last)
11043             {
11044                ((Expression)last.expressions->last).destType = exp.destType;
11045                if(exp.destType)
11046                   exp.destType.refCount++;
11047             }
11048             ProcessStatement(exp.compound);
11049             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
11050             if(exp.expType)
11051                exp.expType.refCount++;
11052          }
11053          break;
11054       }
11055       case classExp:
11056       {
11057          Specifier spec = exp._classExp.specifiers->first;
11058          if(spec && spec.type == nameSpecifier)
11059          {
11060             exp.expType = MkClassType(spec.name);
11061             exp.expType.kind = subClassType;
11062             exp.byReference = true;
11063          }
11064          else
11065          {
11066             exp.expType = MkClassType("ecere::com::Class");
11067             exp.byReference = true;
11068          }
11069          break;
11070       }
11071       case classDataExp:
11072       {
11073          Class _class = thisClass ? thisClass : currentClass;
11074          if(_class)
11075          {
11076             Identifier id = exp.classData.id;
11077             char structName[1024];
11078             Expression classExp;
11079             strcpy(structName, "__ecereClassData_");
11080             FullClassNameCat(structName, _class.fullName, false);
11081             exp.type = pointerExp;
11082             exp.member.member = id;
11083             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
11084                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
11085             else
11086                classExp = MkExpIdentifier(MkIdentifier("class"));
11087
11088             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
11089                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
11090                   MkExpBrackets(MkListOne(MkExpOp(
11091                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
11092                         MkExpMember(classExp, MkIdentifier("data"))), '+',
11093                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
11094                      )));
11095
11096             ProcessExpressionType(exp);
11097             return;
11098          }
11099          break;
11100       }
11101       case arrayExp:
11102       {
11103          Type type = null;
11104          const char * typeString = null;
11105          char typeStringBuf[1024];
11106          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
11107             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
11108          {
11109             Class templateClass = exp.destType._class.registered;
11110             typeString = templateClass.templateArgs[2].dataTypeString;
11111          }
11112          else if(exp.list)
11113          {
11114             // Guess type from expressions in the array
11115             Expression e;
11116             for(e = exp.list->first; e; e = e.next)
11117             {
11118                ProcessExpressionType(e);
11119                if(e.expType)
11120                {
11121                   if(!type) { type = e.expType; type.refCount++; }
11122                   else
11123                   {
11124                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11125                      if(!MatchTypeExpression(e, type, null, false, true))
11126                      {
11127                         FreeType(type);
11128                         type = e.expType;
11129                         e.expType = null;
11130
11131                         e = exp.list->first;
11132                         ProcessExpressionType(e);
11133                         if(e.expType)
11134                         {
11135                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
11136                            if(!MatchTypeExpression(e, type, null, false, true))
11137                            {
11138                               FreeType(e.expType);
11139                               e.expType = null;
11140                               FreeType(type);
11141                               type = null;
11142                               break;
11143                            }
11144                         }
11145                      }
11146                   }
11147                   if(e.expType)
11148                   {
11149                      FreeType(e.expType);
11150                      e.expType = null;
11151                   }
11152                }
11153             }
11154             if(type)
11155             {
11156                typeStringBuf[0] = '\0';
11157                PrintTypeNoConst(type, typeStringBuf, false, true);
11158                typeString = typeStringBuf;
11159                FreeType(type);
11160                type = null;
11161             }
11162          }
11163          if(typeString)
11164          {
11165             /*
11166             (Container)& (struct BuiltInContainer)
11167             {
11168                ._vTbl = class(BuiltInContainer)._vTbl,
11169                ._class = class(BuiltInContainer),
11170                .refCount = 0,
11171                .data = (int[]){ 1, 7, 3, 4, 5 },
11172                .count = 5,
11173                .type = class(int),
11174             }
11175             */
11176             char templateString[1024];
11177             OldList * initializers = MkList();
11178             OldList * structInitializers = MkList();
11179             OldList * specs = MkList();
11180             Expression expExt;
11181             Declarator decl = SpecDeclFromString(typeString, specs, null);
11182             sprintf(templateString, "Container<%s>", typeString);
11183
11184             if(exp.list)
11185             {
11186                Expression e;
11187                type = ProcessTypeString(typeString, false);
11188                while((e = exp.list->first))
11189                {
11190                   exp.list->Remove(e);
11191                   e.destType = type;
11192                   type.refCount++;
11193                   ProcessExpressionType(e);
11194                   ListAdd(initializers, MkInitializerAssignment(e));
11195                }
11196                FreeType(type);
11197                delete exp.list;
11198             }
11199
11200             DeclareStruct(curExternal, "ecere::com::BuiltInContainer", false, true);
11201
11202             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11203                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11204             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11205                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11206             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11207                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11208             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11209                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11210                MkInitializerList(initializers))));
11211                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11212             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11213                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11214             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11215                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11216             exp.expType = ProcessTypeString(templateString, false);
11217             exp.type = bracketsExp;
11218             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11219                MkExpOp(null, '&',
11220                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11221                   MkInitializerList(structInitializers)))));
11222             ProcessExpressionType(expExt);
11223          }
11224          else
11225          {
11226             exp.expType = ProcessTypeString("Container", false);
11227             Compiler_Error($"Couldn't determine type of array elements\n");
11228          }
11229          break;
11230       }
11231    }
11232
11233    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11234    {
11235       FreeType(exp.expType);
11236       exp.expType = ReplaceThisClassType(thisClass);
11237    }
11238
11239    // Resolve structures here
11240    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11241    {
11242       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11243       // TODO: Fix members reference...
11244       if(symbol)
11245       {
11246          if(exp.expType.kind != enumType)
11247          {
11248             Type member;
11249             String enumName = CopyString(exp.expType.enumName);
11250
11251             // Fixed a memory leak on self-referencing C structs typedefs
11252             // by instantiating a new type rather than simply copying members
11253             // into exp.expType
11254             FreeType(exp.expType);
11255             exp.expType = Type { };
11256             exp.expType.kind = symbol.type.kind;
11257             exp.expType.refCount++;
11258             exp.expType.enumName = enumName;
11259
11260             exp.expType.members = symbol.type.members;
11261             for(member = symbol.type.members.first; member; member = member.next)
11262                member.refCount++;
11263          }
11264          else
11265          {
11266             NamedLink64 member;
11267             for(member = symbol.type.members.first; member; member = member.next)
11268             {
11269                NamedLink64 value { name = CopyString(member.name) };
11270                exp.expType.members.Add(value);
11271             }
11272          }
11273       }
11274    }
11275
11276    // Trying to do this here before conversion properties kick in and this becomes a new expression... (Fixing Class c; const char * a = c;)
11277    // Mark nohead classes as by reference, unless we're casting them to an integral type
11278    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11279       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11280          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11281           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11282    {
11283       exp.byReference = true;
11284    }
11285
11286    yylloc = exp.loc;
11287    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11288    else if(exp.destType && !exp.destType.keepCast)
11289    {
11290       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11291          exp.needTemplateCast = 1;
11292
11293       if(exp.destType.kind == voidType);
11294       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11295       {
11296          // Warn for casting unrelated types to/from struct classes
11297          bool invalidCast = false;
11298          if(inCompiler && exp.destType.count && exp.expType)
11299          {
11300             Class c1 = (exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
11301             Class c2 = (exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
11302             if(c1 && c1.type != structClass) c1 = null;
11303             if(c2 && c2.type != structClass) c2 = null;
11304             if((c1 && !exp.expType.byReference && !c2 && !exp.destType.isPointerType) || (c2 && !exp.destType.byReference && !c1 && !exp.expType.isPointerType))
11305                invalidCast = true;
11306          }
11307          if(!exp.destType.count || unresolved || invalidCast)
11308          {
11309             if(!exp.expType)
11310             {
11311                yylloc = exp.loc;
11312                if(exp.destType.kind != ellipsisType)
11313                {
11314                   char type2[1024];
11315                   type2[0] = '\0';
11316                   if(inCompiler)
11317                   {
11318                      char expString[10240];
11319                      expString[0] = '\0';
11320
11321                      PrintType(exp.destType, type2, false, true);
11322
11323                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11324                      if(unresolved)
11325                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11326                      else if(exp.type != dummyExp)
11327                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11328                   }
11329                }
11330                else
11331                {
11332                   char expString[10240] ;
11333                   expString[0] = '\0';
11334                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11335
11336                   if(unresolved)
11337                      Compiler_Error($"unresolved identifier %s\n", expString);
11338                   else if(exp.type != dummyExp)
11339                      Compiler_Error($"couldn't determine type of %s\n", expString);
11340                }
11341             }
11342             else
11343             {
11344                char type1[1024];
11345                char type2[1024];
11346                type1[0] = '\0';
11347                type2[0] = '\0';
11348                if(inCompiler)
11349                {
11350                   PrintType(exp.expType, type1, false, true);
11351                   PrintType(exp.destType, type2, false, true);
11352                }
11353
11354                //CheckExpressionType(exp, exp.destType, false);
11355
11356                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11357                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11358                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11359                else
11360                {
11361                   Expression nbExp = GetNonBracketsExp(exp);
11362                   bool skipWarning = false;
11363                   TypeKind kind = exp.destType.kind;
11364                   if(nbExp.type == conditionExp && nbExp.destType && !nbExp.destType.casted && nbExp.destType.kind == exp.destType.kind)
11365                      // The if/else operands have already been checked / warned about
11366                      skipWarning = true;
11367                   if((kind == charType || kind == shortType) && exp.destType.isSigned == exp.expType.signedBeforePromotion && nbExp.type == opExp && nbExp.op.exp1 && nbExp.op.exp2)
11368                   {
11369                      int op = nbExp.op.op;
11370                      Expression nbExp1, nbExp2;
11371                      TypeKind from;
11372
11373                      switch(op)
11374                      {
11375                         case '%': case '/':
11376                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11377                            from = nbExp1.expType.promotedFrom;
11378                            // Division and Modulo will not take more room than type before promotion
11379                            if(from == charType || (kind == shortType && from == shortType))
11380                               skipWarning = true;
11381                            break;
11382                         // Left shift
11383                         case LEFT_OP: case RIGHT_OP:
11384                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11385                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11386                            from = nbExp1.expType.promotedFrom;
11387                            // Right shift will not take more room than type before promotion
11388                            if(op == RIGHT_OP && (from == charType || (kind == shortType && from == shortType)))
11389                               skipWarning = true;
11390                            else if(nbExp2.isConstant && nbExp2.type == constantExp && (nbExp.op.op == RIGHT_OP || nbExp1.expType.bitMemberSize))
11391                            {
11392                               int n = (int)strtol(nbExp2.constant, null, 0);
11393                               int s = from == charType ? 8 : 16;
11394                               // Left shifting a bit member constrained in size may still fit in type before promotion
11395                               if(nbExp1.expType.bitMemberSize && nbExp1.expType.bitMemberSize < s)
11396                                  s = nbExp1.expType.bitMemberSize;
11397
11398                               // If right shifted enough things will fit in smaller type
11399                               if(nbExp.op.op == RIGHT_OP)
11400                                  s -= n;
11401                               else
11402                                  s += n;
11403                               if(s <= (kind == charType ? 8 : 16))
11404                                  skipWarning = true;
11405                            }
11406                            break;
11407                         case '-':
11408                            if(!exp.destType.isSigned)
11409                            {
11410                               nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11411                               nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11412                               from = nbExp2.expType.promotedFrom;
11413                               // Max value of unsigned type before promotion minus the same will always fit
11414                               if((from == charType || from == shortType) && nbExp1.isConstant && nbExp1.type == constantExp)
11415                               {
11416                                  int n = (int)strtol(nbExp1.constant, null, 0);
11417                                  if(n == (from == charType ? 255 : 65535))
11418                                     skipWarning = true;
11419                               }
11420                            }
11421                            break;
11422                         case '|':
11423                         {
11424                            TypeKind kind1, kind2;
11425                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11426                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11427                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11428                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11429                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) &&
11430                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11431                               skipWarning = true;
11432                            break;
11433                         }
11434                         case '&':
11435                         {
11436                            TypeKind kind1, kind2;
11437                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11438                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11439                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11440                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11441                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) ||
11442                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11443                               skipWarning = true;
11444                            break;
11445                         }
11446                      }
11447                   }
11448
11449                   if(!skipWarning)
11450                   {
11451                      char expString[10240];
11452                      expString[0] = '\0';
11453                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11454
11455 #ifdef _DEBUG
11456                      CheckExpressionType(exp, exp.destType, false, true);
11457 #endif
11458
11459                      // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11460                      if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11461                                         !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11462                                         !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11463                                         !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11464                      {
11465                         if(invalidCast)
11466                            Compiler_Error($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11467                         else
11468                            Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11469                      }
11470                   }
11471
11472                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11473                   if(!inCompiler)
11474                   {
11475                      FreeType(exp.expType);
11476                      exp.destType.refCount++;
11477                      exp.expType = exp.destType;
11478                   }
11479                }
11480             }
11481          }
11482       }
11483       // Cast function pointers to void * as eC already checked compatibility
11484       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11485               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11486       {
11487          Expression nbExp = GetNonBracketsExp(exp);
11488          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11489          {
11490             Expression e = MoveExpContents(exp);
11491             exp.cast.exp = MkExpBrackets(MkListOne(e));
11492             exp.type = castExp;
11493             exp.cast.exp.destType = exp.destType;
11494             if(exp.destType) exp.destType.refCount++;
11495             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11496          }
11497       }
11498    }
11499    else if(unresolved)
11500    {
11501       if(exp.identifier._class && exp.identifier._class.name)
11502          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11503       else if(exp.identifier.string && exp.identifier.string[0])
11504          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11505    }
11506    else if(!exp.expType && exp.type != dummyExp)
11507    {
11508       char expString[10240];
11509       expString[0] = '\0';
11510       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11511       Compiler_Error($"couldn't determine type of %s\n", expString);
11512    }
11513
11514    // Let's try to support any_object & typed_object here:
11515    if(inCompiler)
11516       ApplyAnyObjectLogic(exp);
11517
11518    // Mark nohead classes as by reference, unless we're casting them to an integral type
11519    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11520       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11521          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11522           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11523    {
11524       exp.byReference = true;
11525    }
11526    yylloc = oldyylloc;
11527 }
11528
11529 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11530 {
11531    // THIS CODE WILL FIND NEXT MEMBER...
11532    if(*curMember)
11533    {
11534       *curMember = (*curMember).next;
11535
11536       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11537       {
11538          *curMember = subMemberStack[--(*subMemberStackPos)];
11539          *curMember = (*curMember).next;
11540       }
11541
11542       // SKIP ALL PROPERTIES HERE...
11543       while((*curMember) && (*curMember).isProperty)
11544          *curMember = (*curMember).next;
11545
11546       if(subMemberStackPos)
11547       {
11548          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11549          {
11550             subMemberStack[(*subMemberStackPos)++] = *curMember;
11551
11552             *curMember = (*curMember).members.first;
11553             while(*curMember && (*curMember).isProperty)
11554                *curMember = (*curMember).next;
11555          }
11556       }
11557    }
11558    while(!*curMember)
11559    {
11560       if(!*curMember)
11561       {
11562          if(subMemberStackPos && *subMemberStackPos)
11563          {
11564             *curMember = subMemberStack[--(*subMemberStackPos)];
11565             *curMember = (*curMember).next;
11566          }
11567          else
11568          {
11569             Class lastCurClass = *curClass;
11570
11571             if(*curClass == _class) break;     // REACHED THE END
11572
11573             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11574             *curMember = (*curClass).membersAndProperties.first;
11575          }
11576
11577          while((*curMember) && (*curMember).isProperty)
11578             *curMember = (*curMember).next;
11579          if(subMemberStackPos)
11580          {
11581             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11582             {
11583                subMemberStack[(*subMemberStackPos)++] = *curMember;
11584
11585                *curMember = (*curMember).members.first;
11586                while(*curMember && (*curMember).isProperty)
11587                   *curMember = (*curMember).next;
11588             }
11589          }
11590       }
11591    }
11592 }
11593
11594
11595 static void ProcessInitializer(Initializer init, Type type)
11596 {
11597    switch(init.type)
11598    {
11599       case expInitializer:
11600          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11601          {
11602             // TESTING THIS FOR SHUTTING = 0 WARNING
11603             if(init.exp && !init.exp.destType)
11604             {
11605                FreeType(init.exp.destType);
11606                init.exp.destType = type;
11607                if(type) type.refCount++;
11608             }
11609             if(init.exp)
11610             {
11611                ProcessExpressionType(init.exp);
11612                init.isConstant = init.exp.isConstant;
11613             }
11614             break;
11615          }
11616          else
11617          {
11618             Expression exp = init.exp;
11619             Instantiation inst = exp.instance;
11620             MembersInit members;
11621
11622             init.type = listInitializer;
11623             init.list = MkList();
11624
11625             if(inst.members)
11626             {
11627                for(members = inst.members->first; members; members = members.next)
11628                {
11629                   if(members.type == dataMembersInit)
11630                   {
11631                      MemberInit member;
11632                      for(member = members.dataMembers->first; member; member = member.next)
11633                      {
11634                         ListAdd(init.list, member.initializer);
11635                         member.initializer = null;
11636                      }
11637                   }
11638                   // Discard all MembersInitMethod
11639                }
11640             }
11641             FreeExpression(exp);
11642          }
11643       case listInitializer:
11644       {
11645          Initializer i;
11646          Type initializerType = null;
11647          Class curClass = null;
11648          DataMember curMember = null;
11649          DataMember subMemberStack[256];
11650          int subMemberStackPos = 0;
11651
11652          if(type && type.kind == arrayType)
11653             initializerType = Dereference(type);
11654          else if(type && (type.kind == structType || type.kind == unionType))
11655             initializerType = type.members.first;
11656
11657          for(i = init.list->first; i; i = i.next)
11658          {
11659             if(type && type.kind == classType && type._class && type._class.registered)
11660             {
11661                // 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)
11662                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11663                // TODO: Generate error on initializing a private data member this way from another module...
11664                if(curMember)
11665                {
11666                   if(!curMember.dataType)
11667                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11668                   initializerType = curMember.dataType;
11669                }
11670             }
11671             ProcessInitializer(i, initializerType);
11672             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11673                initializerType = initializerType.next;
11674             if(!i.isConstant)
11675                init.isConstant = false;
11676          }
11677
11678          if(type && type.kind == arrayType)
11679             FreeType(initializerType);
11680
11681          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11682          {
11683             Compiler_Error($"Assigning list initializer to non list\n");
11684          }
11685          break;
11686       }
11687    }
11688 }
11689
11690 static void ProcessSpecifier(Specifier spec, bool declareStruct, bool warnClasses)
11691 {
11692    switch(spec.type)
11693    {
11694       case baseSpecifier:
11695       {
11696          if(spec.specifier == THISCLASS)
11697          {
11698             if(thisClass)
11699             {
11700                spec.type = nameSpecifier;
11701                spec.name = ReplaceThisClass(thisClass);
11702                spec.symbol = FindClass(spec.name);
11703                ProcessSpecifier(spec, declareStruct, false);
11704             }
11705          }
11706          break;
11707       }
11708       case nameSpecifier:
11709       {
11710          Symbol symbol = FindType(curContext, spec.name);
11711          if(symbol)
11712             DeclareType(curExternal, symbol.type, true, true);
11713          else if(spec.symbol /*&& declareStruct*/)
11714          {
11715             Class c = spec.symbol.registered;
11716             if(warnClasses && !c)
11717                Compiler_Warning("Undeclared class %s\n", spec.name);
11718             DeclareStruct(curExternal, spec.name, c && c.type == noHeadClass, declareStruct && c && c.type == structClass);
11719          }
11720          break;
11721       }
11722       case enumSpecifier:
11723       {
11724          Enumerator e;
11725          if(spec.list)
11726          {
11727             for(e = spec.list->first; e; e = e.next)
11728             {
11729                if(e.exp)
11730                   ProcessExpressionType(e.exp);
11731             }
11732          }
11733          // Fall through for IDE type processing
11734          if(inCompiler)
11735             break;
11736       }
11737       case structSpecifier:
11738       case unionSpecifier:
11739       {
11740          if(spec.definitions)
11741          {
11742             //ClassDef def;
11743             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11744             //if(symbol)
11745                ProcessClass(spec.definitions, symbol);
11746             /*else
11747             {
11748                for(def = spec.definitions->first; def; def = def.next)
11749                {
11750                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11751                      ProcessDeclaration(def.decl);
11752                }
11753             }*/
11754          }
11755          break;
11756       }
11757       /*
11758       case classSpecifier:
11759       {
11760          Symbol classSym = FindClass(spec.name);
11761          if(classSym && classSym.registered && classSym.registered.type == structClass)
11762             DeclareStruct(spec.name, false, true);
11763          break;
11764       }
11765       */
11766    }
11767 }
11768
11769
11770 static void ProcessDeclarator(Declarator decl, bool isFunction)
11771 {
11772    switch(decl.type)
11773    {
11774       case identifierDeclarator:
11775          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11776          {
11777             FreeSpecifier(decl.identifier._class);
11778             decl.identifier._class = null;
11779          }
11780          break;
11781       case arrayDeclarator:
11782          if(decl.array.exp)
11783             ProcessExpressionType(decl.array.exp);
11784       case structDeclarator:
11785       case bracketsDeclarator:
11786       case functionDeclarator:
11787       case pointerDeclarator:
11788       case extendedDeclarator:
11789       case extendedDeclaratorEnd:
11790       {
11791          Identifier id = null;
11792          Specifier classSpec = null;
11793          if(decl.type == functionDeclarator)
11794          {
11795             id = GetDeclId(decl);
11796             if(id && id._class)
11797             {
11798                classSpec = id._class;
11799                id._class = null;
11800             }
11801          }
11802          if(decl.declarator)
11803             ProcessDeclarator(decl.declarator, isFunction);
11804          if(decl.type == functionDeclarator)
11805          {
11806             if(classSpec)
11807             {
11808                TypeName param
11809                {
11810                   qualifiers = MkListOne(classSpec);
11811                   declarator = null;
11812                };
11813                if(!decl.function.parameters)
11814                   decl.function.parameters = MkList();
11815                decl.function.parameters->Insert(null, param);
11816             }
11817             if(decl.function.parameters)
11818             {
11819                TypeName param;
11820
11821                for(param = decl.function.parameters->first; param; param = param.next)
11822                {
11823                   if(param.qualifiers)
11824                   {
11825                      Specifier spec;
11826                      for(spec = param.qualifiers->first; spec; spec = spec.next)
11827                      {
11828                         if(spec.type == baseSpecifier)
11829                         {
11830                            if(spec.specifier == TYPED_OBJECT)
11831                            {
11832                               Declarator d = param.declarator;
11833                               TypeName newParam
11834                               {
11835                                  qualifiers = MkListOne(MkSpecifier(VOID));
11836                                  declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11837                               };
11838                               if(!d || d.type != pointerDeclarator)
11839                                  newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11840
11841                               FreeList(param.qualifiers, FreeSpecifier);
11842
11843                               param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11844                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11845
11846                               DeclareStruct(curExternal, "ecere::com::Class", false, true);
11847
11848                               decl.function.parameters->Insert(param, newParam);
11849                               param = newParam;
11850                               break;
11851                            }
11852                            else if(spec.specifier == ANY_OBJECT)
11853                            {
11854                               Declarator d = param.declarator;
11855
11856                               FreeList(param.qualifiers, FreeSpecifier);
11857
11858                               param.qualifiers = MkListOne(MkSpecifier(VOID));
11859                               if(!d || d.type != pointerDeclarator)
11860                                  param.qualifiers->Insert(null, MkSpecifier(CONST));
11861                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11862                               break;
11863                            }
11864                            else if(spec.specifier == THISCLASS)
11865                            {
11866                               if(thisClass)
11867                               {
11868                                  spec.type = nameSpecifier;
11869                                  spec.name = ReplaceThisClass(thisClass);
11870                                  spec.symbol = FindClass(spec.name);
11871                                  ProcessSpecifier(spec, false, false);
11872                               }
11873                               break;
11874                            }
11875                         }
11876                         else if(spec.type == nameSpecifier)
11877                         {
11878                            ProcessSpecifier(spec, isFunction, true);
11879                         }
11880                         else if((spec.type == structSpecifier || spec.type == unionSpecifier) && !spec.definitions && spec.id && spec.id.string)
11881                         {
11882                            Declarator d = param.declarator;
11883                            if(!d || d.type != pointerDeclarator)
11884                               DeclareStruct(curExternal, spec.id.string, false, true);
11885                         }
11886                      }
11887                   }
11888
11889                   if(param.declarator)
11890                      ProcessDeclarator(param.declarator, false);
11891                }
11892             }
11893          }
11894          break;
11895       }
11896    }
11897 }
11898
11899 static void ProcessDeclaration(Declaration decl, bool warnClasses)
11900 {
11901    yylloc = decl.loc;
11902    switch(decl.type)
11903    {
11904       case initDeclaration:
11905       {
11906          bool declareStruct = false;
11907          /*
11908          lineNum = decl.pos.line;
11909          column = decl.pos.col;
11910          */
11911
11912          if(decl.declarators)
11913          {
11914             InitDeclarator d;
11915
11916             for(d = decl.declarators->first; d; d = d.next)
11917             {
11918                Type type, subType;
11919                ProcessDeclarator(d.declarator, false);
11920
11921                type = ProcessType(decl.specifiers, d.declarator);
11922
11923                if(d.initializer)
11924                {
11925                   ProcessInitializer(d.initializer, type);
11926
11927                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11928
11929                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11930                      d.initializer.exp.type == instanceExp)
11931                   {
11932                      if(type.kind == classType && type._class ==
11933                         d.initializer.exp.expType._class)
11934                      {
11935                         Instantiation inst = d.initializer.exp.instance;
11936                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11937
11938                         d.initializer.exp.instance = null;
11939                         if(decl.specifiers)
11940                            FreeList(decl.specifiers, FreeSpecifier);
11941                         FreeList(decl.declarators, FreeInitDeclarator);
11942
11943                         d = null;
11944
11945                         decl.type = instDeclaration;
11946                         decl.inst = inst;
11947                      }
11948                   }
11949                }
11950                for(subType = type; subType;)
11951                {
11952                   if(subType.kind == classType)
11953                   {
11954                      declareStruct = true;
11955                      break;
11956                   }
11957                   else if(subType.kind == pointerType)
11958                      break;
11959                   else if(subType.kind == arrayType)
11960                      subType = subType.arrayType;
11961                   else
11962                      break;
11963                }
11964
11965                FreeType(type);
11966                if(!d) break;
11967             }
11968          }
11969
11970          if(decl.specifiers)
11971          {
11972             Specifier s;
11973             for(s = decl.specifiers->first; s; s = s.next)
11974             {
11975                ProcessSpecifier(s, declareStruct, true);
11976             }
11977          }
11978          break;
11979       }
11980       case instDeclaration:
11981       {
11982          ProcessInstantiationType(decl.inst);
11983          break;
11984       }
11985       case structDeclaration:
11986       {
11987          Specifier spec;
11988          Declarator d;
11989          bool declareStruct = false;
11990
11991          if(decl.declarators)
11992          {
11993             for(d = decl.declarators->first; d; d = d.next)
11994             {
11995                Type type = ProcessType(decl.specifiers, d.declarator);
11996                Type subType;
11997                ProcessDeclarator(d, false);
11998                for(subType = type; subType;)
11999                {
12000                   if(subType.kind == classType)
12001                   {
12002                      declareStruct = true;
12003                      break;
12004                   }
12005                   else if(subType.kind == pointerType)
12006                      break;
12007                   else if(subType.kind == arrayType)
12008                      subType = subType.arrayType;
12009                   else
12010                      break;
12011                }
12012                FreeType(type);
12013             }
12014          }
12015          if(decl.specifiers)
12016          {
12017             for(spec = decl.specifiers->first; spec; spec = spec.next)
12018                ProcessSpecifier(spec, declareStruct, warnClasses);
12019          }
12020          break;
12021       }
12022    }
12023 }
12024
12025 static FunctionDefinition curFunction;
12026
12027 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
12028 {
12029    char propName[1024], propNameM[1024];
12030    char getName[1024], setName[1024];
12031    OldList * args;
12032
12033    DeclareProperty(curExternal, prop, setName, getName);
12034
12035    // eInstance_FireWatchers(object, prop);
12036    strcpy(propName, "__ecereProp_");
12037    FullClassNameCat(propName, prop._class.fullName, false);
12038    strcat(propName, "_");
12039    FullClassNameCat(propName, prop.name, true);
12040
12041    strcpy(propNameM, "__ecerePropM_");
12042    FullClassNameCat(propNameM, prop._class.fullName, false);
12043    strcat(propNameM, "_");
12044    FullClassNameCat(propNameM, prop.name, true);
12045
12046    if(prop.isWatchable)
12047    {
12048       args = MkList();
12049       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
12050       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12051       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
12052
12053       args = MkList();
12054       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
12055       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
12056       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
12057
12058       DeclareFunctionUtil(curExternal, "eInstance_FireWatchers");
12059    }
12060
12061    {
12062       args = MkList();
12063       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
12064       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12065       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
12066
12067       args = MkList();
12068       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
12069       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
12070       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
12071
12072       DeclareFunctionUtil(curExternal, "eInstance_FireSelfWatchers");
12073    }
12074
12075    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
12076       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12077       curFunction.propSet.fireWatchersDone = true;
12078 }
12079
12080 static void ProcessStatement(Statement stmt)
12081 {
12082    yylloc = stmt.loc;
12083    /*
12084    lineNum = stmt.pos.line;
12085    column = stmt.pos.col;
12086    */
12087    switch(stmt.type)
12088    {
12089       case labeledStmt:
12090          ProcessStatement(stmt.labeled.stmt);
12091          break;
12092       case caseStmt:
12093          // This expression should be constant...
12094          if(stmt.caseStmt.exp)
12095          {
12096             FreeType(stmt.caseStmt.exp.destType);
12097             stmt.caseStmt.exp.destType = curSwitchType;
12098             if(curSwitchType) curSwitchType.refCount++;
12099             ProcessExpressionType(stmt.caseStmt.exp);
12100             ComputeExpression(stmt.caseStmt.exp);
12101          }
12102          if(stmt.caseStmt.stmt)
12103             ProcessStatement(stmt.caseStmt.stmt);
12104          break;
12105       case compoundStmt:
12106       {
12107          if(stmt.compound.context)
12108          {
12109             Declaration decl;
12110             Statement s;
12111
12112             Statement prevCompound = curCompound;
12113             Context prevContext = curContext;
12114
12115             if(!stmt.compound.isSwitch)
12116                curCompound = stmt;
12117             curContext = stmt.compound.context;
12118
12119             if(stmt.compound.declarations)
12120             {
12121                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
12122                   ProcessDeclaration(decl, true);
12123             }
12124             if(stmt.compound.statements)
12125             {
12126                for(s = stmt.compound.statements->first; s; s = s.next)
12127                   ProcessStatement(s);
12128             }
12129
12130             curContext = prevContext;
12131             curCompound = prevCompound;
12132          }
12133          break;
12134       }
12135       case expressionStmt:
12136       {
12137          Expression exp;
12138          if(stmt.expressions)
12139          {
12140             for(exp = stmt.expressions->first; exp; exp = exp.next)
12141                ProcessExpressionType(exp);
12142          }
12143          break;
12144       }
12145       case ifStmt:
12146       {
12147          Expression exp;
12148
12149          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
12150          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
12151          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
12152          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
12153          {
12154             ProcessExpressionType(exp);
12155          }
12156          if(stmt.ifStmt.stmt)
12157             ProcessStatement(stmt.ifStmt.stmt);
12158          if(stmt.ifStmt.elseStmt)
12159             ProcessStatement(stmt.ifStmt.elseStmt);
12160          break;
12161       }
12162       case switchStmt:
12163       {
12164          Type oldSwitchType = curSwitchType;
12165          if(stmt.switchStmt.exp)
12166          {
12167             Expression exp;
12168             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
12169             {
12170                if(!exp.next)
12171                {
12172                   /*
12173                   Type destType
12174                   {
12175                      kind = intType;
12176                      refCount = 1;
12177                   };
12178                   e.exp.destType = destType;
12179                   */
12180
12181                   ProcessExpressionType(exp);
12182                }
12183                if(!exp.next)
12184                   curSwitchType = exp.expType;
12185             }
12186          }
12187          ProcessStatement(stmt.switchStmt.stmt);
12188          curSwitchType = oldSwitchType;
12189          break;
12190       }
12191       case whileStmt:
12192       {
12193          if(stmt.whileStmt.exp)
12194          {
12195             Expression exp;
12196
12197             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
12198             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
12199             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
12200             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
12201             {
12202                ProcessExpressionType(exp);
12203             }
12204          }
12205          if(stmt.whileStmt.stmt)
12206             ProcessStatement(stmt.whileStmt.stmt);
12207          break;
12208       }
12209       case doWhileStmt:
12210       {
12211          if(stmt.doWhile.exp)
12212          {
12213             Expression exp;
12214
12215             if(stmt.doWhile.exp->last)
12216             {
12217                FreeType(((Expression)stmt.doWhile.exp->last).destType);
12218                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
12219                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
12220             }
12221             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
12222             {
12223                ProcessExpressionType(exp);
12224             }
12225          }
12226          if(stmt.doWhile.stmt)
12227             ProcessStatement(stmt.doWhile.stmt);
12228          break;
12229       }
12230       case forStmt:
12231       {
12232          Expression exp;
12233          if(stmt.forStmt.init)
12234             ProcessStatement(stmt.forStmt.init);
12235
12236          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
12237          {
12238             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
12239             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
12240             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
12241          }
12242
12243          if(stmt.forStmt.check)
12244             ProcessStatement(stmt.forStmt.check);
12245          if(stmt.forStmt.increment)
12246          {
12247             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
12248                ProcessExpressionType(exp);
12249          }
12250
12251          if(stmt.forStmt.stmt)
12252             ProcessStatement(stmt.forStmt.stmt);
12253          break;
12254       }
12255       case forEachStmt:
12256       {
12257          Identifier id = stmt.forEachStmt.id;
12258          OldList * exp = stmt.forEachStmt.exp;
12259          OldList * filter = stmt.forEachStmt.filter;
12260          Statement block = stmt.forEachStmt.stmt;
12261          char iteratorType[1024];
12262          Type source;
12263          Expression e;
12264          bool isBuiltin = exp && exp->last &&
12265             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12266               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12267          Expression arrayExp;
12268          const char * typeString = null;
12269          int builtinCount = 0;
12270
12271          for(e = exp ? exp->first : null; e; e = e.next)
12272          {
12273             if(!e.next)
12274             {
12275                FreeType(e.destType);
12276                e.destType = ProcessTypeString("Container", false);
12277             }
12278             if(!isBuiltin || e.next)
12279                ProcessExpressionType(e);
12280          }
12281
12282          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12283          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12284             eClass_IsDerived(source._class.registered, containerClass)))
12285          {
12286             Class _class = source ? source._class.registered : null;
12287             Symbol symbol;
12288             Expression expIt = null;
12289             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12290             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12291             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12292             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12293
12294             if(inCompiler)
12295             {
12296                stmt.type = compoundStmt;
12297
12298                stmt.compound.context = Context { };
12299                stmt.compound.context.parent = curContext;
12300                curContext = stmt.compound.context;
12301             }
12302
12303             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12304             {
12305                Class mapClass = eSystem_FindClass(privateModule, "Map");
12306                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12307                isCustomAVLTree = true;
12308                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12309                   isAVLTree = true;
12310                else */if(eClass_IsDerived(source._class.registered, mapClass))
12311                   isMap = true;
12312             }
12313             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12314             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12315             {
12316                Class listClass = eSystem_FindClass(privateModule, "List");
12317                isLinkList = true;
12318                isList = eClass_IsDerived(source._class.registered, listClass);
12319             }
12320
12321             if(inCompiler && isArray)
12322             {
12323                Declarator decl;
12324                OldList * specs = MkList();
12325                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12326                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12327                stmt.compound.declarations = MkListOne(
12328                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12329                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12330                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12331                      MkInitializerAssignment(MkExpBrackets(exp))))));
12332             }
12333             else if(isBuiltin)
12334             {
12335                Type type = null;
12336                char typeStringBuf[1024];
12337
12338                // TODO: Merge this code?
12339                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12340                if(((Expression)exp->last).type == castExp)
12341                {
12342                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12343                   if(typeName)
12344                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12345                }
12346
12347                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12348                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12349                   arrayExp.destType._class.registered.templateArgs)
12350                {
12351                   Class templateClass = arrayExp.destType._class.registered;
12352                   typeString = templateClass.templateArgs[2].dataTypeString;
12353                }
12354                else if(arrayExp.list)
12355                {
12356                   // Guess type from expressions in the array
12357                   Expression e;
12358                   for(e = arrayExp.list->first; e; e = e.next)
12359                   {
12360                      ProcessExpressionType(e);
12361                      if(e.expType)
12362                      {
12363                         if(!type) { type = e.expType; type.refCount++; }
12364                         else
12365                         {
12366                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12367                            if(!MatchTypeExpression(e, type, null, false, true))
12368                            {
12369                               FreeType(type);
12370                               type = e.expType;
12371                               e.expType = null;
12372
12373                               e = arrayExp.list->first;
12374                               ProcessExpressionType(e);
12375                               if(e.expType)
12376                               {
12377                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12378                                  if(!MatchTypeExpression(e, type, null, false, true))
12379                                  {
12380                                     FreeType(e.expType);
12381                                     e.expType = null;
12382                                     FreeType(type);
12383                                     type = null;
12384                                     break;
12385                                  }
12386                               }
12387                            }
12388                         }
12389                         if(e.expType)
12390                         {
12391                            FreeType(e.expType);
12392                            e.expType = null;
12393                         }
12394                      }
12395                   }
12396                   if(type)
12397                   {
12398                      typeStringBuf[0] = '\0';
12399                      PrintType(type, typeStringBuf, false, true);
12400                      typeString = typeStringBuf;
12401                      FreeType(type);
12402                   }
12403                }
12404                if(typeString)
12405                {
12406                   if(inCompiler)
12407                   {
12408                      OldList * initializers = MkList();
12409                      Declarator decl;
12410                      OldList * specs = MkList();
12411                      if(arrayExp.list)
12412                      {
12413                         Expression e;
12414
12415                         builtinCount = arrayExp.list->count;
12416                         type = ProcessTypeString(typeString, false);
12417                         while((e = arrayExp.list->first))
12418                         {
12419                            arrayExp.list->Remove(e);
12420                            e.destType = type;
12421                            type.refCount++;
12422                            ProcessExpressionType(e);
12423                            if(inCompiler)
12424                               ListAdd(initializers, MkInitializerAssignment(e));
12425                         }
12426                         FreeType(type);
12427                         delete arrayExp.list;
12428                      }
12429                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12430
12431                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12432                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12433
12434                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12435                         PlugDeclarator(
12436                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12437                            ), MkInitializerList(initializers)))));
12438                      FreeList(exp, FreeExpression);
12439                   }
12440                   else if(arrayExp.list)
12441                   {
12442                      Expression e;
12443                      type = ProcessTypeString(typeString, false);
12444                      for(e = arrayExp.list->first; e; e = e.next)
12445                      {
12446                         e.destType = type;
12447                         type.refCount++;
12448                         ProcessExpressionType(e);
12449                      }
12450                      FreeType(type);
12451                   }
12452                }
12453                else
12454                {
12455                   arrayExp.expType = ProcessTypeString("Container", false);
12456                   Compiler_Error($"Couldn't determine type of array elements\n");
12457                }
12458
12459                /*
12460                Declarator decl;
12461                OldList * specs = MkList();
12462
12463                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12464                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12465                stmt.compound.declarations = MkListOne(
12466                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12467                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12468                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12469                      MkInitializerAssignment(MkExpBrackets(exp))))));
12470                */
12471             }
12472             else if(inCompiler && isLinkList && !isList)
12473             {
12474                Declarator decl;
12475                OldList * specs = MkList();
12476                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12477                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12478                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12479                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12480                      MkInitializerAssignment(MkExpBrackets(exp))))));
12481             }
12482             /*else if(isCustomAVLTree)
12483             {
12484                Declarator decl;
12485                OldList * specs = MkList();
12486                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12487                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12488                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12489                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12490                      MkInitializerAssignment(MkExpBrackets(exp))))));
12491             }*/
12492             else if(inCompiler && _class.templateArgs)
12493             {
12494                if(isMap)
12495                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12496                else
12497                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12498
12499                stmt.compound.declarations = MkListOne(
12500                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12501                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12502                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12503             }
12504             if(inCompiler)
12505             {
12506                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12507
12508                if(block)
12509                {
12510                   // Reparent sub-contexts in this statement
12511                   switch(block.type)
12512                   {
12513                      case compoundStmt:
12514                         if(block.compound.context)
12515                            block.compound.context.parent = stmt.compound.context;
12516                         break;
12517                      case ifStmt:
12518                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12519                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12520                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12521                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12522                         break;
12523                      case switchStmt:
12524                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12525                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12526                         break;
12527                      case whileStmt:
12528                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12529                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12530                         break;
12531                      case doWhileStmt:
12532                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12533                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12534                         break;
12535                      case forStmt:
12536                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12537                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12538                         break;
12539                      case forEachStmt:
12540                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12541                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12542                         break;
12543                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12544                      case labeledStmt:
12545                      case caseStmt
12546                      case expressionStmt:
12547                      case gotoStmt:
12548                      case continueStmt:
12549                      case breakStmt
12550                      case returnStmt:
12551                      case asmStmt:
12552                      case badDeclarationStmt:
12553                      case fireWatchersStmt:
12554                      case stopWatchingStmt:
12555                      case watchStmt:
12556                      */
12557                   }
12558                }
12559
12560                if(filter)
12561                {
12562                   block = MkIfStmt(filter, block, null);
12563                }
12564                if(isArray)
12565                {
12566                   stmt.compound.statements = MkListOne(MkForStmt(
12567                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12568                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12569                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12570                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12571                      block));
12572                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12573                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12574                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12575                }
12576                else if(isBuiltin)
12577                {
12578                   char count[128];
12579                   //OldList * specs = MkList();
12580                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12581
12582                   sprintf(count, "%d", builtinCount);
12583
12584                   stmt.compound.statements = MkListOne(MkForStmt(
12585                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12586                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12587                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12588                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12589                      block));
12590
12591                   /*
12592                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12593                   stmt.compound.statements = MkListOne(MkForStmt(
12594                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12595                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12596                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12597                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12598                      block));
12599                  */
12600                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12601                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12602                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12603                }
12604                else if(isLinkList && !isList)
12605                {
12606                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12607                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12608                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12609                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12610                   {
12611                      stmt.compound.statements = MkListOne(MkForStmt(
12612                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12613                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12614                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12615                         block));
12616                   }
12617                   else
12618                   {
12619                      OldList * specs = MkList();
12620                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12621                      stmt.compound.statements = MkListOne(MkForStmt(
12622                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12623                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12624                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12625                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12626                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12627                         block));
12628                   }
12629                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12630                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12631                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12632                }
12633                /*else if(isCustomAVLTree)
12634                {
12635                   stmt.compound.statements = MkListOne(MkForStmt(
12636                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12637                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12638                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12639                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12640                      block));
12641
12642                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12643                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12644                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12645                }*/
12646                else
12647                {
12648                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12649                      MkIdentifier("Next")), null)), block));
12650                }
12651                ProcessExpressionType(expIt);
12652                if(stmt.compound.declarations->first)
12653                   ProcessDeclaration(stmt.compound.declarations->first, true);
12654
12655                if(symbol)
12656                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12657
12658                ProcessStatement(stmt);
12659             }
12660             else
12661                ProcessStatement(stmt.forEachStmt.stmt);
12662             if(inCompiler)
12663                curContext = stmt.compound.context.parent;
12664             break;
12665          }
12666          else
12667          {
12668             Compiler_Error($"Expression is not a container\n");
12669          }
12670          break;
12671       }
12672       case gotoStmt:
12673          break;
12674       case continueStmt:
12675          break;
12676       case breakStmt:
12677          break;
12678       case returnStmt:
12679       {
12680          Expression exp;
12681          if(stmt.expressions)
12682          {
12683             for(exp = stmt.expressions->first; exp; exp = exp.next)
12684             {
12685                if(!exp.next)
12686                {
12687                   if(curFunction && !curFunction.type)
12688                      curFunction.type = ProcessType(
12689                         curFunction.specifiers, curFunction.declarator);
12690                   FreeType(exp.destType);
12691                   // TODO: current property if not compiling
12692                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12693                   if(exp.destType) exp.destType.refCount++;
12694                }
12695                ProcessExpressionType(exp);
12696             }
12697          }
12698          break;
12699       }
12700       case badDeclarationStmt:
12701       {
12702          ProcessDeclaration(stmt.decl, true);
12703          break;
12704       }
12705       case asmStmt:
12706       {
12707          AsmField field;
12708          if(stmt.asmStmt.inputFields)
12709          {
12710             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12711                if(field.expression)
12712                   ProcessExpressionType(field.expression);
12713          }
12714          if(stmt.asmStmt.outputFields)
12715          {
12716             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12717                if(field.expression)
12718                   ProcessExpressionType(field.expression);
12719          }
12720          if(stmt.asmStmt.clobberedFields)
12721          {
12722             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12723             {
12724                if(field.expression)
12725                   ProcessExpressionType(field.expression);
12726             }
12727          }
12728          break;
12729       }
12730       case watchStmt:
12731       {
12732          PropertyWatch propWatch;
12733          OldList * watches = stmt._watch.watches;
12734          Expression object = stmt._watch.object;
12735          Expression watcher = stmt._watch.watcher;
12736          if(watcher)
12737             ProcessExpressionType(watcher);
12738          if(object)
12739             ProcessExpressionType(object);
12740
12741          if(inCompiler)
12742          {
12743             if(watcher || thisClass)
12744             {
12745                External external = curExternal;
12746                Context context = curContext;
12747
12748                stmt.type = expressionStmt;
12749                stmt.expressions = MkList();
12750
12751                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12752                {
12753                   ClassFunction func;
12754                   char watcherName[1024];
12755                   Class watcherClass = watcher ?
12756                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12757                   External createdExternal;
12758
12759                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12760                   if(propWatch.deleteWatch)
12761                      strcat(watcherName, "_delete");
12762                   else
12763                   {
12764                      Identifier propID;
12765                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12766                      {
12767                         strcat(watcherName, "_");
12768                         strcat(watcherName, propID.string);
12769                      }
12770                   }
12771
12772                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12773                   {
12774                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12775                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12776                      ProcessClassFunctionBody(func, propWatch.compound);
12777                      propWatch.compound = null;
12778
12779                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12780
12781                      FreeClassFunction(func);
12782
12783                      curExternal = createdExternal;
12784                      ProcessFunction(createdExternal.function);
12785
12786                      if(propWatch.deleteWatch)
12787                      {
12788                         OldList * args = MkList();
12789                         ListAdd(args, CopyExpression(object));
12790                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12791                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12792                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12793                      }
12794                      else
12795                      {
12796                         Class _class = object.expType._class.registered;
12797                         Identifier propID;
12798
12799                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12800                         {
12801                            char propName[1024];
12802                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12803                            if(prop)
12804                            {
12805                               char getName[1024], setName[1024];
12806                               OldList * args = MkList();
12807
12808                               DeclareProperty(createdExternal, prop, setName, getName);
12809
12810                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12811                               strcpy(propName, "__ecereProp_");
12812                               FullClassNameCat(propName, prop._class.fullName, false);
12813                               strcat(propName, "_");
12814                               FullClassNameCat(propName, prop.name, true);
12815
12816                               ListAdd(args, CopyExpression(object));
12817                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12818                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12819                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12820
12821                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12822
12823                               external.CreateUniqueEdge(createdExternal, true);
12824                            }
12825                            else
12826                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12827                         }
12828                      }
12829                   }
12830                   else
12831                      Compiler_Error($"Invalid watched object\n");
12832                }
12833
12834                curExternal = external;
12835                curContext = context;
12836
12837                if(watcher)
12838                   FreeExpression(watcher);
12839                if(object)
12840                   FreeExpression(object);
12841                FreeList(watches, FreePropertyWatch);
12842             }
12843             else
12844                Compiler_Error($"No observer specified and not inside a class\n");
12845          }
12846          else
12847          {
12848             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12849             {
12850                ProcessStatement(propWatch.compound);
12851             }
12852
12853          }
12854          break;
12855       }
12856       case fireWatchersStmt:
12857       {
12858          OldList * watches = stmt._watch.watches;
12859          Expression object = stmt._watch.object;
12860          Class _class;
12861          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12862          // printf("%X\n", watches);
12863          // printf("%X\n", stmt._watch.watches);
12864          if(object)
12865             ProcessExpressionType(object);
12866
12867          if(inCompiler)
12868          {
12869             _class = object ?
12870                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12871
12872             if(_class)
12873             {
12874                Identifier propID;
12875
12876                stmt.type = expressionStmt;
12877                stmt.expressions = MkList();
12878
12879                // Check if we're inside a property set
12880                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12881                {
12882                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12883                }
12884                else if(!watches)
12885                {
12886                   //Compiler_Error($"No property specified and not inside a property set\n");
12887                }
12888                if(watches)
12889                {
12890                   for(propID = watches->first; propID; propID = propID.next)
12891                   {
12892                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12893                      if(prop)
12894                      {
12895                         CreateFireWatcher(prop, object, stmt);
12896                      }
12897                      else
12898                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12899                   }
12900                }
12901                else
12902                {
12903                   // Fire all properties!
12904                   Property prop;
12905                   Class base;
12906                   for(base = _class; base; base = base.base)
12907                   {
12908                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12909                      {
12910                         if(prop.isProperty && prop.isWatchable)
12911                         {
12912                            CreateFireWatcher(prop, object, stmt);
12913                         }
12914                      }
12915                   }
12916                }
12917
12918                if(object)
12919                   FreeExpression(object);
12920                FreeList(watches, FreeIdentifier);
12921             }
12922             else
12923                Compiler_Error($"Invalid object specified and not inside a class\n");
12924          }
12925          break;
12926       }
12927       case stopWatchingStmt:
12928       {
12929          OldList * watches = stmt._watch.watches;
12930          Expression object = stmt._watch.object;
12931          Expression watcher = stmt._watch.watcher;
12932          Class _class;
12933          if(object)
12934             ProcessExpressionType(object);
12935          if(watcher)
12936             ProcessExpressionType(watcher);
12937          if(inCompiler)
12938          {
12939             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12940
12941             if(watcher || thisClass)
12942             {
12943                if(_class)
12944                {
12945                   Identifier propID;
12946
12947                   stmt.type = expressionStmt;
12948                   stmt.expressions = MkList();
12949
12950                   if(!watches)
12951                   {
12952                      OldList * args;
12953                      // eInstance_StopWatching(object, null, watcher);
12954                      args = MkList();
12955                      ListAdd(args, CopyExpression(object));
12956                      ListAdd(args, MkExpConstant("0"));
12957                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12958                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12959                   }
12960                   else
12961                   {
12962                      for(propID = watches->first; propID; propID = propID.next)
12963                      {
12964                         char propName[1024];
12965                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12966                         if(prop)
12967                         {
12968                            char getName[1024], setName[1024];
12969                            OldList * args = MkList();
12970
12971                            DeclareProperty(curExternal, prop, setName, getName);
12972
12973                            // eInstance_StopWatching(object, prop, watcher);
12974                            strcpy(propName, "__ecereProp_");
12975                            FullClassNameCat(propName, prop._class.fullName, false);
12976                            strcat(propName, "_");
12977                            FullClassNameCat(propName, prop.name, true);
12978
12979                            ListAdd(args, CopyExpression(object));
12980                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12981                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12982                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12983                         }
12984                         else
12985                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12986                      }
12987                   }
12988
12989                   if(object)
12990                      FreeExpression(object);
12991                   if(watcher)
12992                      FreeExpression(watcher);
12993                   FreeList(watches, FreeIdentifier);
12994                }
12995                else
12996                   Compiler_Error($"Invalid object specified and not inside a class\n");
12997             }
12998             else
12999                Compiler_Error($"No observer specified and not inside a class\n");
13000          }
13001          break;
13002       }
13003    }
13004 }
13005
13006 static void ProcessFunction(FunctionDefinition function)
13007 {
13008    Identifier id = GetDeclId(function.declarator);
13009    Symbol symbol = function.declarator ? function.declarator.symbol : null;
13010    Type type = symbol ? symbol.type : null;
13011    Class oldThisClass = thisClass;
13012    Context oldTopContext = topContext;
13013
13014    yylloc = function.loc;
13015    // Process thisClass
13016
13017    if(type && type.thisClass)
13018    {
13019       Symbol classSym = type.thisClass;
13020       Class _class = type.thisClass.registered;
13021       char className[1024];
13022       char structName[1024];
13023       Declarator funcDecl;
13024       Symbol thisSymbol;
13025
13026       bool typedObject = false;
13027
13028       if(_class && !_class.base)
13029       {
13030          _class = currentClass;
13031          if(_class && !_class.symbol)
13032             _class.symbol = FindClass(_class.fullName);
13033          classSym = _class ? _class.symbol : null;
13034          typedObject = true;
13035       }
13036
13037       thisClass = _class;
13038
13039       if(inCompiler && _class)
13040       {
13041          if(type.kind == functionType)
13042          {
13043             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
13044             {
13045                //TypeName param = symbol.type.params.first;
13046                Type param = symbol.type.params.first;
13047                symbol.type.params.Remove(param);
13048                //FreeTypeName(param);
13049                FreeType(param);
13050             }
13051             if(type.classObjectType != classPointer)
13052             {
13053                symbol.type.params.Insert(null, MkClassType(_class.fullName));
13054                symbol.type.staticMethod = true;
13055                symbol.type.thisClass = null;
13056
13057                // HIGH DANGER: VERIFYING THIS...
13058                symbol.type.extraParam = false;
13059             }
13060          }
13061
13062          strcpy(className, "__ecereClass_");
13063          FullClassNameCat(className, _class.fullName, true);
13064
13065          structName[0] = 0;
13066          FullClassNameCat(structName, _class.fullName, false);
13067
13068          // [class] this
13069          funcDecl = GetFuncDecl(function.declarator);
13070          if(funcDecl)
13071          {
13072             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
13073             {
13074                TypeName param = funcDecl.function.parameters->first;
13075                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
13076                {
13077                   funcDecl.function.parameters->Remove(param);
13078                   FreeTypeName(param);
13079                }
13080             }
13081
13082             if(!function.propertyNoThis)
13083             {
13084                TypeName thisParam = null;
13085
13086                if(type.classObjectType != classPointer)
13087                {
13088                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
13089                   if(!funcDecl.function.parameters)
13090                      funcDecl.function.parameters = MkList();
13091                   funcDecl.function.parameters->Insert(null, thisParam);
13092                }
13093
13094                if(typedObject)
13095                {
13096                   if(type.classObjectType != classPointer)
13097                   {
13098                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
13099                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
13100                   }
13101
13102                   thisParam = TypeName
13103                   {
13104                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
13105                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
13106                   };
13107                   DeclareStruct(curExternal, "ecere::com::Class", false, true);
13108                   funcDecl.function.parameters->Insert(null, thisParam);
13109                }
13110             }
13111          }
13112
13113          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13114          {
13115             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13116             funcDecl = GetFuncDecl(initDecl.declarator);
13117             if(funcDecl)
13118             {
13119                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
13120                {
13121                   TypeName param = funcDecl.function.parameters->first;
13122                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
13123                   {
13124                      funcDecl.function.parameters->Remove(param);
13125                      FreeTypeName(param);
13126                   }
13127                }
13128
13129                if(type.classObjectType != classPointer)
13130                {
13131                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
13132                   {
13133                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
13134
13135                      if(!funcDecl.function.parameters)
13136                         funcDecl.function.parameters = MkList();
13137                      funcDecl.function.parameters->Insert(null, thisParam);
13138                   }
13139                }
13140             }
13141          }
13142       }
13143
13144       // Add this to the context
13145       if(function.body)
13146       {
13147          if(type.classObjectType != classPointer)
13148          {
13149             thisSymbol = Symbol
13150             {
13151                string = CopyString("this");
13152                type = classSym ? MkClassType(classSym.string) : null;
13153             };
13154             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
13155
13156             if(typedObject && thisSymbol.type)
13157             {
13158                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
13159                thisSymbol.type.byReference = type.byReference;
13160                thisSymbol.type.typedByReference = type.byReference;
13161             }
13162          }
13163       }
13164
13165       // Pointer to class data
13166       if(inCompiler && _class && _class.type == normalClass && type.classObjectType != classPointer)
13167       {
13168          DataMember member = null;
13169          {
13170             Class base;
13171             for(base = _class; base && base.type != systemClass; base = base.next)
13172             {
13173                for(member = base.membersAndProperties.first; member; member = member.next)
13174                   if(!member.isProperty)
13175                      break;
13176                if(member)
13177                   break;
13178             }
13179          }
13180          for(member = _class.membersAndProperties.first; member; member = member.next)
13181             if(!member.isProperty)
13182                break;
13183          if(member)
13184          {
13185             char pointerName[1024];
13186
13187             Declaration decl;
13188             Initializer initializer;
13189             Expression exp, bytePtr;
13190
13191             strcpy(pointerName, "__ecerePointer_");
13192             FullClassNameCat(pointerName, _class.fullName, false);
13193             {
13194                char className[1024];
13195                strcpy(className, "__ecereClass_");
13196                FullClassNameCat(className, classSym.string, true);
13197
13198                DeclareClass(curExternal, classSym, className);
13199             }
13200
13201             // ((byte *) this)
13202             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
13203
13204             if(_class.fixed)
13205             {
13206                Expression e;
13207                if(_class.offset && _class.offset == (_class.base.type == noHeadClass ? _class.base.memberOffset : _class.base.structSize))
13208                {
13209                   e = MkExpClassSize(MkSpecifierName(_class.base.fullName));
13210                   ProcessExpressionType(e);
13211                }
13212                else
13213                {
13214                   char string[256];
13215                   sprintf(string, "%d", _class.offset);  // Need Bootstrap Fix
13216                   e = MkExpConstant(string);
13217                }
13218                exp = QBrackets(MkExpOp(bytePtr, '+', e));
13219             }
13220             else
13221             {
13222                // ([bytePtr] + [className]->offset)
13223                exp = QBrackets(MkExpOp(bytePtr, '+',
13224                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
13225             }
13226
13227             // (this ? [exp] : 0)
13228             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
13229             exp.expType = Type
13230             {
13231                refCount = 1;
13232                kind = pointerType;
13233                type = Type { refCount = 1, kind = voidType };
13234             };
13235
13236             if(function.body)
13237             {
13238                yylloc = function.body.loc;
13239                // ([structName] *) [exp]
13240                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13241                initializer = MkInitializerAssignment(
13242                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13243
13244                // [structName] * [pointerName] = [initializer];
13245                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13246
13247                {
13248                   Context prevContext = curContext;
13249                   OldList * list;
13250                   curContext = function.body.compound.context;
13251
13252                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13253                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13254                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13255
13256                   curContext = prevContext;
13257                }
13258
13259                // WHY?
13260                decl.symbol = null;
13261
13262                if(!function.body.compound.declarations)
13263                   function.body.compound.declarations = MkList();
13264                function.body.compound.declarations->Insert(null, decl);
13265             }
13266          }
13267       }
13268
13269
13270       // Loop through the function and replace undeclared identifiers
13271       // which are a member of the class (methods, properties or data)
13272       // by "this.[member]"
13273    }
13274    else
13275       thisClass = null;
13276
13277    if(id)
13278    {
13279       FreeSpecifier(id._class);
13280       id._class = null;
13281
13282       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13283       {
13284          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13285          id = GetDeclId(initDecl.declarator);
13286
13287          FreeSpecifier(id._class);
13288          id._class = null;
13289       }
13290    }
13291    if(function.body)
13292       topContext = function.body.compound.context;
13293    {
13294       FunctionDefinition oldFunction = curFunction;
13295       curFunction = function;
13296       if(function.body)
13297          ProcessStatement(function.body);
13298
13299       // If this is a property set and no firewatchers has been done yet, add one here
13300       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13301       {
13302          Statement prevCompound = curCompound;
13303          Context prevContext = curContext;
13304
13305          Statement fireWatchers = MkFireWatchersStmt(null, null);
13306          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13307          ListAdd(function.body.compound.statements, fireWatchers);
13308
13309          curCompound = function.body;
13310          curContext = function.body.compound.context;
13311
13312          ProcessStatement(fireWatchers);
13313
13314          curContext = prevContext;
13315          curCompound = prevCompound;
13316
13317       }
13318
13319       curFunction = oldFunction;
13320    }
13321
13322    if(function.declarator)
13323    {
13324       ProcessDeclarator(function.declarator, true);
13325    }
13326
13327    topContext = oldTopContext;
13328    thisClass = oldThisClass;
13329 }
13330
13331 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13332 static void ProcessClass(OldList definitions, Symbol symbol)
13333 {
13334    ClassDef def;
13335    External external = curExternal;
13336    Class regClass = symbol ? symbol.registered : null;
13337
13338    // Process all functions
13339    for(def = definitions.first; def; def = def.next)
13340    {
13341       if(def.type == functionClassDef)
13342       {
13343          if(def.function.declarator)
13344             curExternal = def.function.declarator.symbol.pointerExternal;
13345          else
13346             curExternal = external;
13347
13348          ProcessFunction((FunctionDefinition)def.function);
13349       }
13350       else if(def.type == declarationClassDef)
13351       {
13352          if(def.decl.type == instDeclaration)
13353          {
13354             thisClass = regClass;
13355             ProcessInstantiationType(def.decl.inst);
13356             thisClass = null;
13357          }
13358          // Testing this
13359          else
13360          {
13361             Class backThisClass = thisClass;
13362             if(regClass) thisClass = regClass;
13363             ProcessDeclaration(def.decl, symbol ? true : false);
13364             thisClass = backThisClass;
13365          }
13366       }
13367       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13368       {
13369          MemberInit defProperty;
13370
13371          // Add this to the context
13372          Symbol thisSymbol = Symbol
13373          {
13374             string = CopyString("this");
13375             type = regClass ? MkClassType(regClass.fullName) : null;
13376          };
13377          globalContext.symbols.Add((BTNode)thisSymbol);
13378
13379          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13380          {
13381             thisClass = regClass;
13382             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13383             thisClass = null;
13384          }
13385
13386          globalContext.symbols.Remove((BTNode)thisSymbol);
13387          FreeSymbol(thisSymbol);
13388       }
13389       else if(def.type == propertyClassDef && def.propertyDef)
13390       {
13391          PropertyDef prop = def.propertyDef;
13392
13393          // Add this to the context
13394          thisClass = regClass;
13395          if(prop.setStmt)
13396          {
13397             if(regClass)
13398             {
13399                Symbol thisSymbol
13400                {
13401                   string = CopyString("this");
13402                   type = MkClassType(regClass.fullName);
13403                };
13404                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13405             }
13406
13407             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13408             ProcessStatement(prop.setStmt);
13409          }
13410          if(prop.getStmt)
13411          {
13412             if(regClass)
13413             {
13414                Symbol thisSymbol
13415                {
13416                   string = CopyString("this");
13417                   type = MkClassType(regClass.fullName);
13418                };
13419                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13420             }
13421
13422             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13423             ProcessStatement(prop.getStmt);
13424          }
13425          if(prop.issetStmt)
13426          {
13427             if(regClass)
13428             {
13429                Symbol thisSymbol
13430                {
13431                   string = CopyString("this");
13432                   type = MkClassType(regClass.fullName);
13433                };
13434                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13435             }
13436
13437             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13438             ProcessStatement(prop.issetStmt);
13439          }
13440
13441          thisClass = null;
13442       }
13443       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13444       {
13445          PropertyWatch propertyWatch = def.propertyWatch;
13446
13447          thisClass = regClass;
13448          if(propertyWatch.compound)
13449          {
13450             Symbol thisSymbol
13451             {
13452                string = CopyString("this");
13453                type = regClass ? MkClassType(regClass.fullName) : null;
13454             };
13455
13456             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13457
13458             curExternal = null;
13459             ProcessStatement(propertyWatch.compound);
13460          }
13461          thisClass = null;
13462       }
13463    }
13464 }
13465
13466 void DeclareFunctionUtil(External neededBy, const String s)
13467 {
13468    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13469    if(function)
13470    {
13471       char name[1024];
13472       name[0] = 0;
13473       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13474          strcpy(name, "__ecereFunction_");
13475       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13476       DeclareFunction(neededBy, function, name);
13477    }
13478    else if(neededBy)
13479       FindSymbol(s, globalContext, globalContext, false, false);
13480 }
13481
13482 bool reachedPass15;
13483
13484 void ComputeDataTypes()
13485 {
13486    External external;
13487
13488    currentClass = null;
13489
13490    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13491
13492    DeclareStruct(null, "ecere::com::Class", false, true);
13493    DeclareStruct(null, "ecere::com::Instance", false, true);
13494    DeclareStruct(null, "ecere::com::Property", false, true);
13495    DeclareStruct(null, "ecere::com::DataMember", false, true);
13496    DeclareStruct(null, "ecere::com::Method", false, true);
13497    DeclareStruct(null, "ecere::com::SerialBuffer", false, true);
13498    DeclareStruct(null, "ecere::com::ClassTemplateArgument", false, true);
13499
13500    DeclareFunctionUtil(null, "eSystem_New");
13501    DeclareFunctionUtil(null, "eSystem_New0");
13502    DeclareFunctionUtil(null, "eSystem_Renew");
13503    DeclareFunctionUtil(null, "eSystem_Renew0");
13504    DeclareFunctionUtil(null, "eSystem_Delete");
13505    DeclareFunctionUtil(null, "eClass_GetProperty");
13506    DeclareFunctionUtil(null, "eClass_SetProperty");
13507    DeclareFunctionUtil(null, "eInstance_FireSelfWatchers");
13508    DeclareFunctionUtil(null, "eInstance_SetMethod");
13509    DeclareFunctionUtil(null, "eInstance_IncRef");
13510    DeclareFunctionUtil(null, "eInstance_StopWatching");
13511    DeclareFunctionUtil(null, "eInstance_Watch");
13512    DeclareFunctionUtil(null, "eInstance_FireWatchers");
13513    reachedPass15 = true;
13514
13515    for(external = ast->first; external; external = external.next)
13516    {
13517       afterExternal = curExternal = external;
13518       if(external.type == functionExternal)
13519       {
13520          if(memoryGuard)
13521          {
13522             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13523             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13524          }
13525
13526          currentClass = external.function._class;
13527          ProcessFunction(external.function);
13528       }
13529       // There shouldn't be any _class member access here anyways...
13530       else if(external.type == declarationExternal)
13531       {
13532          if(memoryGuard && external.declaration && external.declaration.type == instDeclaration)
13533          {
13534             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13535             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13536          }
13537
13538          currentClass = null;
13539          if(external.declaration)
13540             ProcessDeclaration(external.declaration, true);
13541       }
13542       else if(external.type == classExternal)
13543       {
13544          ClassDefinition _class = external._class;
13545          currentClass = external.symbol.registered;
13546          if(memoryGuard)
13547          {
13548             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13549             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13550          }
13551          if(_class.definitions)
13552          {
13553             ProcessClass(_class.definitions, _class.symbol);
13554          }
13555          if(inCompiler)
13556          {
13557             // Free class data...
13558             ast->Remove(external);
13559             delete external;
13560          }
13561       }
13562       else if(external.type == nameSpaceExternal)
13563       {
13564          thisNameSpace = external.id.string;
13565       }
13566    }
13567    currentClass = null;
13568    thisNameSpace = null;
13569    curExternal = null;
13570 }