compiler/libec: Fixed disappearing cast on units within brackets
[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                ComputeExpression(e);
5729                //FreeExpContents(exp);
5730                FreeType(exp.expType);
5731                FreeType(exp.destType);
5732                *exp = *e;
5733                exp.prev = prev;
5734                exp.next = next;
5735                delete e;
5736                delete list;
5737             }
5738             else
5739             {
5740                FreeExpression(e);
5741             }
5742          }
5743          break;
5744       }
5745       /*
5746
5747       case ExpIndex:
5748       {
5749          Expression e;
5750          exp.isConstant = true;
5751
5752          ComputeExpression(exp.index.exp);
5753          if(!exp.index.exp.isConstant)
5754             exp.isConstant = false;
5755
5756          for(e = exp.index.index->first; e; e = e.next)
5757          {
5758             ComputeExpression(e);
5759             if(!e.next)
5760             {
5761                // Check if this type is int
5762             }
5763             if(!e.isConstant)
5764                exp.isConstant = false;
5765          }
5766          exp.expType = Dereference(exp.index.exp.expType);
5767          break;
5768       }
5769       */
5770       case memberExp:
5771       {
5772          Expression memberExp = exp.member.exp;
5773          Identifier memberID = exp.member.member;
5774
5775          Type type;
5776          ComputeExpression(exp.member.exp);
5777          type = exp.member.exp.expType;
5778          if(type)
5779          {
5780             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);
5781             Property prop = null;
5782             DataMember member = null;
5783             Class convertTo = null;
5784             if(type.kind == subClassType && exp.member.exp.type == classExp)
5785                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5786
5787             if(!_class)
5788             {
5789                char string[256];
5790                Symbol classSym;
5791                string[0] = '\0';
5792                PrintTypeNoConst(type, string, false, true);
5793                classSym = FindClass(string);
5794                _class = classSym ? classSym.registered : null;
5795             }
5796
5797             if(exp.member.member)
5798             {
5799                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5800                if(!prop)
5801                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5802             }
5803             if(!prop && !member && _class && exp.member.member)
5804             {
5805                Symbol classSym = FindClass(exp.member.member.string);
5806                convertTo = _class;
5807                _class = classSym ? classSym.registered : null;
5808                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5809             }
5810
5811             if(prop)
5812             {
5813                if(prop.compiled)
5814                {
5815                   Type type = prop.dataType;
5816                   // TODO: Assuming same base type for units...
5817                   if(_class.type == unitClass)
5818                   {
5819                      if(type.kind == classType)
5820                      {
5821                         Class _class = type._class.registered;
5822                         if(_class.type == unitClass)
5823                         {
5824                            if(!_class.dataType)
5825                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5826                            type = _class.dataType;
5827                         }
5828                      }
5829                      switch(type.kind)
5830                      {
5831                         case floatType:
5832                         {
5833                            float value;
5834                            float (*Get)(float) = (void *)prop.Get;
5835                            GetFloat(exp.member.exp, &value);
5836                            exp.constant = PrintFloat(Get ? Get(value) : value);
5837                            exp.type = constantExp;
5838                            break;
5839                         }
5840                         case doubleType:
5841                         {
5842                            double value;
5843                            double (*Get)(double);
5844                            GetDouble(exp.member.exp, &value);
5845
5846                            if(convertTo)
5847                               Get = (void *)prop.Set;
5848                            else
5849                               Get = (void *)prop.Get;
5850                            exp.constant = PrintDouble(Get ? Get(value) : value);
5851                            exp.type = constantExp;
5852                            break;
5853                         }
5854                      }
5855                   }
5856                   else
5857                   {
5858                      if(convertTo)
5859                      {
5860                         Expression value = exp.member.exp;
5861                         Type type;
5862                         if(!prop.dataType)
5863                            ProcessPropertyType(prop);
5864
5865                         type = prop.dataType;
5866                         if(!type)
5867                         {
5868                             // printf("Investigate this\n");
5869                         }
5870                         else if(_class.type == structClass)
5871                         {
5872                            switch(type.kind)
5873                            {
5874                               case classType:
5875                               {
5876                                  Class propertyClass = type._class.registered;
5877                                  if(propertyClass.type == structClass && value.type == instanceExp)
5878                                  {
5879                                     void (*Set)(void *, void *) = (void *)prop.Set;
5880                                     exp.instance = Instantiation { };
5881                                     exp.instance.data = new0 byte[_class.structSize];
5882                                     exp.instance._class = MkSpecifierName(_class.fullName);
5883                                     exp.instance.loc = exp.loc;
5884                                     exp.type = instanceExp;
5885                                     Set(exp.instance.data, value.instance.data);
5886                                     PopulateInstance(exp.instance);
5887                                  }
5888                                  break;
5889                               }
5890                               case intType:
5891                               {
5892                                  int intValue;
5893                                  void (*Set)(void *, int) = (void *)prop.Set;
5894
5895                                  exp.instance = Instantiation { };
5896                                  exp.instance.data = new0 byte[_class.structSize];
5897                                  exp.instance._class = MkSpecifierName(_class.fullName);
5898                                  exp.instance.loc = exp.loc;
5899                                  exp.type = instanceExp;
5900
5901                                  GetInt(value, &intValue);
5902
5903                                  Set(exp.instance.data, intValue);
5904                                  PopulateInstance(exp.instance);
5905                                  break;
5906                               }
5907                               case int64Type:
5908                               {
5909                                  int64 intValue;
5910                                  void (*Set)(void *, int64) = (void *)prop.Set;
5911
5912                                  exp.instance = Instantiation { };
5913                                  exp.instance.data = new0 byte[_class.structSize];
5914                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5915                                  exp.instance.loc = exp.loc;
5916                                  exp.type = instanceExp;
5917
5918                                  GetInt64(value, &intValue);
5919
5920                                  Set(exp.instance.data, intValue);
5921                                  PopulateInstance(exp.instance);
5922                                  break;
5923                               }
5924                               case intPtrType:
5925                               {
5926                                  // TOFIX:
5927                                  intptr intValue;
5928                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5929
5930                                  exp.instance = Instantiation { };
5931                                  exp.instance.data = new0 byte[_class.structSize];
5932                                  exp.instance._class = MkSpecifierName(_class.fullName);
5933                                  exp.instance.loc = exp.loc;
5934                                  exp.type = instanceExp;
5935
5936                                  GetIntPtr(value, &intValue);
5937
5938                                  Set(exp.instance.data, intValue);
5939                                  PopulateInstance(exp.instance);
5940                                  break;
5941                               }
5942                               case intSizeType:
5943                               {
5944                                  // TOFIX:
5945                                  intsize intValue;
5946                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5947
5948                                  exp.instance = Instantiation { };
5949                                  exp.instance.data = new0 byte[_class.structSize];
5950                                  exp.instance._class = MkSpecifierName(_class.fullName);
5951                                  exp.instance.loc = exp.loc;
5952                                  exp.type = instanceExp;
5953
5954                                  GetIntSize(value, &intValue);
5955
5956                                  Set(exp.instance.data, intValue);
5957                                  PopulateInstance(exp.instance);
5958                                  break;
5959                               }
5960                               case floatType:
5961                               {
5962                                  float floatValue;
5963                                  void (*Set)(void *, float) = (void *)prop.Set;
5964
5965                                  exp.instance = Instantiation { };
5966                                  exp.instance.data = new0 byte[_class.structSize];
5967                                  exp.instance._class = MkSpecifierName(_class.fullName);
5968                                  exp.instance.loc = exp.loc;
5969                                  exp.type = instanceExp;
5970
5971                                  GetFloat(value, &floatValue);
5972
5973                                  Set(exp.instance.data, floatValue);
5974                                  PopulateInstance(exp.instance);
5975                                  break;
5976                               }
5977                               case doubleType:
5978                               {
5979                                  double doubleValue;
5980                                  void (*Set)(void *, double) = (void *)prop.Set;
5981
5982                                  exp.instance = Instantiation { };
5983                                  exp.instance.data = new0 byte[_class.structSize];
5984                                  exp.instance._class = MkSpecifierName(_class.fullName);
5985                                  exp.instance.loc = exp.loc;
5986                                  exp.type = instanceExp;
5987
5988                                  GetDouble(value, &doubleValue);
5989
5990                                  Set(exp.instance.data, doubleValue);
5991                                  PopulateInstance(exp.instance);
5992                                  break;
5993                               }
5994                            }
5995                         }
5996                         else if(_class.type == bitClass)
5997                         {
5998                            switch(type.kind)
5999                            {
6000                               case classType:
6001                               {
6002                                  Class propertyClass = type._class.registered;
6003                                  if(propertyClass.type == structClass && value.instance.data)
6004                                  {
6005                                     unsigned int (*Set)(void *) = (void *)prop.Set;
6006                                     unsigned int bits = Set(value.instance.data);
6007                                     exp.constant = PrintHexUInt(bits);
6008                                     exp.type = constantExp;
6009                                     break;
6010                                  }
6011                                  else if(_class.type == bitClass)
6012                                  {
6013                                     unsigned int value;
6014                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
6015                                     unsigned int bits;
6016
6017                                     GetUInt(exp.member.exp, &value);
6018                                     bits = Set(value);
6019                                     exp.constant = PrintHexUInt(bits);
6020                                     exp.type = constantExp;
6021                                  }
6022                               }
6023                            }
6024                         }
6025                      }
6026                      else
6027                      {
6028                         if(_class.type == bitClass)
6029                         {
6030                            unsigned int value;
6031                            GetUInt(exp.member.exp, &value);
6032
6033                            switch(type.kind)
6034                            {
6035                               case classType:
6036                               {
6037                                  Class _class = type._class.registered;
6038                                  if(_class.type == structClass)
6039                                  {
6040                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6041
6042                                     exp.instance = Instantiation { };
6043                                     exp.instance.data = new0 byte[_class.structSize];
6044                                     exp.instance._class = MkSpecifierName(_class.fullName);
6045                                     exp.instance.loc = exp.loc;
6046                                     //exp.instance.fullSet = true;
6047                                     exp.type = instanceExp;
6048                                     Get(value, exp.instance.data);
6049                                     PopulateInstance(exp.instance);
6050                                  }
6051                                  else if(_class.type == bitClass)
6052                                  {
6053                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6054                                     uint64 bits = Get(value);
6055                                     exp.constant = PrintHexUInt64(bits);
6056                                     exp.type = constantExp;
6057                                  }
6058                                  break;
6059                               }
6060                            }
6061                         }
6062                         else if(_class.type == structClass)
6063                         {
6064                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6065                            switch(type.kind)
6066                            {
6067                               case classType:
6068                               {
6069                                  Class _class = type._class.registered;
6070                                  if(_class.type == structClass && value)
6071                                  {
6072                                     void (*Get)(void *, void *) = (void *)prop.Get;
6073
6074                                     exp.instance = Instantiation { };
6075                                     exp.instance.data = new0 byte[_class.structSize];
6076                                     exp.instance._class = MkSpecifierName(_class.fullName);
6077                                     exp.instance.loc = exp.loc;
6078                                     //exp.instance.fullSet = true;
6079                                     exp.type = instanceExp;
6080                                     Get(value, exp.instance.data);
6081                                     PopulateInstance(exp.instance);
6082                                  }
6083                                  break;
6084                               }
6085                            }
6086                         }
6087                         /*else
6088                         {
6089                            char * value = exp.member.exp.instance.data;
6090                            switch(type.kind)
6091                            {
6092                               case classType:
6093                               {
6094                                  Class _class = type._class.registered;
6095                                  if(_class.type == normalClass)
6096                                  {
6097                                     void *(*Get)(void *) = (void *)prop.Get;
6098
6099                                     exp.instance = Instantiation { };
6100                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6101                                     exp.type = instanceExp;
6102                                     exp.instance.data = Get(value, exp.instance.data);
6103                                  }
6104                                  break;
6105                               }
6106                            }
6107                         }
6108                         */
6109                      }
6110                   }
6111                }
6112                else
6113                {
6114                   exp.isConstant = false;
6115                }
6116             }
6117             else if(member)
6118             {
6119             }
6120          }
6121
6122          if(exp.type != ExpressionType::memberExp)
6123          {
6124             FreeExpression(memberExp);
6125             FreeIdentifier(memberID);
6126          }
6127          break;
6128       }
6129       case typeSizeExp:
6130       {
6131          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6132          FreeExpContents(exp);
6133          exp.constant = PrintUInt(ComputeTypeSize(type));
6134          exp.type = constantExp;
6135          FreeType(type);
6136          break;
6137       }
6138       case classSizeExp:
6139       {
6140          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6141          if(classSym && classSym.registered)
6142          {
6143             if(classSym.registered.fixed)
6144             {
6145                FreeSpecifier(exp._class);
6146                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6147                exp.type = constantExp;
6148             }
6149             else
6150             {
6151                char className[1024];
6152                strcpy(className, "__ecereClass_");
6153                FullClassNameCat(className, classSym.string, true);
6154
6155                DeclareClass(curExternal, classSym, className);
6156
6157                FreeExpContents(exp);
6158                exp.type = pointerExp;
6159                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6160                exp.member.member = MkIdentifier("structSize");
6161             }
6162          }
6163          break;
6164       }
6165       case castExp:
6166       //case constantExp:
6167       {
6168          Type type;
6169          Expression e = exp;
6170          if(exp.type == castExp)
6171          {
6172             if(exp.cast.exp)
6173                ComputeExpression(exp.cast.exp);
6174             e = exp.cast.exp;
6175          }
6176          if(e && exp.expType)
6177          {
6178             /*if(exp.destType)
6179                type = exp.destType;
6180             else*/
6181                type = exp.expType;
6182             if(type.kind == classType)
6183             {
6184                Class _class = type._class.registered;
6185                if(_class && (_class.type == unitClass || _class.type == bitClass))
6186                {
6187                   if(!_class.dataType)
6188                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6189                   type = _class.dataType;
6190                }
6191             }
6192
6193             switch(type.kind)
6194             {
6195                case _BoolType:
6196                case charType:
6197                   if(type.isSigned)
6198                   {
6199                      char value = 0;
6200                      if(GetChar(e, &value))
6201                      {
6202                         FreeExpContents(exp);
6203                         exp.constant = PrintChar(value);
6204                         exp.type = constantExp;
6205                      }
6206                   }
6207                   else
6208                   {
6209                      unsigned char value = 0;
6210                      if(GetUChar(e, &value))
6211                      {
6212                         FreeExpContents(exp);
6213                         exp.constant = PrintUChar(value);
6214                         exp.type = constantExp;
6215                      }
6216                   }
6217                   break;
6218                case shortType:
6219                   if(type.isSigned)
6220                   {
6221                      short value = 0;
6222                      if(GetShort(e, &value))
6223                      {
6224                         FreeExpContents(exp);
6225                         exp.constant = PrintShort(value);
6226                         exp.type = constantExp;
6227                      }
6228                   }
6229                   else
6230                   {
6231                      unsigned short value = 0;
6232                      if(GetUShort(e, &value))
6233                      {
6234                         FreeExpContents(exp);
6235                         exp.constant = PrintUShort(value);
6236                         exp.type = constantExp;
6237                      }
6238                   }
6239                   break;
6240                case intType:
6241                   if(type.isSigned)
6242                   {
6243                      int value = 0;
6244                      if(GetInt(e, &value))
6245                      {
6246                         FreeExpContents(exp);
6247                         exp.constant = PrintInt(value);
6248                         exp.type = constantExp;
6249                      }
6250                   }
6251                   else
6252                   {
6253                      unsigned int value = 0;
6254                      if(GetUInt(e, &value))
6255                      {
6256                         FreeExpContents(exp);
6257                         exp.constant = PrintUInt(value);
6258                         exp.type = constantExp;
6259                      }
6260                   }
6261                   break;
6262                case int64Type:
6263                   if(type.isSigned)
6264                   {
6265                      int64 value = 0;
6266                      if(GetInt64(e, &value))
6267                      {
6268                         FreeExpContents(exp);
6269                         exp.constant = PrintInt64(value);
6270                         exp.type = constantExp;
6271                      }
6272                   }
6273                   else
6274                   {
6275                      uint64 value = 0;
6276                      if(GetUInt64(e, &value))
6277                      {
6278                         FreeExpContents(exp);
6279                         exp.constant = PrintUInt64(value);
6280                         exp.type = constantExp;
6281                      }
6282                   }
6283                   break;
6284                case intPtrType:
6285                   if(type.isSigned)
6286                   {
6287                      intptr value = 0;
6288                      if(GetIntPtr(e, &value))
6289                      {
6290                         FreeExpContents(exp);
6291                         exp.constant = PrintInt64((int64)value);
6292                         exp.type = constantExp;
6293                      }
6294                   }
6295                   else
6296                   {
6297                      uintptr value = 0;
6298                      if(GetUIntPtr(e, &value))
6299                      {
6300                         FreeExpContents(exp);
6301                         exp.constant = PrintUInt64((uint64)value);
6302                         exp.type = constantExp;
6303                      }
6304                   }
6305                   break;
6306                case intSizeType:
6307                   if(type.isSigned)
6308                   {
6309                      intsize value = 0;
6310                      if(GetIntSize(e, &value))
6311                      {
6312                         FreeExpContents(exp);
6313                         exp.constant = PrintInt64((int64)value);
6314                         exp.type = constantExp;
6315                      }
6316                   }
6317                   else
6318                   {
6319                      uintsize value = 0;
6320                      if(GetUIntSize(e, &value))
6321                      {
6322                         FreeExpContents(exp);
6323                         exp.constant = PrintUInt64((uint64)value);
6324                         exp.type = constantExp;
6325                      }
6326                   }
6327                   break;
6328                case floatType:
6329                {
6330                   float value = 0;
6331                   if(GetFloat(e, &value))
6332                   {
6333                      FreeExpContents(exp);
6334                      exp.constant = PrintFloat(value);
6335                      exp.type = constantExp;
6336                   }
6337                   break;
6338                }
6339                case doubleType:
6340                {
6341                   double value = 0;
6342                   if(GetDouble(e, &value))
6343                   {
6344                      FreeExpContents(exp);
6345                      exp.constant = PrintDouble(value);
6346                      exp.type = constantExp;
6347                   }
6348                   break;
6349                }
6350             }
6351          }
6352          break;
6353       }
6354       case conditionExp:
6355       {
6356          Operand op1 { };
6357          Operand op2 { };
6358          Operand op3 { };
6359
6360          if(exp.cond.exp)
6361             // Caring only about last expression for now...
6362             ComputeExpression(exp.cond.exp->last);
6363          if(exp.cond.elseExp)
6364             ComputeExpression(exp.cond.elseExp);
6365          if(exp.cond.cond)
6366             ComputeExpression(exp.cond.cond);
6367
6368          op1 = GetOperand(exp.cond.cond);
6369          if(op1.type) op1.type.refCount++;
6370          op2 = GetOperand(exp.cond.exp->last);
6371          if(op2.type) op2.type.refCount++;
6372          op3 = GetOperand(exp.cond.elseExp);
6373          if(op3.type) op3.type.refCount++;
6374
6375          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6376          if(op1.type) FreeType(op1.type);
6377          if(op2.type) FreeType(op2.type);
6378          if(op3.type) FreeType(op3.type);
6379          break;
6380       }
6381    }
6382 }
6383
6384 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6385 {
6386    bool result = true;
6387    if(destType)
6388    {
6389       OldList converts { };
6390       Conversion convert;
6391
6392       if(destType.kind == voidType)
6393          return false;
6394
6395       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6396          result = false;
6397       if(converts.count)
6398       {
6399          // for(convert = converts.last; convert; convert = convert.prev)
6400          for(convert = converts.first; convert; convert = convert.next)
6401          {
6402             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6403             if(!empty)
6404             {
6405                Expression newExp { };
6406                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6407
6408                // TODO: Check this...
6409                *newExp = *exp;
6410                newExp.prev = null;
6411                newExp.next = null;
6412                newExp.destType = null;
6413
6414                if(convert.isGet)
6415                {
6416                   // [exp].ColorRGB
6417                   exp.type = memberExp;
6418                   exp.addedThis = true;
6419                   exp.member.exp = newExp;
6420                   FreeType(exp.member.exp.expType);
6421
6422                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6423                   exp.member.exp.expType.classObjectType = objectType;
6424                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6425                   exp.member.memberType = propertyMember;
6426                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6427                   // TESTING THIS... for (int)degrees
6428                   exp.needCast = true;
6429                   if(exp.expType) exp.expType.refCount++;
6430                   ApplyAnyObjectLogic(exp.member.exp);
6431                }
6432                else
6433                {
6434
6435                   /*if(exp.isConstant)
6436                   {
6437                      // Color { ColorRGB = [exp] };
6438                      exp.type = instanceExp;
6439                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6440                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6441                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6442                   }
6443                   else*/
6444                   {
6445                      // If not constant, don't turn it yet into an instantiation
6446                      // (Go through the deep members system first)
6447                      exp.type = memberExp;
6448                      exp.addedThis = true;
6449                      exp.member.exp = newExp;
6450
6451                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6452                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6453                         newExp.expType._class.registered.type == noHeadClass)
6454                      {
6455                         newExp.byReference = true;
6456                      }
6457
6458                      FreeType(exp.member.exp.expType);
6459                      /*exp.member.exp.expType = convert.convert.dataType;
6460                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6461                      exp.member.exp.expType = null;
6462                      if(convert.convert.dataType)
6463                      {
6464                         exp.member.exp.expType = { };
6465                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6466                         exp.member.exp.expType.refCount = 1;
6467                         exp.member.exp.expType.classObjectType = objectType;
6468                         ApplyAnyObjectLogic(exp.member.exp);
6469                      }
6470
6471                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6472                      exp.member.memberType = reverseConversionMember;
6473                      exp.expType = convert.resultType ? convert.resultType :
6474                         MkClassType(convert.convert._class.fullName);
6475                      exp.needCast = true;
6476                      if(convert.resultType) convert.resultType.refCount++;
6477                   }
6478                }
6479             }
6480             else
6481             {
6482                FreeType(exp.expType);
6483                if(convert.isGet)
6484                {
6485                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6486                   if(exp.destType.casted)
6487                      exp.needCast = true;
6488                   if(exp.expType) exp.expType.refCount++;
6489                }
6490                else
6491                {
6492                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6493                   if(exp.destType.casted)
6494                      exp.needCast = true;
6495                   if(convert.resultType)
6496                      convert.resultType.refCount++;
6497                }
6498             }
6499          }
6500          if(exp.isConstant && inCompiler)
6501             ComputeExpression(exp);
6502
6503          converts.Free(FreeConvert);
6504       }
6505
6506       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6507       {
6508          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6509       }
6510       if(!result && exp.expType && exp.destType)
6511       {
6512          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6513              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6514             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6515             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6516             result = true;
6517       }
6518    }
6519    // if(result) CheckTemplateTypes(exp);
6520    return result;
6521 }
6522
6523 void CheckTemplateTypes(Expression exp)
6524 {
6525    /*
6526    bool et = exp.expType ? exp.expType.passAsTemplate : false;
6527    bool dt = exp.destType ? exp.destType.passAsTemplate : false;
6528    */
6529    Expression nbExp = GetNonBracketsExp(exp);
6530    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6531       (nbExp == exp || nbExp.type != castExp))
6532    {
6533       Expression newExp { };
6534       Context context;
6535       TypeKind kind = exp.expType.kind;
6536       *newExp = *exp;
6537       if(exp.destType) exp.destType.refCount++;
6538       if(exp.expType)  exp.expType.refCount++;
6539       newExp.prev = null;
6540       newExp.next = null;
6541
6542       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6543       {
6544          Class c = exp.expType._class.registered;
6545          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6546          {
6547             if(!c.dataType)
6548                c.dataType = ProcessTypeString(c.dataTypeString, false);
6549             kind = c.dataType.kind;
6550          }
6551       }
6552
6553       switch(kind)
6554       {
6555          case doubleType:
6556             if(exp.destType.classObjectType)
6557             {
6558                // We need to pass the address, just pass it along (Undo what was done above)
6559                if(exp.destType) exp.destType.refCount--;
6560                if(exp.expType)  exp.expType.refCount--;
6561                delete newExp;
6562             }
6563             else
6564             {
6565                // If we're looking for value:
6566                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6567                OldList * specs;
6568                OldList * unionDefs = MkList();
6569                OldList * statements = MkList();
6570                context = PushContext();
6571                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6572                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6573                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6574                exp.type = extensionCompoundExp;
6575                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6576                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6577                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6578                exp.compound.compound.context = context;
6579                PopContext(context);
6580             }
6581             break;
6582          default:
6583             exp.type = castExp;
6584             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6585             if((exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass) || exp.expType.isPointerType)
6586                exp.cast.exp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), MkExpBrackets(MkListOne(newExp)));
6587             else
6588                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6589             exp.needCast = true;
6590             break;
6591       }
6592    }
6593    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6594    {
6595       Expression newExp { };
6596       Context context;
6597       TypeKind kind = exp.expType.kind;
6598       *newExp = *exp;
6599       if(exp.destType) exp.destType.refCount++;
6600       if(exp.expType)  exp.expType.refCount++;
6601       newExp.prev = null;
6602       newExp.next = null;
6603
6604       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6605       {
6606          Class c = exp.expType._class.registered;
6607          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6608          {
6609             if(!c.dataType)
6610                c.dataType = ProcessTypeString(c.dataTypeString, false);
6611             kind = c.dataType.kind;
6612          }
6613       }
6614
6615       switch(kind)
6616       {
6617          case doubleType:
6618             if(exp.destType.classObjectType)
6619             {
6620                // We need to pass the address, just pass it along (Undo what was done above)
6621                if(exp.destType) exp.destType.refCount--;
6622                if(exp.expType)  exp.expType.refCount--;
6623                delete newExp;
6624             }
6625             else
6626             {
6627                // If we're looking for value:
6628                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6629                OldList * specs;
6630                OldList * unionDefs = MkList();
6631                OldList * statements = MkList();
6632                context = PushContext();
6633                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6634                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6635                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6636                exp.type = extensionCompoundExp;
6637                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6638                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6639                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6640                exp.compound.compound.context = context;
6641                PopContext(context);
6642             }
6643             break;
6644          case classType:
6645          {
6646             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6647             {
6648                exp.type = bracketsExp;
6649
6650                newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6651                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6652                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6653                ProcessExpressionType(exp.list->first);
6654                break;
6655             }
6656             else
6657             {
6658                exp.type = bracketsExp;
6659                if(exp.expType.isPointerType)
6660                {
6661                   exp.needTemplateCast = 2;
6662                   newExp.needCast = true;
6663                   newExp.needTemplateCast = 2;
6664                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6665                }
6666
6667                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6668                exp.needTemplateCast = 2;
6669                newExp.needCast = true;
6670                newExp.needTemplateCast = 2;
6671                ProcessExpressionType(exp.list->first);
6672                break;
6673             }
6674          }
6675          default:
6676          {
6677             if(exp.expType.kind == templateType)
6678             {
6679                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6680                if(type)
6681                {
6682                   FreeType(exp.destType);
6683                   FreeType(exp.expType);
6684                   delete newExp;
6685                   break;
6686                }
6687             }
6688             /*if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6689             {
6690                // When was this required?    Removed to address using templated values to pass to printf()
6691                exp.type = opExp;
6692                exp.op.op = '*';
6693                exp.op.exp1 = null;
6694                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6695                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6696             }
6697             else*/
6698             {
6699                char typeString[1024];
6700                Declarator decl;
6701                OldList * specs = MkList();
6702                typeString[0] = '\0';
6703                PrintType(exp.expType, typeString, false, false);
6704                decl = SpecDeclFromString(typeString, specs, null);
6705
6706                exp.type = castExp;
6707                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6708                exp.cast.typeName = MkTypeName(specs, decl);
6709                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6710                exp.cast.exp.needCast = true;
6711                exp.needTemplateCast = 2;
6712                newExp.needTemplateCast = 2;
6713             }
6714             break;
6715          }
6716       }
6717    }
6718 }
6719 // TODO: The Symbol tree should be reorganized by namespaces
6720 // Name Space:
6721 //    - Tree of all symbols within (stored without namespace)
6722 //    - Tree of sub-namespaces
6723
6724 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6725 {
6726    int nsLen = strlen(nameSpace);
6727    Symbol symbol;
6728    // Start at the name space prefix
6729    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6730    {
6731       char * s = symbol.string;
6732       if(!strncmp(s, nameSpace, nsLen))
6733       {
6734          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6735          int c;
6736          char * namePart;
6737          for(c = strlen(s)-1; c >= 0; c--)
6738             if(s[c] == ':')
6739                break;
6740
6741          namePart = s+c+1;
6742          if(!strcmp(namePart, name))
6743          {
6744             // TODO: Error on ambiguity
6745             return symbol;
6746          }
6747       }
6748       else
6749          break;
6750    }
6751    return null;
6752 }
6753
6754 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6755 {
6756    int c;
6757    char nameSpace[1024];
6758    const char * namePart;
6759    bool gotColon = false;
6760
6761    nameSpace[0] = '\0';
6762    for(c = strlen(name)-1; c >= 0; c--)
6763       if(name[c] == ':')
6764       {
6765          gotColon = true;
6766          break;
6767       }
6768
6769    namePart = name+c+1;
6770    while(c >= 0 && name[c] == ':') c--;
6771    if(c >= 0)
6772    {
6773       // Try an exact match first
6774       Symbol symbol = (Symbol)tree.FindString(name);
6775       if(symbol)
6776          return symbol;
6777
6778       // Namespace specified
6779       memcpy(nameSpace, name, c + 1);
6780       nameSpace[c+1] = 0;
6781
6782       return ScanWithNameSpace(tree, nameSpace, namePart);
6783    }
6784    else if(gotColon)
6785    {
6786       // Looking for a global symbol, e.g. ::Sleep()
6787       Symbol symbol = (Symbol)tree.FindString(namePart);
6788       return symbol;
6789    }
6790    else
6791    {
6792       // Name only (no namespace specified)
6793       Symbol symbol = (Symbol)tree.FindString(namePart);
6794       if(symbol)
6795          return symbol;
6796       return ScanWithNameSpace(tree, "", namePart);
6797    }
6798    return null;
6799 }
6800
6801 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6802 {
6803 #ifdef _DEBUG
6804    //Time startTime = GetTime();
6805 #endif
6806    // Optimize this later? Do this before/less?
6807    Context ctx;
6808    Symbol symbol = null;
6809
6810    // First, check if the identifier is declared inside the function
6811    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6812
6813    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6814    {
6815       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6816       {
6817          symbol = null;
6818          if(thisNameSpace)
6819          {
6820             char curName[1024];
6821             strcpy(curName, thisNameSpace);
6822             strcat(curName, "::");
6823             strcat(curName, name);
6824             // Try to resolve in current namespace first
6825             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6826          }
6827          if(!symbol)
6828             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6829       }
6830       else
6831          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6832
6833       if(symbol || ctx == endContext) break;
6834    }
6835    if(inCompiler && symbol && ctx == globalContext && symbol.pointerExternal && curExternal && symbol.pointerExternal != curExternal)
6836       curExternal.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
6837 #ifdef _DEBUG
6838    //findSymbolTotalTime += GetTime() - startTime;
6839 #endif
6840    return symbol;
6841 }
6842
6843 static void GetTypeSpecs(Type type, OldList * specs)
6844 {
6845    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6846    switch(type.kind)
6847    {
6848       case classType:
6849       {
6850          if(type._class.registered)
6851          {
6852             if(!type._class.registered.dataType)
6853                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6854             GetTypeSpecs(type._class.registered.dataType, specs);
6855          }
6856          break;
6857       }
6858       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6859       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6860       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6861       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6862       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6863       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6864       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6865       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6866       case intType:
6867       default:
6868          ListAdd(specs, MkSpecifier(INT)); break;
6869    }
6870 }
6871
6872 static void PrintArraySize(Type arrayType, char * string)
6873 {
6874    char size[256];
6875    size[0] = '\0';
6876    strcat(size, "[");
6877    if(arrayType.enumClass)
6878       strcat(size, arrayType.enumClass.string);
6879    else if(arrayType.arraySizeExp)
6880       PrintExpression(arrayType.arraySizeExp, size);
6881    strcat(size, "]");
6882    strcat(string, size);
6883 }
6884
6885 // WARNING : This function expects a null terminated string since it recursively concatenate...
6886 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6887 {
6888    if(type)
6889    {
6890       if(printConst && type.constant)
6891          strcat(string, "const ");
6892       switch(type.kind)
6893       {
6894          case classType:
6895          {
6896             Symbol c = type._class;
6897             bool isObjectBaseClass = !c || !c.string || !strcmp(c.string, "class");
6898             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6899             //       look into merging with thisclass ?
6900             if(type.classObjectType == typedObject && isObjectBaseClass)
6901                strcat(string, "typed_object");
6902             else if(type.classObjectType == anyObject && isObjectBaseClass)
6903                strcat(string, "any_object");
6904             else
6905             {
6906                if(c && c.string)
6907                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6908             }
6909             if(type.byReference)
6910                strcat(string, " &");
6911             break;
6912          }
6913          case voidType: strcat(string, "void"); break;
6914          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6915          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6916          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6917          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6918          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6919          case _BoolType: strcat(string, "_Bool"); break;
6920          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6921          case floatType: strcat(string, "float"); break;
6922          case doubleType: strcat(string, "double"); break;
6923          case structType:
6924             if(type.enumName)
6925             {
6926                strcat(string, "struct ");
6927                strcat(string, type.enumName);
6928             }
6929             else if(type.typeName)
6930                strcat(string, type.typeName);
6931             else
6932             {
6933                Type member;
6934                strcat(string, "struct { ");
6935                for(member = type.members.first; member; member = member.next)
6936                {
6937                   PrintType(member, string, true, fullName);
6938                   strcat(string,"; ");
6939                }
6940                strcat(string,"}");
6941             }
6942             break;
6943          case unionType:
6944             if(type.enumName)
6945             {
6946                strcat(string, "union ");
6947                strcat(string, type.enumName);
6948             }
6949             else if(type.typeName)
6950                strcat(string, type.typeName);
6951             else
6952             {
6953                strcat(string, "union ");
6954                strcat(string,"(unnamed)");
6955             }
6956             break;
6957          case enumType:
6958             if(type.enumName)
6959             {
6960                strcat(string, "enum ");
6961                strcat(string, type.enumName);
6962             }
6963             else if(type.typeName)
6964                strcat(string, type.typeName);
6965             else
6966                strcat(string, "int"); // "enum");
6967             break;
6968          case ellipsisType:
6969             strcat(string, "...");
6970             break;
6971          case subClassType:
6972             strcat(string, "subclass(");
6973             strcat(string, type._class ? type._class.string : "int");
6974             strcat(string, ")");
6975             break;
6976          case templateType:
6977             strcat(string, type.templateParameter.identifier.string);
6978             break;
6979          case thisClassType:
6980             strcat(string, "thisclass");
6981             break;
6982          case vaListType:
6983             strcat(string, "__builtin_va_list");
6984             break;
6985       }
6986    }
6987 }
6988
6989 static void PrintName(Type type, char * string, bool fullName)
6990 {
6991    if(type.name && type.name[0])
6992    {
6993       if(fullName)
6994          strcat(string, type.name);
6995       else
6996       {
6997          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
6998          if(name) name += 2; else name = type.name;
6999          strcat(string, name);
7000       }
7001    }
7002 }
7003
7004 static void PrintAttribs(Type type, char * string)
7005 {
7006    if(type)
7007    {
7008       if(type.dllExport)   strcat(string, "dllexport ");
7009       if(type.attrStdcall) strcat(string, "stdcall ");
7010    }
7011 }
7012
7013 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
7014 {
7015    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7016    {
7017       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
7018          PrintAttribs(type, string);
7019       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
7020          strcat(string, " const");
7021       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
7022       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7023          strcat(string, " (");
7024       if(type.kind == pointerType)
7025       {
7026          if(type.type.kind == functionType || type.type.kind == methodType)
7027             PrintAttribs(type.type, string);
7028       }
7029       if(type.kind == pointerType)
7030       {
7031          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7032             strcat(string, "*");
7033          else
7034             strcat(string, " *");
7035       }
7036       if(printConst && type.constant && type.kind == pointerType)
7037          strcat(string, " const");
7038    }
7039    else
7040       PrintTypeSpecs(type, string, fullName, printConst);
7041 }
7042
7043 static void PostPrintType(Type type, char * string, bool fullName)
7044 {
7045    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7046       strcat(string, ")");
7047    if(type.kind == arrayType)
7048       PrintArraySize(type, string);
7049    else if(type.kind == functionType)
7050    {
7051       Type param;
7052       strcat(string, "(");
7053       for(param = type.params.first; param; param = param.next)
7054       {
7055          PrintType(param, string, true, fullName);
7056          if(param.next) strcat(string, ", ");
7057       }
7058       strcat(string, ")");
7059    }
7060    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7061       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7062 }
7063
7064 // *****
7065 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7066 // *****
7067 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7068 {
7069    PrePrintType(type, string, fullName, null, printConst);
7070
7071    if(type.thisClass || (printName && type.name && type.name[0]))
7072       strcat(string, " ");
7073    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7074    {
7075       Symbol _class = type.thisClass;
7076       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7077       {
7078          if(type.classObjectType == classPointer)
7079             strcat(string, "class");
7080          else
7081             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7082       }
7083       else if(_class && _class.string)
7084       {
7085          String s = _class.string;
7086          if(fullName)
7087             strcat(string, s);
7088          else
7089          {
7090             char * name = RSearchString(s, "::", strlen(s), true, false);
7091             if(name) name += 2; else name = s;
7092             strcat(string, name);
7093          }
7094       }
7095       strcat(string, "::");
7096    }
7097
7098    if(printName && type.name)
7099       PrintName(type, string, fullName);
7100    PostPrintType(type, string, fullName);
7101    if(type.bitFieldCount)
7102    {
7103       char count[100];
7104       sprintf(count, ":%d", type.bitFieldCount);
7105       strcat(string, count);
7106    }
7107 }
7108
7109 void PrintType(Type type, char * string, bool printName, bool fullName)
7110 {
7111    _PrintType(type, string, printName, fullName, true);
7112 }
7113
7114 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7115 {
7116    _PrintType(type, string, printName, fullName, false);
7117 }
7118
7119 static Type FindMember(Type type, char * string)
7120 {
7121    Type memberType;
7122    for(memberType = type.members.first; memberType; memberType = memberType.next)
7123    {
7124       if(!memberType.name)
7125       {
7126          Type subType = FindMember(memberType, string);
7127          if(subType)
7128             return subType;
7129       }
7130       else if(!strcmp(memberType.name, string))
7131          return memberType;
7132    }
7133    return null;
7134 }
7135
7136 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7137 {
7138    Type memberType;
7139    for(memberType = type.members.first; memberType; memberType = memberType.next)
7140    {
7141       if(!memberType.name)
7142       {
7143          Type subType = FindMember(memberType, string);
7144          if(subType)
7145          {
7146             *offset += memberType.offset;
7147             return subType;
7148          }
7149       }
7150       else if(!strcmp(memberType.name, string))
7151       {
7152          *offset += memberType.offset;
7153          return memberType;
7154       }
7155    }
7156    return null;
7157 }
7158
7159 public bool GetParseError() { return parseError; }
7160
7161 Expression ParseExpressionString(char * expression)
7162 {
7163    parseError = false;
7164
7165    fileInput = TempFile { };
7166    fileInput.Write(expression, 1, strlen(expression));
7167    fileInput.Seek(0, start);
7168
7169    echoOn = false;
7170    parsedExpression = null;
7171    resetScanner();
7172    expression_yyparse();
7173    delete fileInput;
7174
7175    return parsedExpression;
7176 }
7177
7178 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7179 {
7180    Identifier id = exp.identifier;
7181    Method method = null;
7182    Property prop = null;
7183    DataMember member = null;
7184    ClassProperty classProp = null;
7185
7186    if(_class && _class.type == enumClass)
7187    {
7188       NamedLink64 value = null;
7189       Class enumClass = eSystem_FindClass(privateModule, "enum");
7190       if(enumClass)
7191       {
7192          Class baseClass;
7193          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7194          {
7195             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7196             for(value = e.values.first; value; value = value.next)
7197             {
7198                if(!strcmp(value.name, id.string))
7199                   break;
7200             }
7201             if(value)
7202             {
7203                exp.isConstant = true;
7204                if(inCompiler || inPreCompiler || inDebugger)
7205                {
7206                   char constant[256];
7207                   FreeExpContents(exp);
7208
7209                   exp.type = constantExp;
7210                   if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7211                      sprintf(constant, FORMAT64D, value.data);
7212                   else
7213                      sprintf(constant, FORMAT64HEX, value.data);
7214                   exp.constant = CopyString(constant);
7215                }
7216                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7217                exp.expType = MkClassType(baseClass.fullName);
7218                break;
7219             }
7220          }
7221       }
7222       if(value)
7223          return true;
7224    }
7225    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7226    {
7227       ProcessMethodType(method);
7228       exp.expType = Type
7229       {
7230          refCount = 1;
7231          kind = methodType;
7232          method = method;
7233          // Crash here?
7234          // TOCHECK: Put it back to what it was...
7235          // methodClass = _class;
7236          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7237       };
7238       //id._class = null;
7239       return true;
7240    }
7241    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7242    {
7243       if(!prop.dataType)
7244          ProcessPropertyType(prop);
7245       exp.expType = prop.dataType;
7246       if(prop.dataType) prop.dataType.refCount++;
7247       return true;
7248    }
7249    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7250    {
7251       if(!member.dataType)
7252          member.dataType = ProcessTypeString(member.dataTypeString, false);
7253       exp.expType = member.dataType;
7254       if(member.dataType) member.dataType.refCount++;
7255       return true;
7256    }
7257    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7258    {
7259       if(!classProp.dataType)
7260          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7261
7262       if(classProp.constant)
7263       {
7264          FreeExpContents(exp);
7265
7266          exp.isConstant = true;
7267          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7268          {
7269             //char constant[256];
7270             exp.type = stringExp;
7271             exp.constant = QMkString((char *)(uintptr)classProp.Get(_class));
7272          }
7273          else
7274          {
7275             char constant[256];
7276             exp.type = constantExp;
7277             sprintf(constant, "%d", (int)classProp.Get(_class));
7278             exp.constant = CopyString(constant);
7279          }
7280       }
7281       else
7282       {
7283          // TO IMPLEMENT...
7284       }
7285
7286       exp.expType = classProp.dataType;
7287       if(classProp.dataType) classProp.dataType.refCount++;
7288       return true;
7289    }
7290    return false;
7291 }
7292
7293 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7294 {
7295    BinaryTree * tree = &nameSpace.functions;
7296    GlobalData data = (GlobalData)tree->FindString(name);
7297    NameSpace * child;
7298    if(!data)
7299    {
7300       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7301       {
7302          data = ScanGlobalData(child, name);
7303          if(data)
7304             break;
7305       }
7306    }
7307    return data;
7308 }
7309
7310 static GlobalData FindGlobalData(char * name)
7311 {
7312    int start = 0, c;
7313    NameSpace * nameSpace;
7314    nameSpace = globalData;
7315    for(c = 0; name[c]; c++)
7316    {
7317       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7318       {
7319          NameSpace * newSpace;
7320          char * spaceName = new char[c - start + 1];
7321          strncpy(spaceName, name + start, c - start);
7322          spaceName[c-start] = '\0';
7323          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7324          delete spaceName;
7325          if(!newSpace)
7326             return null;
7327          nameSpace = newSpace;
7328          if(name[c] == ':') c++;
7329          start = c+1;
7330       }
7331    }
7332    if(c - start)
7333    {
7334       return ScanGlobalData(nameSpace, name + start);
7335    }
7336    return null;
7337 }
7338
7339 static int definedExpStackPos;
7340 static void * definedExpStack[512];
7341
7342 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7343 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7344 {
7345    Expression prev = checkedExp.prev, next = checkedExp.next;
7346
7347    FreeExpContents(checkedExp);
7348    FreeType(checkedExp.expType);
7349    FreeType(checkedExp.destType);
7350
7351    *checkedExp = *newExp;
7352
7353    delete newExp;
7354
7355    checkedExp.prev = prev;
7356    checkedExp.next = next;
7357 }
7358
7359 void ApplyAnyObjectLogic(Expression e)
7360 {
7361    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7362 #ifdef _DEBUG
7363    char debugExpString[4096];
7364    debugExpString[0] = '\0';
7365    PrintExpression(e, debugExpString);
7366 #endif
7367
7368    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7369    {
7370       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7371       //ellipsisDestType = destType;
7372       if(e && e.expType)
7373       {
7374          Type type = e.expType;
7375          Class _class = null;
7376          //Type destType = e.destType;
7377
7378          if(type.kind == classType && type._class && type._class.registered)
7379          {
7380             _class = type._class.registered;
7381          }
7382          else if(type.kind == subClassType)
7383          {
7384             _class = FindClass("ecere::com::Class").registered;
7385          }
7386          else
7387          {
7388             char string[1024] = "";
7389             Symbol classSym;
7390
7391             PrintTypeNoConst(type, string, false, true);
7392             classSym = FindClass(string);
7393             if(classSym) _class = classSym.registered;
7394          }
7395
7396          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...
7397             (!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))) ||
7398             destType.byReference)))
7399          {
7400             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7401             {
7402                Expression checkedExp = e, newExp;
7403
7404                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7405                {
7406                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7407                   {
7408                      if(checkedExp.type == extensionCompoundExp)
7409                      {
7410                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7411                      }
7412                      else
7413                         checkedExp = checkedExp.list->last;
7414                   }
7415                   else if(checkedExp.type == castExp)
7416                      checkedExp = checkedExp.cast.exp;
7417                }
7418
7419                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7420                {
7421                   newExp = checkedExp.op.exp2;
7422                   checkedExp.op.exp2 = null;
7423                   FreeExpContents(checkedExp);
7424
7425                   if(e.expType && e.expType.passAsTemplate)
7426                   {
7427                      char size[100];
7428                      ComputeTypeSize(e.expType);
7429                      sprintf(size, "%d", e.expType.size);   // Potential 32/64 Bootstrap issue
7430                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7431                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7432                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7433                   }
7434
7435                   ReplaceExpContents(checkedExp, newExp);
7436                   e.byReference = true;
7437                }
7438                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7439                {
7440                   Expression checkedExp; //, newExp;
7441
7442                   {
7443                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7444                      bool hasAddress =
7445                         e.type == identifierExp ||
7446                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7447                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7448                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7449                         e.type == indexExp;
7450
7451                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7452                      {
7453                         Context context = PushContext();
7454                         Declarator decl;
7455                         OldList * specs = MkList();
7456                         char typeString[1024];
7457                         Expression newExp { };
7458
7459                         typeString[0] = '\0';
7460                         *newExp = *e;
7461
7462                         //if(e.destType) e.destType.refCount++;
7463                         // if(exp.expType) exp.expType.refCount++;
7464                         newExp.prev = null;
7465                         newExp.next = null;
7466                         newExp.expType = null;
7467
7468                         PrintTypeNoConst(e.expType, typeString, false, true);
7469                         decl = SpecDeclFromString(typeString, specs, null);
7470                         newExp.destType = ProcessType(specs, decl);
7471
7472                         curContext = context;
7473
7474                         // We need a current compound for this
7475                         if(curCompound)
7476                         {
7477                            char name[100];
7478                            OldList * stmts = MkList();
7479                            e.type = extensionCompoundExp;
7480                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7481                            if(!curCompound.compound.declarations)
7482                               curCompound.compound.declarations = MkList();
7483                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7484                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7485                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7486                            e.compound = MkCompoundStmt(null, stmts);
7487                         }
7488                         else
7489                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7490
7491                         /*
7492                         e.compound = MkCompoundStmt(
7493                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7494                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7495
7496                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7497                         */
7498
7499                         {
7500                            Type type = e.destType;
7501                            e.destType = { };
7502                            CopyTypeInto(e.destType, type);
7503                            e.destType.refCount = 1;
7504                            e.destType.classObjectType = none;
7505                            FreeType(type);
7506                         }
7507
7508                         e.compound.compound.context = context;
7509                         PopContext(context);
7510                         curContext = context.parent;
7511                      }
7512                   }
7513
7514                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7515                   checkedExp = e;
7516                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7517                   {
7518                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7519                      {
7520                         if(checkedExp.type == extensionCompoundExp)
7521                         {
7522                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7523                         }
7524                         else
7525                            checkedExp = checkedExp.list->last;
7526                      }
7527                      else if(checkedExp.type == castExp)
7528                         checkedExp = checkedExp.cast.exp;
7529                   }
7530                   {
7531                      Expression operand { };
7532                      operand = *checkedExp;
7533                      checkedExp.Clear();
7534                      checkedExp.destType = ProcessTypeString("void *", false);
7535                      checkedExp.expType = checkedExp.destType;
7536                      checkedExp.destType.refCount++;
7537
7538                      checkedExp.type = opExp;
7539                      checkedExp.op.op = '&';
7540                      checkedExp.op.exp1 = null;
7541                      checkedExp.op.exp2 = operand;
7542
7543                      //newExp = MkExpOp(null, '&', checkedExp);
7544                   }
7545                   //ReplaceExpContents(checkedExp, newExp);
7546                }
7547             }
7548          }
7549       }
7550    }
7551    {
7552       // If expression type is a simple class, make it an address
7553       // FixReference(e, true);
7554    }
7555 //#if 0
7556    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7557       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7558          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7559    {
7560       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"))
7561       {
7562          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7563       }
7564       else
7565       {
7566          Expression thisExp { };
7567
7568          *thisExp = *e;
7569          thisExp.prev = null;
7570          thisExp.next = null;
7571          e.Clear();
7572
7573          e.type = bracketsExp;
7574          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7575          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7576             ((Expression)e.list->first).byReference = true;
7577
7578          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7579          {
7580             e.expType = thisExp.expType;
7581             e.expType.refCount++;
7582          }
7583          else*/
7584          {
7585             e.expType = { };
7586             CopyTypeInto(e.expType, thisExp.expType);
7587             e.expType.byReference = false;
7588             e.expType.refCount = 1;
7589
7590             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7591                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7592             {
7593                e.expType.classObjectType = none;
7594             }
7595          }
7596       }
7597    }
7598 // TOFIX: Try this for a nice IDE crash!
7599 //#endif
7600    // The other way around
7601    else
7602 //#endif
7603    if(destType && e.expType &&
7604          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7605          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7606          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7607    {
7608       if(destType.kind == ellipsisType)
7609       {
7610          Compiler_Error($"Unspecified type\n");
7611       }
7612       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7613       {
7614          bool byReference = e.expType.byReference;
7615          Expression thisExp { };
7616          Declarator decl;
7617          OldList * specs = MkList();
7618          char typeString[1024]; // Watch buffer overruns
7619          Type type;
7620          ClassObjectType backupClassObjectType;
7621          bool backupByReference;
7622
7623          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7624             type = e.expType;
7625          else
7626             type = destType;
7627
7628          backupClassObjectType = type.classObjectType;
7629          backupByReference = type.byReference;
7630
7631          type.classObjectType = none;
7632          type.byReference = false;
7633
7634          typeString[0] = '\0';
7635          PrintType(type, typeString, false, true);
7636          decl = SpecDeclFromString(typeString, specs, null);
7637
7638          type.classObjectType = backupClassObjectType;
7639          type.byReference = backupByReference;
7640
7641          *thisExp = *e;
7642          thisExp.prev = null;
7643          thisExp.next = null;
7644          e.Clear();
7645
7646          if( ( type.kind == classType && type._class && type._class.registered &&
7647                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7648                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7649              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7650              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7651          {
7652             bool passAsTemplate = thisExp.destType.passAsTemplate;
7653             Type t;
7654
7655             destType.refCount++;
7656
7657             e.type = opExp;
7658             e.op.op = '*';
7659             e.op.exp1 = null;
7660             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7661
7662             t = { };
7663             CopyTypeInto(t, thisExp.destType);
7664             t.passAsTemplate = false;
7665             FreeType(thisExp.destType);
7666             thisExp.destType = t;
7667
7668             t = { };
7669             CopyTypeInto(t, destType);
7670             t.passAsTemplate = passAsTemplate;
7671             FreeType(destType);
7672             destType = t;
7673             destType.refCount = 0;
7674
7675             e.expType = { };
7676             CopyTypeInto(e.expType, type);
7677             if(type.passAsTemplate)
7678             {
7679                e.expType.classObjectType = none;
7680                e.expType.passAsTemplate = false;
7681             }
7682             e.expType.byReference = false;
7683             e.expType.refCount = 1;
7684          }
7685          else
7686          {
7687             e.type = castExp;
7688             e.cast.typeName = MkTypeName(specs, decl);
7689             e.cast.exp = thisExp;
7690             e.byReference = true;
7691             e.expType = type;
7692             type.refCount++;
7693          }
7694
7695          if(e.destType)
7696             FreeType(e.destType);
7697
7698          e.destType = destType;
7699          destType.refCount++;
7700       }
7701    }
7702 }
7703
7704 void ApplyLocation(Expression exp, Location loc)
7705 {
7706    exp.loc = loc;
7707    switch(exp.type)
7708    {
7709       case opExp:
7710          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7711          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7712          break;
7713       case bracketsExp:
7714          if(exp.list)
7715          {
7716             Expression e;
7717             for(e = exp.list->first; e; e = e.next)
7718                ApplyLocation(e, loc);
7719          }
7720          break;
7721       case indexExp:
7722          if(exp.index.index)
7723          {
7724             Expression e;
7725             for(e = exp.index.index->first; e; e = e.next)
7726                ApplyLocation(e, loc);
7727          }
7728          if(exp.index.exp)
7729             ApplyLocation(exp.index.exp, loc);
7730          break;
7731       case callExp:
7732          if(exp.call.arguments)
7733          {
7734             Expression arg;
7735             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7736                ApplyLocation(arg, loc);
7737          }
7738          if(exp.call.exp)
7739             ApplyLocation(exp.call.exp, loc);
7740          break;
7741       case memberExp:
7742       case pointerExp:
7743          if(exp.member.exp)
7744             ApplyLocation(exp.member.exp, loc);
7745          break;
7746       case castExp:
7747          if(exp.cast.exp)
7748             ApplyLocation(exp.cast.exp, loc);
7749          break;
7750       case conditionExp:
7751          if(exp.cond.exp)
7752          {
7753             Expression e;
7754             for(e = exp.cond.exp->first; e; e = e.next)
7755                ApplyLocation(e, loc);
7756          }
7757          if(exp.cond.cond)
7758             ApplyLocation(exp.cond.cond, loc);
7759          if(exp.cond.elseExp)
7760             ApplyLocation(exp.cond.elseExp, loc);
7761          break;
7762       case vaArgExp:
7763          if(exp.vaArg.exp)
7764             ApplyLocation(exp.vaArg.exp, loc);
7765          break;
7766       default:
7767          break;
7768    }
7769 }
7770
7771 void ProcessExpressionType(Expression exp)
7772 {
7773    bool unresolved = false;
7774    Location oldyylloc = yylloc;
7775    bool notByReference = false;
7776 #ifdef _DEBUG
7777    char debugExpString[4096];
7778    debugExpString[0] = '\0';
7779    PrintExpression(exp, debugExpString);
7780 #endif
7781    if(!exp || exp.expType)
7782       return;
7783
7784    //eSystem_Logf("%s\n", expString);
7785
7786    // Testing this here
7787    yylloc = exp.loc;
7788    switch(exp.type)
7789    {
7790       case identifierExp:
7791       {
7792          Identifier id = exp.identifier;
7793          if(!id || !topContext) return;
7794
7795          // DOING THIS LATER NOW...
7796          if(id._class && id._class.name)
7797          {
7798             id.classSym = id._class.symbol; // FindClass(id._class.name);
7799             /* TODO: Name Space Fix ups
7800             if(!id.classSym)
7801                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7802             */
7803          }
7804
7805          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7806          {
7807             exp.expType = ProcessTypeString("Module", true);
7808             break;
7809          }
7810          else */
7811          if(!strcmp(id.string, "__runtimePlatform"))
7812          {
7813             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7814             break;
7815          }
7816          else if(strstr(id.string, "__ecereClass") == id.string)
7817          {
7818             exp.expType = ProcessTypeString("ecere::com::Class", true);
7819             break;
7820          }
7821          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7822          {
7823             // Added this here as well
7824             ReplaceClassMembers(exp, thisClass);
7825             if(exp.type != identifierExp)
7826             {
7827                ProcessExpressionType(exp);
7828                break;
7829             }
7830
7831             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7832                break;
7833          }
7834          else
7835          {
7836             Symbol symbol = null;
7837             bool findInGlobal = false;
7838             if(!topContext.parent && exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == enumClass)
7839                findInGlobal = true;  // In global context, look at enum values first
7840             else
7841                symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7842
7843             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7844             if(!symbol/* && exp.destType*/)
7845             {
7846                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7847                   break;
7848                else
7849                {
7850                   if(thisClass)
7851                   {
7852                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7853                      if(exp.type != identifierExp)
7854                      {
7855                         ProcessExpressionType(exp);
7856                         break;
7857                      }
7858                   }
7859                   // Static methods called from inside the _class
7860                   else if(currentClass && !id._class)
7861                   {
7862                      if(ResolveIdWithClass(exp, currentClass, true))
7863                         break;
7864                   }
7865                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7866                }
7867             }
7868             if(findInGlobal)
7869                symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
7870
7871             // If we manage to resolve this symbol
7872             if(symbol)
7873             {
7874                Type type = symbol.type;
7875                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7876
7877                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7878                {
7879                   Context context = SetupTemplatesContext(_class);
7880                   type = ReplaceThisClassType(_class);
7881                   FinishTemplatesContext(context);
7882                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7883                }
7884
7885                FreeSpecifier(id._class);
7886                id._class = null;
7887                delete id.string;
7888                id.string = CopyString(symbol.string);
7889
7890                id.classSym = null;
7891                exp.expType = type;
7892                if(type)
7893                   type.refCount++;
7894
7895                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7896                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7897                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7898                   // Add missing cases here... enum Classes...
7899                   exp.isConstant = true;
7900
7901                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7902                if(symbol.isParam || !strcmp(id.string, "this"))
7903                {
7904                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7905                      exp.byReference = true;
7906
7907                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7908                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7909                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7910                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7911                   {
7912                      Identifier id = exp.identifier;
7913                      exp.type = bracketsExp;
7914                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7915                   }*/
7916                }
7917
7918                if(symbol.isIterator)
7919                {
7920                   if(symbol.isIterator == 3)
7921                   {
7922                      exp.type = bracketsExp;
7923                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7924                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7925                      exp.expType = null;
7926                      ProcessExpressionType(exp);
7927                   }
7928                   else if(symbol.isIterator != 4)
7929                   {
7930                      exp.type = memberExp;
7931                      exp.member.exp = MkExpIdentifier(exp.identifier);
7932                      exp.member.exp.expType = exp.expType;
7933                      /*if(symbol.isIterator == 6)
7934                         exp.member.member = MkIdentifier("key");
7935                      else*/
7936                         exp.member.member = MkIdentifier("data");
7937                      exp.expType = null;
7938                      ProcessExpressionType(exp);
7939                   }
7940                }
7941                break;
7942             }
7943             else
7944             {
7945                DefinedExpression definedExp = null;
7946                if(thisNameSpace && !(id._class && !id._class.name))
7947                {
7948                   char name[1024];
7949                   strcpy(name, thisNameSpace);
7950                   strcat(name, "::");
7951                   strcat(name, id.string);
7952                   definedExp = eSystem_FindDefine(privateModule, name);
7953                }
7954                if(!definedExp)
7955                   definedExp = eSystem_FindDefine(privateModule, id.string);
7956                if(definedExp)
7957                {
7958                   int c;
7959                   for(c = 0; c<definedExpStackPos; c++)
7960                      if(definedExpStack[c] == definedExp)
7961                         break;
7962                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7963                   {
7964                      Location backupYylloc = yylloc;
7965                      File backInput = fileInput;
7966                      definedExpStack[definedExpStackPos++] = definedExp;
7967
7968                      fileInput = TempFile { };
7969                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7970                      fileInput.Seek(0, start);
7971
7972                      echoOn = false;
7973                      parsedExpression = null;
7974                      resetScanner();
7975                      expression_yyparse();
7976                      delete fileInput;
7977                      if(backInput)
7978                         fileInput = backInput;
7979
7980                      yylloc = backupYylloc;
7981
7982                      if(parsedExpression)
7983                      {
7984                         FreeIdentifier(id);
7985                         exp.type = bracketsExp;
7986                         exp.list = MkListOne(parsedExpression);
7987                         ApplyLocation(parsedExpression, yylloc);
7988                         ProcessExpressionType(exp);
7989                         definedExpStackPos--;
7990                         return;
7991                      }
7992                      definedExpStackPos--;
7993                   }
7994                   else
7995                   {
7996                      if(inCompiler)
7997                      {
7998                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7999                      }
8000                   }
8001                }
8002                else
8003                {
8004                   GlobalData data = null;
8005                   if(thisNameSpace && !(id._class && !id._class.name))
8006                   {
8007                      char name[1024];
8008                      strcpy(name, thisNameSpace);
8009                      strcat(name, "::");
8010                      strcat(name, id.string);
8011                      data = FindGlobalData(name);
8012                   }
8013                   if(!data)
8014                      data = FindGlobalData(id.string);
8015                   if(data)
8016                   {
8017                      DeclareGlobalData(curExternal, data);
8018                      exp.expType = data.dataType;
8019                      if(data.dataType) data.dataType.refCount++;
8020
8021                      delete id.string;
8022                      id.string = CopyString(data.fullName);
8023                      FreeSpecifier(id._class);
8024                      id._class = null;
8025
8026                      break;
8027                   }
8028                   else
8029                   {
8030                      GlobalFunction function = null;
8031                      if(thisNameSpace && !(id._class && !id._class.name))
8032                      {
8033                         char name[1024];
8034                         strcpy(name, thisNameSpace);
8035                         strcat(name, "::");
8036                         strcat(name, id.string);
8037                         function = eSystem_FindFunction(privateModule, name);
8038                      }
8039                      if(!function)
8040                         function = eSystem_FindFunction(privateModule, id.string);
8041                      if(function)
8042                      {
8043                         char name[1024];
8044                         delete id.string;
8045                         id.string = CopyString(function.name);
8046                         name[0] = 0;
8047
8048                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8049                            strcpy(name, "__ecereFunction_");
8050                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8051                         if(DeclareFunction(curExternal, function, name))
8052                         {
8053                            delete id.string;
8054                            id.string = CopyString(name);
8055                         }
8056                         exp.expType = function.dataType;
8057                         if(function.dataType) function.dataType.refCount++;
8058
8059                         FreeSpecifier(id._class);
8060                         id._class = null;
8061
8062                         break;
8063                      }
8064                   }
8065                }
8066             }
8067          }
8068          unresolved = true;
8069          break;
8070       }
8071       case instanceExp:
8072       {
8073          // Class _class;
8074          // Symbol classSym;
8075
8076          if(!exp.instance._class)
8077          {
8078             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8079             {
8080                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8081             }
8082          }
8083
8084          //classSym = FindClass(exp.instance._class.fullName);
8085          //_class = classSym ? classSym.registered : null;
8086
8087          ProcessInstantiationType(exp.instance);
8088
8089          exp.isConstant = exp.instance.isConstant;
8090
8091          /*
8092          if(_class.type == unitClass && _class.base.type != systemClass)
8093          {
8094             {
8095                Type destType = exp.destType;
8096
8097                exp.destType = MkClassType(_class.base.fullName);
8098                exp.expType = MkClassType(_class.fullName);
8099                CheckExpressionType(exp, exp.destType, true);
8100
8101                exp.destType = destType;
8102             }
8103             exp.expType = MkClassType(_class.fullName);
8104          }
8105          else*/
8106          if(exp.instance._class)
8107          {
8108             exp.expType = MkClassType(exp.instance._class.name);
8109             /*if(exp.expType._class && exp.expType._class.registered &&
8110                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8111                exp.expType.byReference = true;*/
8112          }
8113          break;
8114       }
8115       case constantExp:
8116       {
8117          if(!exp.expType)
8118          {
8119             char * constant = exp.constant;
8120             Type type
8121             {
8122                refCount = 1;
8123                constant = true;
8124             };
8125             exp.expType = type;
8126
8127             if(constant[0] == '\'')
8128             {
8129                if((int)((byte *)constant)[1] > 127)
8130                {
8131                   int nb;
8132                   unichar ch = UTF8GetChar(constant + 1, &nb);
8133                   if(nb < 2) ch = constant[1];
8134                   delete constant;
8135                   exp.constant = PrintUInt(ch);
8136                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8137                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8138                   type._class = FindClass("unichar");
8139
8140                   type.isSigned = false;
8141                }
8142                else
8143                {
8144                   type.kind = charType;
8145                   type.isSigned = true;
8146                }
8147             }
8148             else
8149             {
8150                char * dot = strchr(constant, '.');
8151                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8152                char * exponent;
8153                if(isHex)
8154                {
8155                   exponent = strchr(constant, 'p');
8156                   if(!exponent) exponent = strchr(constant, 'P');
8157                }
8158                else
8159                {
8160                   exponent = strchr(constant, 'e');
8161                   if(!exponent) exponent = strchr(constant, 'E');
8162                }
8163
8164                if(dot || exponent)
8165                {
8166                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8167                      type.kind = floatType;
8168                   else
8169                      type.kind = doubleType;
8170                   type.isSigned = true;
8171                }
8172                else
8173                {
8174                   bool isSigned = constant[0] == '-';
8175                   char * endP = null;
8176                   int64 i64 = strtoll(constant, &endP, 0);
8177                   uint64 ui64 = strtoull(constant, &endP, 0);
8178                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8179                   bool forceUnsigned = endP && (!strcmp(endP, "U") || !strcmp(endP, "u") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8180                   if(isSigned)
8181                   {
8182                      if(i64 < MININT)
8183                         is64Bit = true;
8184                   }
8185                   else
8186                   {
8187                      if(ui64 > MAXINT)
8188                      {
8189                         if(ui64 > MAXDWORD)
8190                         {
8191                            is64Bit = true;
8192                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8193                               isSigned = true;
8194                         }
8195                      }
8196                      else if(constant[0] != '0' || !constant[1])
8197                         isSigned = true;
8198                   }
8199                   if(forceUnsigned)
8200                      isSigned = false;
8201                   type.kind = is64Bit ? int64Type : intType;
8202                   type.isSigned = isSigned;
8203                }
8204             }
8205             exp.isConstant = true;
8206             if(exp.destType && exp.destType.kind == doubleType)
8207                type.kind = doubleType;
8208             else if(exp.destType && exp.destType.kind == floatType)
8209                type.kind = floatType;
8210             else if(exp.destType && exp.destType.kind == int64Type)
8211                type.kind = int64Type;
8212          }
8213          break;
8214       }
8215       case stringExp:
8216       {
8217          exp.isConstant = true;      // Why wasn't this constant?
8218          exp.expType = Type
8219          {
8220             refCount = 1;
8221             kind = pointerType;
8222             type = Type
8223             {
8224                refCount = 1;
8225                kind = exp.wideString ? shortType : charType;
8226                constant = true;
8227                isSigned = exp.wideString ? false : true;
8228             }
8229          };
8230          break;
8231       }
8232       case newExp:
8233       case new0Exp:
8234          ProcessExpressionType(exp._new.size);
8235          exp.expType = Type
8236          {
8237             refCount = 1;
8238             kind = pointerType;
8239             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8240          };
8241          DeclareType(curExternal, exp.expType.type, true, false);
8242          break;
8243       case renewExp:
8244       case renew0Exp:
8245          ProcessExpressionType(exp._renew.size);
8246          ProcessExpressionType(exp._renew.exp);
8247          exp.expType = Type
8248          {
8249             refCount = 1;
8250             kind = pointerType;
8251             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8252          };
8253          DeclareType(curExternal, exp.expType.type, true, false);
8254          break;
8255       case opExp:
8256       {
8257          bool assign = false, boolResult = false, boolOps = false;
8258          Type type1 = null, type2 = null;
8259          bool useDestType = false, useSideType = false;
8260          Location oldyylloc = yylloc;
8261          bool useSideUnit = false;
8262          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8263
8264          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8265          Type dummy
8266          {
8267             count = 1;
8268             refCount = 1;
8269          };
8270
8271          switch(exp.op.op)
8272          {
8273             // Assignment Operators
8274             case '=':
8275             case MUL_ASSIGN:
8276             case DIV_ASSIGN:
8277             case MOD_ASSIGN:
8278             case ADD_ASSIGN:
8279             case SUB_ASSIGN:
8280             case LEFT_ASSIGN:
8281             case RIGHT_ASSIGN:
8282             case AND_ASSIGN:
8283             case XOR_ASSIGN:
8284             case OR_ASSIGN:
8285                assign = true;
8286                break;
8287             // boolean Operators
8288             case '!':
8289                // Expect boolean operators
8290                //boolOps = true;
8291                //boolResult = true;
8292                break;
8293             case AND_OP:
8294             case OR_OP:
8295                // Expect boolean operands
8296                boolOps = true;
8297                boolResult = true;
8298                break;
8299             // Comparisons
8300             case EQ_OP:
8301             case '<':
8302             case '>':
8303             case LE_OP:
8304             case GE_OP:
8305             case NE_OP:
8306                // Gives boolean result
8307                boolResult = true;
8308                useSideType = true;
8309                break;
8310             case '+':
8311             case '-':
8312                useSideUnit = true;
8313                useSideType = true;
8314                useDestType = true;
8315                break;
8316
8317             case LEFT_OP:
8318             case RIGHT_OP:
8319                // useSideType = true;
8320                // useDestType = true;
8321                break;
8322
8323             case '|':
8324             case '^':
8325                useSideType = true;
8326                useDestType = true;
8327                break;
8328
8329             case '/':
8330             case '%':
8331                useSideType = true;
8332                useDestType = true;
8333                break;
8334             case '&':
8335             case '*':
8336                if(exp.op.exp1)
8337                {
8338                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8339                   useSideType = true;
8340                   useDestType = true;
8341                }
8342                break;
8343
8344             /*// Implement speed etc.
8345             case '*':
8346             case '/':
8347                break;
8348             */
8349          }
8350          if(exp.op.op == '&')
8351          {
8352             // Added this here earlier for Iterator address as key
8353             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8354             {
8355                Identifier id = exp.op.exp2.identifier;
8356                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8357                if(symbol && symbol.isIterator == 2)
8358                {
8359                   exp.type = memberExp;
8360                   exp.member.exp = exp.op.exp2;
8361                   exp.member.member = MkIdentifier("key");
8362                   exp.expType = null;
8363                   exp.op.exp2.expType = symbol.type;
8364                   symbol.type.refCount++;
8365                   ProcessExpressionType(exp);
8366                   FreeType(dummy);
8367                   break;
8368                }
8369                // exp.op.exp2.usage.usageRef = true;
8370             }
8371          }
8372
8373          //dummy.kind = TypeDummy;
8374          if(exp.op.exp1)
8375          {
8376             // Added this check here to use the dest type only for units derived from the base unit
8377             // So that untyped units will use the side unit as opposed to the untyped destination unit
8378             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8379             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8380                useDestType = false;
8381
8382             if(destClass && useDestType &&
8383               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8384
8385               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8386             {
8387                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8388                exp.op.exp1.destType = exp.destType;
8389                exp.op.exp1.opDestType = true;
8390                if(exp.destType)
8391                   exp.destType.refCount++;
8392             }
8393             else if(!assign)
8394             {
8395                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8396                exp.op.exp1.destType = dummy;
8397                dummy.refCount++;
8398             }
8399
8400             // TESTING THIS HERE...
8401             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8402                ProcessExpressionType(exp.op.exp1);
8403             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8404
8405             exp.op.exp1.opDestType = false;
8406
8407             // Fix for unit and ++ / --
8408             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8409                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8410             {
8411                exp.op.exp2 = MkExpConstant("1");
8412                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8413                assign = true;
8414             }
8415
8416             if(exp.op.exp1.destType == dummy)
8417             {
8418                FreeType(dummy);
8419                exp.op.exp1.destType = null;
8420             }
8421
8422             if(exp.op.exp2)
8423             {
8424                if(!assign && exp.op.exp1.expType && (exp.op.exp1.expType.kind == charType || exp.op.exp1.expType.kind == shortType))
8425                {
8426                   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 };
8427                   FreeType(exp.op.exp1.expType);
8428                   exp.op.exp1.expType = type;
8429                }
8430             }
8431
8432             type1 = exp.op.exp1.expType;
8433          }
8434
8435          if(exp.op.exp2)
8436          {
8437             char expString[10240];
8438             expString[0] = '\0';
8439             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8440             {
8441                if(exp.op.exp1)
8442                {
8443                   exp.op.exp2.destType = exp.op.exp1.expType;
8444                   if(exp.op.exp1.expType)
8445                      exp.op.exp1.expType.refCount++;
8446                }
8447                else
8448                {
8449                   exp.op.exp2.destType = exp.destType;
8450                   if(!exp.op.exp1 || (exp.op.op != '&' && exp.op.op != '^'))
8451                      exp.op.exp2.opDestType = true;
8452                   if(exp.destType)
8453                      exp.destType.refCount++;
8454                }
8455
8456                if(type1) type1.refCount++;
8457                exp.expType = type1;
8458             }
8459             else if(assign)
8460             {
8461                if(inCompiler)
8462                   PrintExpression(exp.op.exp2, expString);
8463
8464                if(type1 && type1.kind == pointerType)
8465                {
8466                   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 ||
8467                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8468                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8469                   else if(exp.op.op == '=')
8470                   {
8471                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8472                      exp.op.exp2.destType = type1;
8473                      if(type1)
8474                         type1.refCount++;
8475                   }
8476                }
8477                else
8478                {
8479                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8480                   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/* ||
8481                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8482                   else
8483                   {
8484                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8485                      exp.op.exp2.destType = type1;
8486                      if(type1)
8487                         type1.refCount++;
8488                   }
8489                }
8490                if(type1) type1.refCount++;
8491                exp.expType = type1;
8492             }
8493             else if(destClass &&
8494                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8495                   (destClass.type == enumClass && useDestType)))
8496             {
8497                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8498                exp.op.exp2.destType = exp.destType;
8499                if(exp.op.op != '&' && exp.op.op != '^')
8500                   exp.op.exp2.opDestType = true;
8501                if(exp.destType)
8502                   exp.destType.refCount++;
8503             }
8504             else
8505             {
8506                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8507                exp.op.exp2.destType = dummy;
8508                dummy.refCount++;
8509             }
8510
8511             // TESTING THIS HERE... (DANGEROUS)
8512             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8513                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8514             {
8515                FreeType(exp.op.exp2.destType);
8516                exp.op.exp2.destType = type1;
8517                type1.refCount++;
8518             }
8519             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8520             // Cannot lose the cast on a sizeof
8521             if(exp.op.op == SIZEOF)
8522             {
8523                Expression e = exp.op.exp2;
8524                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8525                {
8526                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8527                   {
8528                      if(e.type == extensionCompoundExp)
8529                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8530                      else
8531                         e = e.list->last;
8532                   }
8533                }
8534                if(e.type == castExp && e.cast.exp)
8535                   e.cast.exp.needCast = true;
8536             }
8537             ProcessExpressionType(exp.op.exp2);
8538             exp.op.exp2.opDestType = false;
8539             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8540
8541             if(!assign && (exp.op.exp1 || exp.op.op == '~'))
8542             {
8543                if(exp.op.exp2.expType && (exp.op.exp2.expType.kind == charType || exp.op.exp2.expType.kind == shortType))
8544                {
8545                   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 };
8546                   FreeType(exp.op.exp2.expType);
8547                   exp.op.exp2.expType = type;
8548                }
8549             }
8550
8551             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8552             {
8553                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)
8554                {
8555                   if(exp.op.op != '=' && type1.type.kind == voidType)
8556                      Compiler_Error($"void *: unknown size\n");
8557                }
8558                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||
8559                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8560                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8561                               exp.op.exp2.expType._class.registered.type == structClass ||
8562                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8563                {
8564                   if(exp.op.op == ADD_ASSIGN)
8565                      Compiler_Error($"cannot add two pointers\n");
8566                }
8567                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8568                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8569                {
8570                   if(exp.op.op == ADD_ASSIGN)
8571                      Compiler_Error($"cannot add two pointers\n");
8572                }
8573                else if(inCompiler)
8574                {
8575                   char type1String[1024];
8576                   char type2String[1024];
8577                   type1String[0] = '\0';
8578                   type2String[0] = '\0';
8579
8580                   PrintType(exp.op.exp2.expType, type1String, false, true);
8581                   PrintType(type1, type2String, false, true);
8582                   ChangeCh(expString, '\n', ' ');
8583                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8584                }
8585             }
8586
8587             if(exp.op.exp2.destType == dummy)
8588             {
8589                FreeType(dummy);
8590                exp.op.exp2.destType = null;
8591             }
8592
8593             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8594             {
8595                type2 = { };
8596                type2.refCount = 1;
8597                CopyTypeInto(type2, exp.op.exp2.expType);
8598                type2.isSigned = true;
8599             }
8600             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8601             {
8602                type2 = { kind = intType };
8603                type2.refCount = 1;
8604                type2.isSigned = true;
8605             }
8606             else
8607             {
8608                type2 = exp.op.exp2.expType;
8609                if(type2) type2.refCount++;
8610             }
8611          }
8612
8613          dummy.kind = voidType;
8614
8615          if(exp.op.op == SIZEOF)
8616          {
8617             exp.expType = Type
8618             {
8619                refCount = 1;
8620                kind = intSizeType;
8621             };
8622             exp.isConstant = true;
8623          }
8624          // Get type of dereferenced pointer
8625          else if(exp.op.op == '*' && !exp.op.exp1)
8626          {
8627             exp.expType = Dereference(type2);
8628             if(type2 && type2.kind == classType)
8629                notByReference = true;
8630          }
8631          else if(exp.op.op == '&' && !exp.op.exp1)
8632             exp.expType = Reference(type2);
8633          else if(exp.op.op == LEFT_OP || exp.op.op == RIGHT_OP)
8634          {
8635             if(exp.op.exp1.expType)
8636             {
8637                exp.expType = exp.op.exp1.expType;
8638                exp.expType.refCount++;
8639             }
8640          }
8641          else if(!assign)
8642          {
8643             if(boolOps)
8644             {
8645                if(exp.op.exp1)
8646                {
8647                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8648                   exp.op.exp1.destType = MkClassType("bool");
8649                   exp.op.exp1.destType.truth = true;
8650                   if(!exp.op.exp1.expType)
8651                      ProcessExpressionType(exp.op.exp1);
8652                   else
8653                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8654                   FreeType(exp.op.exp1.expType);
8655                   exp.op.exp1.expType = MkClassType("bool");
8656                   exp.op.exp1.expType.truth = true;
8657                }
8658                if(exp.op.exp2)
8659                {
8660                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8661                   exp.op.exp2.destType = MkClassType("bool");
8662                   exp.op.exp2.destType.truth = true;
8663                   if(!exp.op.exp2.expType)
8664                      ProcessExpressionType(exp.op.exp2);
8665                   else
8666                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8667                   FreeType(exp.op.exp2.expType);
8668                   exp.op.exp2.expType = MkClassType("bool");
8669                   exp.op.exp2.expType.truth = true;
8670                }
8671             }
8672             else if(exp.op.exp1 && exp.op.exp2 &&
8673                ((useSideType /*&&
8674                      (useSideUnit ||
8675                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8676                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8677                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8678                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8679             {
8680                if(type1 && type2 &&
8681                   // If either both are class or both are not class
8682                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8683                {
8684                   // Added this check for enum subtraction to result in an int type:
8685                   if(exp.op.op == '-' &&
8686                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8687                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8688                   {
8689                      Type intType;
8690                      if(!type1._class.registered.dataType)
8691                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8692                      if(!type2._class.registered.dataType)
8693                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8694
8695                      intType = ProcessTypeString(
8696                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8697
8698                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8699                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8700                      exp.op.exp1.destType = intType;
8701                      exp.op.exp2.destType = intType;
8702                      intType.refCount++;
8703                   }
8704                   else
8705                   {
8706                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8707                      exp.op.exp2.destType = type1;
8708                      type1.refCount++;
8709                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8710                      exp.op.exp1.destType = type2;
8711                      type2.refCount++;
8712                   }
8713
8714                   // Warning here for adding Radians + Degrees with no destination type
8715                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8716                      type1._class.registered && type1._class.registered.type == unitClass &&
8717                      type2._class.registered && type2._class.registered.type == unitClass &&
8718                      type1._class.registered != type2._class.registered)
8719                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8720                         type1._class.string, type2._class.string, type1._class.string);
8721
8722                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8723                   {
8724                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8725                      if(argExp)
8726                      {
8727                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8728
8729                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8730                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8731                            exp.op.exp1)));
8732
8733                         ProcessExpressionType(exp.op.exp1);
8734
8735                         if(type2.kind != pointerType)
8736                         {
8737                            ProcessExpressionType(classExp);
8738
8739                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8740
8741                            if(!exp.op.exp2.expType)
8742                            {
8743                               if(type2)
8744                                  FreeType(type2);
8745                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8746                               type2.refCount++;
8747                            }
8748
8749                            ProcessExpressionType(exp.op.exp2);
8750                         }
8751                      }
8752                   }
8753
8754                   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)))
8755                   {
8756                      if(type1.kind != classType && type1.type.kind == voidType)
8757                         Compiler_Error($"void *: unknown size\n");
8758                      exp.expType = type1;
8759                      if(type1) type1.refCount++;
8760                   }
8761                   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)))
8762                   {
8763                      if(type2.kind != classType && type2.type.kind == voidType)
8764                         Compiler_Error($"void *: unknown size\n");
8765                      exp.expType = type2;
8766                      if(type2) type2.refCount++;
8767                   }
8768                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8769                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8770                   {
8771                      Compiler_Warning($"different levels of indirection\n");
8772                   }
8773                   else
8774                   {
8775                      bool success = false;
8776                      if(type1.kind == pointerType && type2.kind == pointerType)
8777                      {
8778                         if(exp.op.op == '+')
8779                            Compiler_Error($"cannot add two pointers\n");
8780                         else if(exp.op.op == '-')
8781                         {
8782                            // Pointer Subtraction gives integer
8783                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8784                            {
8785                               exp.expType = Type
8786                               {
8787                                  kind = intType;
8788                                  refCount = 1;
8789                               };
8790                               success = true;
8791
8792                               if(type1.type.kind == templateType)
8793                               {
8794                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8795                                  if(argExp)
8796                                  {
8797                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8798
8799                                     ProcessExpressionType(classExp);
8800
8801                                     exp.type = bracketsExp;
8802                                     exp.list = MkListOne(MkExpOp(
8803                                        MkExpBrackets(MkListOne(MkExpOp(
8804                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8805                                              , exp.op.op,
8806                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8807                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8808
8809                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8810                                     FreeType(dummy);
8811                                     return;
8812                                  }
8813                               }
8814                            }
8815                         }
8816                      }
8817
8818                      if(!success && exp.op.exp1.type == constantExp)
8819                      {
8820                         // If first expression is constant, try to match that first
8821                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8822                         {
8823                            if(exp.expType) FreeType(exp.expType);
8824                            exp.expType = exp.op.exp1.destType;
8825                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8826                            success = true;
8827                         }
8828                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8829                         {
8830                            if(exp.expType) FreeType(exp.expType);
8831                            exp.expType = exp.op.exp2.destType;
8832                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8833                            success = true;
8834                         }
8835                      }
8836                      else if(!success)
8837                      {
8838                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8839                         {
8840                            if(exp.expType) FreeType(exp.expType);
8841                            exp.expType = exp.op.exp2.destType;
8842                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8843                            success = true;
8844                         }
8845                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8846                         {
8847                            if(exp.expType) FreeType(exp.expType);
8848                            exp.expType = exp.op.exp1.destType;
8849                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8850                            success = true;
8851                         }
8852                      }
8853                      if(!success)
8854                      {
8855                         char expString1[10240];
8856                         char expString2[10240];
8857                         char type1[1024];
8858                         char type2[1024];
8859                         expString1[0] = '\0';
8860                         expString2[0] = '\0';
8861                         type1[0] = '\0';
8862                         type2[0] = '\0';
8863                         if(inCompiler)
8864                         {
8865                            PrintExpression(exp.op.exp1, expString1);
8866                            ChangeCh(expString1, '\n', ' ');
8867                            PrintExpression(exp.op.exp2, expString2);
8868                            ChangeCh(expString2, '\n', ' ');
8869                            PrintType(exp.op.exp1.expType, type1, false, true);
8870                            PrintType(exp.op.exp2.expType, type2, false, true);
8871                         }
8872
8873                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8874                      }
8875                   }
8876                }
8877                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8878                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8879                {
8880                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8881                   // Convert e.g. / 4 into / 4.0
8882                   exp.op.exp1.destType = type2._class.registered.dataType;
8883                   if(type2._class.registered.dataType)
8884                      type2._class.registered.dataType.refCount++;
8885                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8886                   exp.expType = type2;
8887                   if(type2) type2.refCount++;
8888                }
8889                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8890                {
8891                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8892                   // Convert e.g. / 4 into / 4.0
8893                   exp.op.exp2.destType = type1._class.registered.dataType;
8894                   if(type1._class.registered.dataType)
8895                      type1._class.registered.dataType.refCount++;
8896                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8897                   exp.expType = type1;
8898                   if(type1) type1.refCount++;
8899                }
8900                else if(type1)
8901                {
8902                   bool valid = false;
8903
8904                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8905                   {
8906                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8907
8908                      if(!type1._class.registered.dataType)
8909                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8910                      exp.op.exp2.destType = type1._class.registered.dataType;
8911                      exp.op.exp2.destType.refCount++;
8912
8913                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8914                      if(type2)
8915                         FreeType(type2);
8916                      type2 = exp.op.exp2.destType;
8917                      if(type2) type2.refCount++;
8918
8919                      exp.expType = type2;
8920                      type2.refCount++;
8921                   }
8922
8923                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8924                   {
8925                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8926
8927                      if(!type2._class.registered.dataType)
8928                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8929                      exp.op.exp1.destType = type2._class.registered.dataType;
8930                      exp.op.exp1.destType.refCount++;
8931
8932                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8933                      type1 = exp.op.exp1.destType;
8934                      exp.expType = type1;
8935                      type1.refCount++;
8936                   }
8937
8938                   // TESTING THIS NEW CODE
8939                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8940                   {
8941                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8942                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8943                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8944                      {
8945                         // Convert the enum to an int instead for these operators
8946                         if(op1IsEnum && exp.op.exp2.expType)
8947                         {
8948                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8949                            {
8950                               if(exp.expType) FreeType(exp.expType);
8951                               exp.expType = exp.op.exp2.expType;
8952                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8953                               valid = true;
8954                            }
8955                         }
8956                         else if(op2IsEnum && exp.op.exp1.expType)
8957                         {
8958                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8959                            {
8960                               if(exp.expType) FreeType(exp.expType);
8961                               exp.expType = exp.op.exp1.expType;
8962                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8963                               valid = true;
8964                            }
8965                         }
8966                      }
8967                      else
8968                      {
8969                         if(op1IsEnum && exp.op.exp2.expType)
8970                         {
8971                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8972                            {
8973                               if(exp.expType) FreeType(exp.expType);
8974                               exp.expType = exp.op.exp1.expType;
8975                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8976                               valid = true;
8977                            }
8978                         }
8979                         else if(op2IsEnum && exp.op.exp1.expType)
8980                         {
8981                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8982                            {
8983                               if(exp.expType) FreeType(exp.expType);
8984                               exp.expType = exp.op.exp2.expType;
8985                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8986                               valid = true;
8987                            }
8988                         }
8989                      }
8990                   }
8991
8992                   if(!valid)
8993                   {
8994                      // 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
8995                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8996                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8997                      {
8998                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8999                         exp.op.exp1.destType = type2;
9000                         type2.refCount++;
9001
9002                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9003                         {
9004                            if(exp.expType) FreeType(exp.expType);
9005                            exp.expType = exp.op.exp1.destType;
9006                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9007                         }
9008                      }
9009                      else
9010                      {
9011                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9012                         exp.op.exp2.destType = type1;
9013                         type1.refCount++;
9014
9015                      /*
9016                      // Maybe this was meant to be an enum...
9017                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9018                      {
9019                         Type oldType = exp.op.exp2.expType;
9020                         exp.op.exp2.expType = null;
9021                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
9022                            FreeType(oldType);
9023                         else
9024                            exp.op.exp2.expType = oldType;
9025                      }
9026                      */
9027
9028                      /*
9029                      // TESTING THIS HERE... LATEST ADDITION
9030                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9031                      {
9032                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9033                         exp.op.exp2.destType = type2._class.registered.dataType;
9034                         if(type2._class.registered.dataType)
9035                            type2._class.registered.dataType.refCount++;
9036                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9037
9038                         //exp.expType = type2._class.registered.dataType; //type2;
9039                         //if(type2) type2.refCount++;
9040                      }
9041
9042                      // TESTING THIS HERE... LATEST ADDITION
9043                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9044                      {
9045                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9046                         exp.op.exp1.destType = type1._class.registered.dataType;
9047                         if(type1._class.registered.dataType)
9048                            type1._class.registered.dataType.refCount++;
9049                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9050                         exp.expType = type1._class.registered.dataType; //type1;
9051                         if(type1) type1.refCount++;
9052                      }
9053                      */
9054
9055                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9056                         {
9057                            if(exp.expType) FreeType(exp.expType);
9058                            exp.expType = exp.op.exp2.destType;
9059                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9060                         }
9061                         else if(type1 && type2)
9062                         {
9063                            char expString1[10240];
9064                            char expString2[10240];
9065                            char type1String[1024];
9066                            char type2String[1024];
9067                            expString1[0] = '\0';
9068                            expString2[0] = '\0';
9069                            type1String[0] = '\0';
9070                            type2String[0] = '\0';
9071                            if(inCompiler)
9072                            {
9073                               PrintExpression(exp.op.exp1, expString1);
9074                               ChangeCh(expString1, '\n', ' ');
9075                               PrintExpression(exp.op.exp2, expString2);
9076                               ChangeCh(expString2, '\n', ' ');
9077                               PrintType(exp.op.exp1.expType, type1String, false, true);
9078                               PrintType(exp.op.exp2.expType, type2String, false, true);
9079                            }
9080
9081                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9082
9083                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9084                            {
9085                               exp.expType = exp.op.exp1.expType;
9086                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9087                            }
9088                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9089                            {
9090                               exp.expType = exp.op.exp2.expType;
9091                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9092                            }
9093                         }
9094                      }
9095                   }
9096                }
9097                else if(type2)
9098                {
9099                   // Maybe this was meant to be an enum...
9100                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9101                   {
9102                      Type oldType = exp.op.exp1.expType;
9103                      exp.op.exp1.expType = null;
9104                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9105                         FreeType(oldType);
9106                      else
9107                         exp.op.exp1.expType = oldType;
9108                   }
9109
9110                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9111                   exp.op.exp1.destType = type2;
9112                   type2.refCount++;
9113                   /*
9114                   // TESTING THIS HERE... LATEST ADDITION
9115                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9116                   {
9117                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9118                      exp.op.exp1.destType = type1._class.registered.dataType;
9119                      if(type1._class.registered.dataType)
9120                         type1._class.registered.dataType.refCount++;
9121                   }
9122
9123                   // TESTING THIS HERE... LATEST ADDITION
9124                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9125                   {
9126                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9127                      exp.op.exp2.destType = type2._class.registered.dataType;
9128                      if(type2._class.registered.dataType)
9129                         type2._class.registered.dataType.refCount++;
9130                   }
9131                   */
9132
9133                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9134                   {
9135                      if(exp.expType) FreeType(exp.expType);
9136                      exp.expType = exp.op.exp1.destType;
9137                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9138                   }
9139                }
9140             }
9141             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9142             {
9143                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9144                {
9145                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9146                   // Convert e.g. / 4 into / 4.0
9147                   exp.op.exp1.destType = type2._class.registered.dataType;
9148                   if(type2._class.registered.dataType)
9149                      type2._class.registered.dataType.refCount++;
9150                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9151                }
9152                if(exp.op.op == '!')
9153                {
9154                   exp.expType = MkClassType("bool");
9155                   exp.expType.truth = true;
9156                }
9157                else
9158                {
9159                   exp.expType = type2;
9160                   if(type2) type2.refCount++;
9161                }
9162             }
9163             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9164             {
9165                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9166                {
9167                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9168                   // Convert e.g. / 4 into / 4.0
9169                   exp.op.exp2.destType = type1._class.registered.dataType;
9170                   if(type1._class.registered.dataType)
9171                      type1._class.registered.dataType.refCount++;
9172                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9173                }
9174                exp.expType = type1;
9175                if(type1) type1.refCount++;
9176             }
9177          }
9178
9179          yylloc = exp.loc;
9180          if(exp.op.exp1 && !exp.op.exp1.expType)
9181          {
9182             char expString[10000];
9183             expString[0] = '\0';
9184             if(inCompiler)
9185             {
9186                PrintExpression(exp.op.exp1, expString);
9187                ChangeCh(expString, '\n', ' ');
9188             }
9189             if(expString[0])
9190                Compiler_Error($"couldn't determine type of %s\n", expString);
9191          }
9192          if(exp.op.exp2 && !exp.op.exp2.expType)
9193          {
9194             char expString[10240];
9195             expString[0] = '\0';
9196             if(inCompiler)
9197             {
9198                PrintExpression(exp.op.exp2, expString);
9199                ChangeCh(expString, '\n', ' ');
9200             }
9201             if(expString[0])
9202                Compiler_Error($"couldn't determine type of %s\n", expString);
9203          }
9204
9205          if(boolResult)
9206          {
9207             FreeType(exp.expType);
9208             exp.expType = MkClassType("bool");
9209             exp.expType.truth = true;
9210          }
9211
9212          if(exp.op.op != SIZEOF)
9213             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9214                (!exp.op.exp2 || exp.op.exp2.isConstant);
9215
9216          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9217          {
9218             DeclareType(curExternal, exp.op.exp2.expType, true, false);
9219          }
9220
9221          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9222             Compiler_Warning($"deleting const qualified object\n");
9223
9224          yylloc = oldyylloc;
9225
9226          FreeType(dummy);
9227          if(type2)
9228             FreeType(type2);
9229          break;
9230       }
9231       case bracketsExp:
9232       case extensionExpressionExp:
9233       {
9234          Expression e;
9235          exp.isConstant = true;
9236          for(e = exp.list->first; e; e = e.next)
9237          {
9238             //bool inced = false;
9239             if(!e.next)
9240             {
9241                FreeType(e.destType);
9242                e.opDestType = exp.opDestType;
9243                e.destType = exp.destType;
9244                if(e.destType) { exp.destType.refCount++; /*e.destType.count++; inced = true;*/ }
9245             }
9246             ProcessExpressionType(e);
9247             /*if(inced)
9248                exp.destType.count--;*/
9249             if(!exp.expType && !e.next)
9250             {
9251                exp.expType = e.expType;
9252                if(e.expType) e.expType.refCount++;
9253                exp.needCast = e.needCast;
9254             }
9255             if(!e.isConstant)
9256                exp.isConstant = false;
9257          }
9258
9259          // In case a cast became a member...
9260          e = exp.list->first;
9261          if(!e.next && e.type == memberExp)
9262          {
9263             // Preserve prev, next
9264             Expression next = exp.next, prev = exp.prev;
9265
9266
9267             FreeType(exp.expType);
9268             FreeType(exp.destType);
9269             delete exp.list;
9270
9271             *exp = *e;
9272
9273             exp.prev = prev;
9274             exp.next = next;
9275
9276             delete e;
9277
9278             ProcessExpressionType(exp);
9279          }
9280          break;
9281       }
9282       case indexExp:
9283       {
9284          Expression e;
9285          exp.isConstant = true;
9286
9287          ProcessExpressionType(exp.index.exp);
9288          if(!exp.index.exp.isConstant)
9289             exp.isConstant = false;
9290
9291          if(exp.index.exp.expType)
9292          {
9293             Type source = exp.index.exp.expType;
9294             if(source.kind == classType && source._class && source._class.registered)
9295             {
9296                Class _class = source._class.registered;
9297                Class c = _class.templateClass ? _class.templateClass : _class;
9298                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9299                {
9300                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9301
9302                   if(exp.index.index && exp.index.index->last)
9303                   {
9304                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9305
9306                      if(type.kind == classType) type.constant = true;
9307                      else if(type.kind == pointerType)
9308                      {
9309                         Type t = type;
9310                         while(t.kind == pointerType) t = t.type;
9311                         t.constant = true;
9312                      }
9313
9314                      ((Expression)exp.index.index->last).destType = type;
9315                   }
9316                }
9317             }
9318          }
9319
9320          for(e = exp.index.index->first; e; e = e.next)
9321          {
9322             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9323             {
9324                if(e.destType) FreeType(e.destType);
9325                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9326             }
9327             ProcessExpressionType(e);
9328             if(!e.next)
9329             {
9330                // Check if this type is int
9331             }
9332             if(!e.isConstant)
9333                exp.isConstant = false;
9334          }
9335
9336          if(!exp.expType)
9337             exp.expType = Dereference(exp.index.exp.expType);
9338          if(exp.expType)
9339             DeclareType(curExternal, exp.expType, true, false);
9340          break;
9341       }
9342       case callExp:
9343       {
9344          Expression e;
9345          Type functionType;
9346          Type methodType = null;
9347          char name[1024];
9348          name[0] = '\0';
9349
9350          if(inCompiler)
9351          {
9352             PrintExpression(exp.call.exp,  name);
9353             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9354             {
9355                //exp.call.exp.expType = null;
9356                PrintExpression(exp.call.exp,  name);
9357             }
9358          }
9359          if(exp.call.exp.type == identifierExp)
9360          {
9361             Expression idExp = exp.call.exp;
9362             Identifier id = idExp.identifier;
9363             if(!strcmp(id.string, "__builtin_frame_address"))
9364             {
9365                exp.expType = ProcessTypeString("void *", true);
9366                if(exp.call.arguments && exp.call.arguments->first)
9367                   ProcessExpressionType(exp.call.arguments->first);
9368                break;
9369             }
9370             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9371             {
9372                exp.expType = ProcessTypeString("int", true);
9373                if(exp.call.arguments && exp.call.arguments->first)
9374                   ProcessExpressionType(exp.call.arguments->first);
9375                break;
9376             }
9377             else if(!strcmp(id.string, "Max") ||
9378                !strcmp(id.string, "Min") ||
9379                !strcmp(id.string, "Sgn") ||
9380                !strcmp(id.string, "Abs"))
9381             {
9382                Expression a = null;
9383                Expression b = null;
9384                Expression tempExp1 = null, tempExp2 = null;
9385                if((!strcmp(id.string, "Max") ||
9386                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9387                {
9388                   a = exp.call.arguments->first;
9389                   b = exp.call.arguments->last;
9390                   tempExp1 = a;
9391                   tempExp2 = b;
9392                }
9393                else if(exp.call.arguments->count == 1)
9394                {
9395                   a = exp.call.arguments->first;
9396                   tempExp1 = a;
9397                }
9398
9399                if(a)
9400                {
9401                   exp.call.arguments->Clear();
9402                   idExp.identifier = null;
9403
9404                   FreeExpContents(exp);
9405
9406                   ProcessExpressionType(a);
9407                   if(b)
9408                      ProcessExpressionType(b);
9409
9410                   exp.type = bracketsExp;
9411                   exp.list = MkList();
9412
9413                   if(a.expType && (!b || b.expType))
9414                   {
9415                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9416                      {
9417                         // Use the simpleStruct name/ids for now...
9418                         if(inCompiler)
9419                         {
9420                            OldList * specs = MkList();
9421                            OldList * decls = MkList();
9422                            Declaration decl;
9423                            char temp1[1024], temp2[1024];
9424
9425                            GetTypeSpecs(a.expType, specs);
9426
9427                            if(a && !a.isConstant && a.type != identifierExp)
9428                            {
9429                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9430                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9431                               tempExp1 = QMkExpId(temp1);
9432                               tempExp1.expType = a.expType;
9433                               if(a.expType)
9434                                  a.expType.refCount++;
9435                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9436                            }
9437                            if(b && !b.isConstant && b.type != identifierExp)
9438                            {
9439                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9440                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9441                               tempExp2 = QMkExpId(temp2);
9442                               tempExp2.expType = b.expType;
9443                               if(b.expType)
9444                                  b.expType.refCount++;
9445                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9446                            }
9447
9448                            decl = MkDeclaration(specs, decls);
9449                            if(!curCompound.compound.declarations)
9450                               curCompound.compound.declarations = MkList();
9451                            curCompound.compound.declarations->Insert(null, decl);
9452                         }
9453                      }
9454                   }
9455
9456                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9457                   {
9458                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9459                      ListAdd(exp.list,
9460                         MkExpCondition(MkExpBrackets(MkListOne(
9461                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9462                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9463                      exp.expType = a.expType;
9464                      if(a.expType)
9465                         a.expType.refCount++;
9466                   }
9467                   else if(!strcmp(id.string, "Abs"))
9468                   {
9469                      ListAdd(exp.list,
9470                         MkExpCondition(MkExpBrackets(MkListOne(
9471                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9472                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9473                      exp.expType = a.expType;
9474                      if(a.expType)
9475                         a.expType.refCount++;
9476                   }
9477                   else if(!strcmp(id.string, "Sgn"))
9478                   {
9479                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9480                      ListAdd(exp.list,
9481                         MkExpCondition(MkExpBrackets(MkListOne(
9482                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9483                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9484                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9485                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9486                      exp.expType = ProcessTypeString("int", false);
9487                   }
9488
9489                   FreeExpression(tempExp1);
9490                   if(tempExp2) FreeExpression(tempExp2);
9491
9492                   FreeIdentifier(id);
9493                   break;
9494                }
9495             }
9496          }
9497
9498          {
9499             Type dummy
9500             {
9501                count = 1;
9502                refCount = 1;
9503             };
9504             if(!exp.call.exp.destType)
9505             {
9506                exp.call.exp.destType = dummy;
9507                dummy.refCount++;
9508             }
9509             ProcessExpressionType(exp.call.exp);
9510             if(exp.call.exp.destType == dummy)
9511             {
9512                FreeType(dummy);
9513                exp.call.exp.destType = null;
9514             }
9515             FreeType(dummy);
9516          }
9517
9518          // Check argument types against parameter types
9519          functionType = exp.call.exp.expType;
9520
9521          if(functionType && functionType.kind == TypeKind::methodType)
9522          {
9523             methodType = functionType;
9524             functionType = methodType.method.dataType;
9525
9526             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9527             // TOCHECK: Instead of doing this here could this be done per param?
9528             if(exp.call.exp.expType.usedClass)
9529             {
9530                char typeString[1024];
9531                typeString[0] = '\0';
9532                {
9533                   Symbol back = functionType.thisClass;
9534                   // Do not output class specifier here (thisclass was added to this)
9535                   functionType.thisClass = null;
9536                   PrintType(functionType, typeString, true, true);
9537                   functionType.thisClass = back;
9538                }
9539                if(strstr(typeString, "thisclass"))
9540                {
9541                   OldList * specs = MkList();
9542                   Declarator decl;
9543                   {
9544                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9545
9546                      decl = SpecDeclFromString(typeString, specs, null);
9547
9548                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9549                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9550                         exp.call.exp.expType.usedClass))
9551                         thisClassParams = false;
9552
9553                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9554                      {
9555                         Class backupThisClass = thisClass;
9556                         thisClass = exp.call.exp.expType.usedClass;
9557                         ProcessDeclarator(decl, true);
9558                         thisClass = backupThisClass;
9559                      }
9560
9561                      thisClassParams = true;
9562
9563                      functionType = ProcessType(specs, decl);
9564                      functionType.refCount = 0;
9565                      FinishTemplatesContext(context);
9566
9567                      // Mark parameters that were 'thisclass'
9568                      {
9569                         Type p, op;
9570                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9571                         {
9572                            //p.wasThisClass = op.kind == thisClassType;
9573                            if(op.kind == thisClassType)
9574                               p.thisClassFrom = methodType.method._class;
9575                         }
9576                      }
9577                      if(methodType.method.dataType.returnType.kind == thisClassType)
9578                      {
9579                         // functionType.returnType.wasThisClass = true;
9580                         functionType.returnType.thisClassFrom = methodType.method._class;
9581                      }
9582                   }
9583
9584                   FreeList(specs, FreeSpecifier);
9585                   FreeDeclarator(decl);
9586                 }
9587             }
9588          }
9589          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9590          {
9591             Type type = functionType.type;
9592             if(!functionType.refCount)
9593             {
9594                functionType.type = null;
9595                FreeType(functionType);
9596             }
9597             //methodType = functionType;
9598             functionType = type;
9599          }
9600          if(functionType && functionType.kind != TypeKind::functionType)
9601          {
9602             Compiler_Error($"called object %s is not a function\n", name);
9603          }
9604          else if(functionType)
9605          {
9606             bool emptyParams = false, noParams = false;
9607             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9608             Type type = functionType.params.first;
9609             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9610             int extra = 0;
9611             Location oldyylloc = yylloc;
9612
9613             if(!type) emptyParams = true;
9614
9615             // WORKING ON THIS:
9616             if(functionType.extraParam && e && functionType.thisClass)
9617             {
9618                e.destType = MkClassType(functionType.thisClass.string);
9619                e = e.next;
9620             }
9621
9622             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9623             // Fixed #141 by adding '&& !functionType.extraParam'
9624             if(!functionType.staticMethod && !functionType.extraParam)
9625             {
9626                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9627                   memberExp.member.exp.expType._class)
9628                {
9629                   type = MkClassType(memberExp.member.exp.expType._class.string);
9630                   if(e)
9631                   {
9632                      e.destType = type;
9633                      e = e.next;
9634                      type = functionType.params.first;
9635                   }
9636                   else
9637                      type.refCount = 0;
9638                }
9639                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9640                {
9641                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9642                   type.byReference = functionType.byReference;
9643                   type.typedByReference = functionType.typedByReference;
9644                   if(e)
9645                   {
9646                      // Allow manually passing a class for typed object
9647                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9648                         e = e.next;
9649                      e.destType = type;
9650                      e = e.next;
9651                      type = functionType.params.first;
9652                   }
9653                   else
9654                      type.refCount = 0;
9655                   //extra = 1;
9656                }
9657             }
9658
9659             if(type && type.kind == voidType)
9660             {
9661                noParams = true;
9662                if(!type.refCount) FreeType(type);
9663                type = null;
9664             }
9665
9666             for( ; e; e = e.next)
9667             {
9668                if(!type && !emptyParams)
9669                {
9670                   yylloc = e.loc;
9671                   if(methodType && methodType.methodClass)
9672                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9673                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9674                         noParams ? 0 : functionType.params.count);
9675                   else
9676                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9677                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9678                         noParams ? 0 : functionType.params.count);
9679                   break;
9680                }
9681
9682                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9683                {
9684                   Type templatedType = null;
9685                   Class _class = methodType.usedClass;
9686                   ClassTemplateParameter curParam = null;
9687                   int id = 0;
9688                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9689                   {
9690                      Class sClass;
9691                      for(sClass = _class; sClass; sClass = sClass.base)
9692                      {
9693                         if(sClass.templateClass) sClass = sClass.templateClass;
9694                         id = 0;
9695                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9696                         {
9697                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9698                            {
9699                               Class nextClass;
9700                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9701                               {
9702                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9703                                  id += nextClass.templateParams.count;
9704                               }
9705                               break;
9706                            }
9707                            id++;
9708                         }
9709                         if(curParam) break;
9710                      }
9711                   }
9712                   if(curParam && _class.templateArgs[id].dataTypeString)
9713                   {
9714                      bool constant = type.constant;
9715                      ClassTemplateArgument arg = _class.templateArgs[id];
9716                      {
9717                         Context context = SetupTemplatesContext(_class);
9718
9719                         /*if(!arg.dataType)
9720                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9721                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9722                         FinishTemplatesContext(context);
9723                      }
9724
9725                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9726                      else if(templatedType.kind == pointerType)
9727                      {
9728                         Type t = templatedType.type;
9729                         while(t.kind == pointerType) t = t.type;
9730                         if(constant) t.constant = constant;
9731                      }
9732
9733                      e.destType = templatedType;
9734                      if(templatedType)
9735                      {
9736                         templatedType.passAsTemplate = true;
9737                         // templatedType.refCount++;
9738                      }
9739                   }
9740                   else
9741                   {
9742                      e.destType = type;
9743                      if(type) type.refCount++;
9744                   }
9745                }
9746                else
9747                {
9748                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9749                   {
9750                      e.destType = type.prev;
9751                      e.destType.refCount++;
9752                   }
9753                   else
9754                   {
9755                      e.destType = type;
9756                      if(type) type.refCount++;
9757                   }
9758                }
9759                // Don't reach the end for the ellipsis
9760                if(type && type.kind != ellipsisType)
9761                {
9762                   Type next = type.next;
9763                   if(!type.refCount) FreeType(type);
9764                   type = next;
9765                }
9766             }
9767
9768             if(type && type.kind != ellipsisType)
9769             {
9770                if(methodType && methodType.methodClass)
9771                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9772                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9773                      functionType.params.count + extra);
9774                else
9775                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9776                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9777                      functionType.params.count + extra);
9778             }
9779             yylloc = oldyylloc;
9780             if(type && !type.refCount) FreeType(type);
9781          }
9782          else
9783          {
9784             functionType = Type
9785             {
9786                refCount = 0;
9787                kind = TypeKind::functionType;
9788             };
9789
9790             if(exp.call.exp.type == identifierExp)
9791             {
9792                char * string = exp.call.exp.identifier.string;
9793                if(inCompiler)
9794                {
9795                   Symbol symbol;
9796                   Location oldyylloc = yylloc;
9797
9798                   yylloc = exp.call.exp.identifier.loc;
9799                   if(strstr(string, "__builtin_") == string)
9800                   {
9801                      if(exp.destType)
9802                      {
9803                         functionType.returnType = exp.destType;
9804                         exp.destType.refCount++;
9805                      }
9806                   }
9807                   else
9808                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9809                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9810                   globalContext.symbols.Add((BTNode)symbol);
9811                   if(strstr(symbol.string, "::"))
9812                      globalContext.hasNameSpace = true;
9813
9814                   yylloc = oldyylloc;
9815                }
9816             }
9817             else if(exp.call.exp.type == memberExp)
9818             {
9819                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9820                   exp.call.exp.member.member.string);*/
9821             }
9822             else
9823                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9824
9825             if(!functionType.returnType)
9826             {
9827                functionType.returnType = Type
9828                {
9829                   refCount = 1;
9830                   kind = intType;
9831                };
9832             }
9833          }
9834          if(functionType && functionType.kind == TypeKind::functionType)
9835          {
9836             exp.expType = functionType.returnType;
9837
9838             if(functionType.returnType)
9839                functionType.returnType.refCount++;
9840
9841             if(!functionType.refCount)
9842                FreeType(functionType);
9843          }
9844
9845          if(exp.call.arguments)
9846          {
9847             for(e = exp.call.arguments->first; e; e = e.next)
9848                ProcessExpressionType(e);
9849          }
9850          break;
9851       }
9852       case memberExp:
9853       {
9854          Type type;
9855          Location oldyylloc = yylloc;
9856          bool thisPtr;
9857          Expression checkExp = exp.member.exp;
9858          while(checkExp)
9859          {
9860             if(checkExp.type == castExp)
9861                checkExp = checkExp.cast.exp;
9862             else if(checkExp.type == bracketsExp)
9863                checkExp = checkExp.list ? checkExp.list->first : null;
9864             else
9865                break;
9866          }
9867
9868          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9869          exp.thisPtr = thisPtr;
9870
9871          // DOING THIS LATER NOW...
9872          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9873          {
9874             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9875             /* TODO: Name Space Fix ups
9876             if(!exp.member.member.classSym)
9877                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9878             */
9879          }
9880
9881          ProcessExpressionType(exp.member.exp);
9882          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9883             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9884          {
9885             exp.isConstant = false;
9886          }
9887          else
9888             exp.isConstant = exp.member.exp.isConstant;
9889          type = exp.member.exp.expType;
9890
9891          yylloc = exp.loc;
9892
9893          if(type && (type.kind == templateType))
9894          {
9895             Class _class = thisClass ? thisClass : currentClass;
9896             ClassTemplateParameter param = null;
9897             if(_class)
9898             {
9899                for(param = _class.templateParams.first; param; param = param.next)
9900                {
9901                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9902                      break;
9903                }
9904             }
9905             if(param && param.defaultArg.member)
9906             {
9907                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9908                if(argExp)
9909                {
9910                   Expression expMember = exp.member.exp;
9911                   Declarator decl;
9912                   OldList * specs = MkList();
9913                   char thisClassTypeString[1024];
9914
9915                   FreeIdentifier(exp.member.member);
9916
9917                   ProcessExpressionType(argExp);
9918
9919                   {
9920                      char * colon = strstr(param.defaultArg.memberString, "::");
9921                      if(colon)
9922                      {
9923                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9924                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9925                      }
9926                      else
9927                         strcpy(thisClassTypeString, _class.fullName);
9928                   }
9929
9930                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9931
9932                   exp.expType = ProcessType(specs, decl);
9933                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9934                   {
9935                      Class expClass = exp.expType._class.registered;
9936                      Class cClass = null;
9937                      int paramCount = 0;
9938                      int lastParam = -1;
9939
9940                      char templateString[1024];
9941                      ClassTemplateParameter param;
9942                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9943                      for(cClass = expClass; cClass; cClass = cClass.base)
9944                      {
9945                         int p = 0;
9946                         for(param = cClass.templateParams.first; param; param = param.next)
9947                         {
9948                            int id = p;
9949                            Class sClass;
9950                            ClassTemplateArgument arg;
9951                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9952                            arg = expClass.templateArgs[id];
9953
9954                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9955                            {
9956                               ClassTemplateParameter cParam;
9957                               //int p = numParams - sClass.templateParams.count;
9958                               int p = 0;
9959                               Class nextClass;
9960                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9961
9962                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9963                               {
9964                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9965                                  {
9966                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9967                                     {
9968                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9969                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9970                                        break;
9971                                     }
9972                                  }
9973                               }
9974                            }
9975
9976                            {
9977                               char argument[256];
9978                               argument[0] = '\0';
9979                               /*if(arg.name)
9980                               {
9981                                  strcat(argument, arg.name.string);
9982                                  strcat(argument, " = ");
9983                               }*/
9984                               switch(param.type)
9985                               {
9986                                  case expression:
9987                                  {
9988                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9989                                     char expString[1024];
9990                                     OldList * specs = MkList();
9991                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9992                                     Expression exp;
9993                                     char * string = PrintHexUInt64(arg.expression.ui64);
9994                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9995                                     delete string;
9996
9997                                     ProcessExpressionType(exp);
9998                                     ComputeExpression(exp);
9999                                     expString[0] = '\0';
10000                                     PrintExpression(exp, expString);
10001                                     strcat(argument, expString);
10002                                     // delete exp;
10003                                     FreeExpression(exp);
10004                                     break;
10005                                  }
10006                                  case identifier:
10007                                  {
10008                                     strcat(argument, arg.member.name);
10009                                     break;
10010                                  }
10011                                  case TemplateParameterType::type:
10012                                  {
10013                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10014                                     {
10015                                        if(!strcmp(arg.dataTypeString, "thisclass"))
10016                                           strcat(argument, thisClassTypeString);
10017                                        else
10018                                           strcat(argument, arg.dataTypeString);
10019                                     }
10020                                     break;
10021                                  }
10022                               }
10023                               if(argument[0])
10024                               {
10025                                  if(paramCount) strcat(templateString, ", ");
10026                                  if(lastParam != p - 1)
10027                                  {
10028                                     strcat(templateString, param.name);
10029                                     strcat(templateString, " = ");
10030                                  }
10031                                  strcat(templateString, argument);
10032                                  paramCount++;
10033                                  lastParam = p;
10034                               }
10035                               p++;
10036                            }
10037                         }
10038                      }
10039                      {
10040                         int len = strlen(templateString);
10041                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10042                         templateString[len++] = '>';
10043                         templateString[len++] = '\0';
10044                      }
10045                      {
10046                         Context context = SetupTemplatesContext(_class);
10047                         FreeType(exp.expType);
10048                         exp.expType = ProcessTypeString(templateString, false);
10049                         FinishTemplatesContext(context);
10050                      }
10051                   }
10052
10053                   if(!expMember.expType.isPointerType)
10054                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10055                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10056                   exp.type = bracketsExp;
10057                   exp.list = MkListOne(MkExpOp(null, '*',
10058                   /*opExp;
10059                   exp.op.op = '*';
10060                   exp.op.exp1 = null;
10061                   exp.op.exp2 = */
10062                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10063                      MkExpBrackets(MkListOne(
10064                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10065                            expMember))),
10066                               '+',
10067                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10068                               '+',
10069                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10070
10071                            ));
10072                }
10073             }
10074             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10075                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10076             {
10077                type = ProcessTemplateParameterType(type.templateParameter);
10078             }
10079          }
10080          // TODO: *** This seems to be where we should add method support for all basic types ***
10081          if(type && (type.kind == templateType));
10082          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10083                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10084                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10085                           (type.kind == pointerType && type.type.kind == charType)))
10086          {
10087             Identifier id = exp.member.member;
10088             TypeKind typeKind = type.kind;
10089             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10090             if(typeKind == subClassType && exp.member.exp.type == classExp)
10091             {
10092                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10093                typeKind = classType;
10094             }
10095
10096             if(id)
10097             {
10098                if(typeKind == intType || typeKind == enumType)
10099                   _class = eSystem_FindClass(privateModule, "int");
10100                else if(!_class)
10101                {
10102                   if(type.kind == classType && type._class && type._class.registered)
10103                   {
10104                      _class = type._class.registered;
10105                   }
10106                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10107                   {
10108                      _class = FindClass("char *").registered;
10109                   }
10110                   else if(type.kind == pointerType)
10111                   {
10112                      _class = eSystem_FindClass(privateModule, "uintptr");
10113                      FreeType(exp.expType);
10114                      exp.expType = ProcessTypeString("uintptr", false);
10115                      exp.byReference = true;
10116                   }
10117                   else
10118                   {
10119                      char string[1024] = "";
10120                      Symbol classSym;
10121                      PrintTypeNoConst(type, string, false, true);
10122                      classSym = FindClass(string);
10123                      if(classSym) _class = classSym.registered;
10124                   }
10125                }
10126             }
10127
10128             if(_class && id)
10129             {
10130                /*bool thisPtr =
10131                   (exp.member.exp.type == identifierExp &&
10132                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10133                Property prop = null;
10134                Method method = null;
10135                DataMember member = null;
10136                Property revConvert = null;
10137                ClassProperty classProp = null;
10138
10139                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10140                   exp.member.memberType = propertyMember;
10141
10142                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10143                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10144
10145                if(typeKind != subClassType)
10146                {
10147                   // Prioritize data members over properties for "this"
10148                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10149                   {
10150                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10151                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10152                      {
10153                         prop = eClass_FindProperty(_class, id.string, privateModule);
10154                         if(prop)
10155                            member = null;
10156                      }
10157                      if(!member && !prop)
10158                         prop = eClass_FindProperty(_class, id.string, privateModule);
10159                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10160                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10161                         exp.member.thisPtr = true;
10162                   }
10163                   // Prioritize properties over data members otherwise
10164                   else
10165                   {
10166                      bool useMemberForNonConst = false;
10167                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10168                      if(!id.classSym)
10169                      {
10170                         prop = eClass_FindProperty(_class, id.string, null);
10171
10172                         useMemberForNonConst = prop && exp.destType &&
10173                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10174                               !strncmp(prop.dataTypeString, "const ", 6);
10175
10176                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10177                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10178                      }
10179
10180                      if((!prop || useMemberForNonConst) && !member)
10181                      {
10182                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10183                         if(!method)
10184                         {
10185                            prop = eClass_FindProperty(_class, id.string, privateModule);
10186
10187                            useMemberForNonConst |= prop && exp.destType &&
10188                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10189                                  !strncmp(prop.dataTypeString, "const ", 6);
10190
10191                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10192                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10193                         }
10194                      }
10195
10196                      if(member && prop)
10197                      {
10198                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10199                            prop = null;
10200                         else
10201                            member = null;
10202                      }
10203                   }
10204                }
10205                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10206                   method = eClass_FindMethod(_class, id.string, privateModule);
10207                if(!prop && !member && !method)
10208                {
10209                   if(typeKind == subClassType)
10210                   {
10211                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10212                      if(classProp)
10213                      {
10214                         exp.member.memberType = classPropertyMember;
10215                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10216                      }
10217                      else
10218                      {
10219                         // Assume this is a class_data member
10220                         char structName[1024];
10221                         Identifier id = exp.member.member;
10222                         Expression classExp = exp.member.exp;
10223                         type.refCount++;
10224
10225                         FreeType(classExp.expType);
10226                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10227
10228                         strcpy(structName, "__ecereClassData_");
10229                         FullClassNameCat(structName, type._class.string, false);
10230                         exp.type = pointerExp;
10231                         exp.member.member = id;
10232
10233                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10234                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10235                               MkExpBrackets(MkListOne(MkExpOp(
10236                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10237                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10238                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10239                                  )));
10240
10241                         FreeType(type);
10242
10243                         ProcessExpressionType(exp);
10244                         return;
10245                      }
10246                   }
10247                   else
10248                   {
10249                      // Check for reverse conversion
10250                      // (Convert in an instantiation later, so that we can use
10251                      //  deep properties system)
10252                      Symbol classSym = FindClass(id.string);
10253                      if(classSym)
10254                      {
10255                         Class convertClass = classSym.registered;
10256                         if(convertClass)
10257                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10258                      }
10259                   }
10260                }
10261
10262                //if(!exp.member.exp.destType)
10263                if(exp.member.exp.destType)
10264                   FreeType(exp.member.exp.destType);
10265                {
10266                   if(method && !method._class.symbol)
10267                      method._class.symbol = FindClass(method._class.fullName);
10268                   if(prop && !prop._class.symbol)
10269                      prop._class.symbol = FindClass(prop._class.fullName);
10270
10271                   exp.member.exp.destType = Type
10272                   {
10273                      refCount = 1;
10274                      kind = classType;
10275                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10276                      // wasThisClass = type ? type.wasThisClass : false;
10277                      thisClassFrom = type ? type.thisClassFrom : null;
10278                   };
10279                }
10280
10281                if(prop)
10282                {
10283                   exp.member.memberType = propertyMember;
10284                   if(!prop.dataType)
10285                      ProcessPropertyType(prop);
10286                   exp.expType = prop.dataType;
10287                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10288                   {
10289                      Type type { };
10290                      CopyTypeInto(type, exp.expType);
10291                      type.refCount = 1;
10292                      type.constant = true;
10293                      exp.expType = type;
10294                   }
10295                   else if(prop.dataType)
10296                      prop.dataType.refCount++;
10297                }
10298                else if(member)
10299                {
10300                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10301                   {
10302                      FreeExpContents(exp);
10303                      exp.type = identifierExp;
10304                      exp.identifier = MkIdentifier("class");
10305                      ProcessExpressionType(exp);
10306                      return;
10307                   }
10308
10309                   exp.member.memberType = dataMember;
10310                   DeclareStruct(curExternal, _class.fullName, false, true);
10311                   if(member._class != _class)
10312                      DeclareStruct(curExternal, member._class.fullName, false, true);
10313
10314                   if(!member.dataType)
10315                   {
10316                      Context context = SetupTemplatesContext(_class);
10317                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10318                      FinishTemplatesContext(context);
10319                   }
10320                   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)
10321                      member.dataType.bitMemberSize = ((BitMember)member).size;
10322                   exp.expType = member.dataType;
10323                   if(member.dataType) member.dataType.refCount++;
10324                }
10325                else if(revConvert)
10326                {
10327                   exp.member.memberType = reverseConversionMember;
10328                   exp.expType = MkClassType(revConvert._class.fullName);
10329                }
10330                else if(method)
10331                {
10332                   //if(inCompiler)
10333                   {
10334                      /*if(id._class)
10335                      {
10336                         exp.type = identifierExp;
10337                         exp.identifier = exp.member.member;
10338                      }
10339                      else*/
10340                         exp.member.memberType = methodMember;
10341                   }
10342                   if(!method.dataType)
10343                      ProcessMethodType(method);
10344                   exp.expType = Type
10345                   {
10346                      refCount = 1;
10347                      kind = methodType;
10348                      method = method;
10349                   };
10350
10351                   // Tricky spot here... To use instance versus class virtual table
10352                   // Put it back to what it was... What did we break?
10353
10354                   // Had to put it back for overriding Main of Thread global instance
10355
10356                   //exp.expType.methodClass = _class;
10357                   exp.expType.methodClass = (id && id._class) ? _class : null;
10358
10359                   // Need the actual class used for templated classes
10360                   exp.expType.usedClass = _class;
10361                }
10362                else if(!classProp)
10363                {
10364                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10365                   {
10366                      FreeExpContents(exp);
10367                      exp.type = identifierExp;
10368                      exp.identifier = MkIdentifier("class");
10369                      FreeType(exp.expType);
10370                      exp.expType = MkClassType("ecere::com::Class");
10371                      return;
10372                   }
10373                   yylloc = exp.member.member.loc;
10374                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10375                   if(inCompiler)
10376                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10377                }
10378
10379                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10380                {
10381                   Class tClass;
10382
10383                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10384                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10385
10386                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10387                   {
10388                      int id = 0;
10389                      ClassTemplateParameter curParam = null;
10390                      Class sClass;
10391
10392                      for(sClass = tClass; sClass; sClass = sClass.base)
10393                      {
10394                         id = 0;
10395                         if(sClass.templateClass) sClass = sClass.templateClass;
10396                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10397                         {
10398                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10399                            {
10400                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10401                                  id += sClass.templateParams.count;
10402                               break;
10403                            }
10404                            id++;
10405                         }
10406                         if(curParam) break;
10407                      }
10408
10409                      if(curParam && tClass.templateArgs[id].dataTypeString)
10410                      {
10411                         ClassTemplateArgument arg = tClass.templateArgs[id];
10412                         Context context = SetupTemplatesContext(tClass);
10413                         bool constant = exp.expType.constant;
10414                         bool passAsTemplate = false;
10415                         Class thisClassFrom = null;
10416                         Type t = ProcessTypeString(exp.expType.templateParameter.dataTypeString, false);
10417                         if(t && t.kind == classType && t._class)
10418                            thisClassFrom = t._class.registered;
10419                         else
10420                            // Mark that 'thisClassFrom' was set to something
10421                            thisClassFrom = eSystem_FindClass(GetPrivateModule(), "class");
10422
10423                         FreeType(t);
10424
10425                         passAsTemplate = tClass.templateClass && (exp.expType.kind != templateType ||
10426                            (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType)));
10427
10428                         /*if(!arg.dataType)
10429                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10430                         FreeType(exp.expType);
10431
10432                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10433                         exp.expType.thisClassFrom = thisClassFrom;
10434                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10435                         else if(exp.expType.kind == pointerType)
10436                         {
10437                            Type t = exp.expType.type;
10438                            while(t.kind == pointerType) t = t.type;
10439                            if(constant) t.constant = constant;
10440                         }
10441                         if(exp.expType)
10442                         {
10443                            if(exp.expType.kind == thisClassType)
10444                            {
10445                               FreeType(exp.expType);
10446                               exp.expType = ReplaceThisClassType(_class);
10447                            }
10448
10449                            if(passAsTemplate)
10450                               exp.expType.passAsTemplate = true;
10451                            //exp.expType.refCount++;
10452                            if(!exp.destType)
10453                            {
10454                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10455                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10456                               else if(exp.destType.kind == pointerType)
10457                               {
10458                                  Type t = exp.destType.type;
10459                                  while(t.kind == pointerType) t = t.type;
10460                                  if(constant) t.constant = constant;
10461                               }
10462
10463                               //exp.destType.refCount++;
10464
10465                               if(exp.destType.kind == thisClassType)
10466                               {
10467                                  FreeType(exp.destType);
10468                                  exp.destType = ReplaceThisClassType(_class);
10469                               }
10470                            }
10471                         }
10472                         FinishTemplatesContext(context);
10473                      }
10474                   }
10475                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10476                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10477                   {
10478                      int id = 0;
10479                      ClassTemplateParameter curParam = null;
10480                      Class sClass;
10481
10482                      for(sClass = tClass; sClass; sClass = sClass.base)
10483                      {
10484                         id = 0;
10485                         if(sClass.templateClass) sClass = sClass.templateClass;
10486                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10487                         {
10488                            if(curParam.type == TemplateParameterType::type &&
10489                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10490                            {
10491                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10492                                  id += sClass.templateParams.count;
10493                               break;
10494                            }
10495                            id++;
10496                         }
10497                         if(curParam) break;
10498                      }
10499
10500                      if(curParam)
10501                      {
10502                         ClassTemplateArgument arg = tClass.templateArgs[id];
10503                         Context context = SetupTemplatesContext(tClass);
10504                         Type basicType;
10505                         /*if(!arg.dataType)
10506                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10507
10508                         basicType = ProcessTypeString(arg.dataTypeString, false);
10509                         if(basicType)
10510                         {
10511                            if(basicType.kind == thisClassType)
10512                            {
10513                               FreeType(basicType);
10514                               basicType = ReplaceThisClassType(_class);
10515                            }
10516
10517                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10518                            if(tClass.templateClass)
10519                               basicType.passAsTemplate = true;
10520                            */
10521
10522                            FreeType(exp.expType);
10523
10524                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10525                            //exp.expType.refCount++;
10526                            if(!exp.destType)
10527                            {
10528                               exp.destType = exp.expType;
10529                               exp.destType.refCount++;
10530                            }
10531
10532                            {
10533                               Expression newExp { };
10534                               OldList * specs = MkList();
10535                               Declarator decl;
10536                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10537                               *newExp = *exp;
10538                               if(exp.destType) exp.destType.refCount++;
10539                               if(exp.expType)  exp.expType.refCount++;
10540                               exp.type = castExp;
10541                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10542                               exp.cast.exp = newExp;
10543                               //FreeType(exp.expType);
10544                               //exp.expType = null;
10545                               //ProcessExpressionType(sourceExp);
10546                            }
10547                         }
10548                         FinishTemplatesContext(context);
10549                      }
10550                   }
10551                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10552                   {
10553                      Class expClass = exp.expType._class.registered;
10554                      if(expClass)
10555                      {
10556                         Class cClass = null;
10557                         int p = 0;
10558                         int paramCount = 0;
10559                         int lastParam = -1;
10560                         char templateString[1024];
10561                         ClassTemplateParameter param;
10562                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10563                         while(cClass != expClass)
10564                         {
10565                            Class sClass;
10566                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10567                            cClass = sClass;
10568
10569                            for(param = cClass.templateParams.first; param; param = param.next)
10570                            {
10571                               Class cClassCur = null;
10572                               int cp = 0;
10573                               ClassTemplateParameter paramCur = null;
10574                               ClassTemplateArgument arg;
10575                               while(cClassCur != tClass && !paramCur)
10576                               {
10577                                  Class sClassCur;
10578                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10579                                  cClassCur = sClassCur;
10580
10581                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10582                                  {
10583                                     if(!strcmp(paramCur.name, param.name))
10584                                     {
10585
10586                                        break;
10587                                     }
10588                                     cp++;
10589                                  }
10590                               }
10591                               if(paramCur && paramCur.type == TemplateParameterType::type)
10592                                  arg = tClass.templateArgs[cp];
10593                               else
10594                                  arg = expClass.templateArgs[p];
10595
10596                               {
10597                                  char argument[256];
10598                                  argument[0] = '\0';
10599                                  /*if(arg.name)
10600                                  {
10601                                     strcat(argument, arg.name.string);
10602                                     strcat(argument, " = ");
10603                                  }*/
10604                                  switch(param.type)
10605                                  {
10606                                     case expression:
10607                                     {
10608                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10609                                        char expString[1024];
10610                                        OldList * specs = MkList();
10611                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10612                                        Expression exp;
10613                                        char * string = PrintHexUInt64(arg.expression.ui64);
10614                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10615                                        delete string;
10616
10617                                        ProcessExpressionType(exp);
10618                                        ComputeExpression(exp);
10619                                        expString[0] = '\0';
10620                                        PrintExpression(exp, expString);
10621                                        strcat(argument, expString);
10622                                        // delete exp;
10623                                        FreeExpression(exp);
10624                                        break;
10625                                     }
10626                                     case identifier:
10627                                     {
10628                                        strcat(argument, arg.member.name);
10629                                        break;
10630                                     }
10631                                     case TemplateParameterType::type:
10632                                     {
10633                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10634                                           strcat(argument, arg.dataTypeString);
10635                                        break;
10636                                     }
10637                                  }
10638                                  if(argument[0])
10639                                  {
10640                                     if(paramCount) strcat(templateString, ", ");
10641                                     if(lastParam != p - 1)
10642                                     {
10643                                        strcat(templateString, param.name);
10644                                        strcat(templateString, " = ");
10645                                     }
10646                                     strcat(templateString, argument);
10647                                     paramCount++;
10648                                     lastParam = p;
10649                                  }
10650                               }
10651                               p++;
10652                            }
10653                         }
10654                         {
10655                            int len = strlen(templateString);
10656                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10657                            templateString[len++] = '>';
10658                            templateString[len++] = '\0';
10659                         }
10660
10661                         FreeType(exp.expType);
10662                         {
10663                            Context context = SetupTemplatesContext(tClass);
10664                            exp.expType = ProcessTypeString(templateString, false);
10665                            FinishTemplatesContext(context);
10666                         }
10667                      }
10668                   }
10669                }
10670             }
10671             else
10672                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10673          }
10674          else if(type && (type.kind == structType || type.kind == unionType))
10675          {
10676             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10677             if(memberType)
10678             {
10679                exp.expType = memberType;
10680                if(memberType)
10681                   memberType.refCount++;
10682             }
10683          }
10684          else
10685          {
10686             char expString[10240];
10687             expString[0] = '\0';
10688             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10689             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10690          }
10691
10692          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10693          {
10694             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10695             {
10696                Identifier id = exp.member.member;
10697                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10698                if(_class)
10699                {
10700                   FreeType(exp.expType);
10701                   exp.expType = ReplaceThisClassType(_class);
10702                }
10703             }
10704          }
10705          yylloc = oldyylloc;
10706          break;
10707       }
10708       // Convert x->y into (*x).y
10709       case pointerExp:
10710       {
10711          Type destType = exp.destType;
10712
10713          // DOING THIS LATER NOW...
10714          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10715          {
10716             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10717             /* TODO: Name Space Fix ups
10718             if(!exp.member.member.classSym)
10719                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10720             */
10721          }
10722
10723          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10724          exp.type = memberExp;
10725          if(destType)
10726             destType.count++;
10727          ProcessExpressionType(exp);
10728          if(destType)
10729             destType.count--;
10730          break;
10731       }
10732       case classSizeExp:
10733       {
10734          //ComputeExpression(exp);
10735
10736          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10737          if(classSym && classSym.registered)
10738          {
10739             if(classSym.registered.type == noHeadClass || (classSym.registered.fixed && classSym.registered.structSize))
10740             {
10741                char name[1024];
10742                Class b = classSym.registered;
10743                name[0] = '\0';
10744                DeclareStruct(curExternal, classSym.string, false, true);
10745                FreeSpecifier(exp._class);
10746                FullClassNameCat(name, classSym.string, false);
10747
10748                if(b.offset == 0)
10749                {
10750                   exp.type = typeSizeExp;
10751                   exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10752                }
10753                else
10754                {
10755                   Expression e;
10756                   exp.type = opExp;
10757                   if(b.structSize == b.offset)
10758                      exp.op.exp1 = MkExpConstant("0");
10759                   else
10760                      exp.op.exp1 = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10761                   exp.op.op = '+';
10762                   e = exp;
10763                   while(b.offset != 0)
10764                   {
10765                      Symbol sym;
10766                      Expression typeSize;
10767
10768                      b = b.base;
10769                      sym = FindClass(b.fullName);
10770
10771                      name[0] = '\0';
10772                      DeclareStruct(curExternal, sym.string, false, true);
10773                      FullClassNameCat(name, sym.string, false);
10774
10775                      if(b.structSize == b.offset)
10776                         typeSize = MkExpConstant("0");
10777                      else
10778                         typeSize = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10779                      e.op.exp2 = b.offset ? MkExpOp(typeSize, '+', null) : typeSize;
10780                      e = e.op.exp2;
10781                   }
10782                }
10783             }
10784             else
10785             {
10786                if(classSym.registered.fixed && !classSym.registered.structSize)
10787                {
10788                   FreeSpecifier(exp._class);
10789                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10790                   exp.type = constantExp;
10791                }
10792                else
10793                {
10794                   char className[1024];
10795                   strcpy(className, "__ecereClass_");
10796                   FullClassNameCat(className, classSym.string, true);
10797
10798                   DeclareClass(curExternal, classSym, className);
10799
10800                   FreeExpContents(exp);
10801                   exp.type = pointerExp;
10802                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10803                   exp.member.member = MkIdentifier("structSize");
10804                }
10805             }
10806          }
10807
10808          exp.expType = Type
10809          {
10810             refCount = 1;
10811             kind = intSizeType;
10812          };
10813          // exp.isConstant = true;
10814          break;
10815       }
10816       case typeSizeExp:
10817       {
10818          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10819
10820          exp.expType = Type
10821          {
10822             refCount = 1;
10823             kind = intSizeType;
10824          };
10825          exp.isConstant = true;
10826
10827          DeclareType(curExternal, type, true, false);
10828          FreeType(type);
10829          break;
10830       }
10831       case castExp:
10832       {
10833          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10834          type.count = 1;
10835          FreeType(exp.cast.exp.destType);
10836          exp.cast.exp.destType = type;
10837          type.refCount++;
10838          type.casted = true;
10839          ProcessExpressionType(exp.cast.exp);
10840          type.casted = false;
10841          type.count = 0;
10842          exp.expType = type;
10843          //type.refCount++;
10844
10845          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10846          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10847          {
10848             void * prev = exp.prev, * next = exp.next;
10849             Type expType = exp.cast.exp.destType;
10850             Expression castExp = exp.cast.exp;
10851             Type destType = exp.destType;
10852
10853             if(expType) expType.refCount++;
10854
10855             //FreeType(exp.destType);
10856             FreeType(exp.expType);
10857             FreeTypeName(exp.cast.typeName);
10858
10859             *exp = *castExp;
10860             FreeType(exp.expType);
10861             FreeType(exp.destType);
10862
10863             exp.expType = expType;
10864             exp.destType = destType;
10865
10866             delete castExp;
10867
10868             exp.prev = prev;
10869             exp.next = next;
10870
10871          }
10872          else
10873          {
10874             exp.isConstant = exp.cast.exp.isConstant;
10875          }
10876          //FreeType(type);
10877          break;
10878       }
10879       case extensionInitializerExp:
10880       {
10881          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10882          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10883          // ProcessInitializer(exp.initializer.initializer, type);
10884          exp.expType = type;
10885          break;
10886       }
10887       case vaArgExp:
10888       {
10889          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10890          ProcessExpressionType(exp.vaArg.exp);
10891          exp.expType = type;
10892          break;
10893       }
10894       case conditionExp:
10895       {
10896          Expression e;
10897          Type t = exp.destType;
10898          if(t && !exp.destType.casted)
10899          {
10900             t = { };
10901             CopyTypeInto(t, exp.destType);
10902             t.count = 0;
10903          }
10904          else if(t)
10905             t.refCount++;
10906
10907          exp.isConstant = true;
10908
10909          FreeType(exp.cond.cond.destType);
10910          exp.cond.cond.destType = MkClassType("bool");
10911          exp.cond.cond.destType.truth = true;
10912          ProcessExpressionType(exp.cond.cond);
10913          if(!exp.cond.cond.isConstant)
10914             exp.isConstant = false;
10915          for(e = exp.cond.exp->first; e; e = e.next)
10916          {
10917             if(!e.next)
10918             {
10919                FreeType(e.destType);
10920                e.destType = t;
10921                if(e.destType) e.destType.refCount++;
10922             }
10923             ProcessExpressionType(e);
10924             if(!e.next)
10925             {
10926                exp.expType = e.expType;
10927                if(e.expType) e.expType.refCount++;
10928             }
10929             if(!e.isConstant)
10930                exp.isConstant = false;
10931          }
10932
10933          FreeType(exp.cond.elseExp.destType);
10934          // Added this check if we failed to find an expType
10935          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10936
10937          // Reversed it...
10938          exp.cond.elseExp.destType = t ? t : exp.expType;
10939
10940          if(exp.cond.elseExp.destType)
10941             exp.cond.elseExp.destType.refCount++;
10942          ProcessExpressionType(exp.cond.elseExp);
10943
10944          // FIXED THIS: Was done before calling process on elseExp
10945          if(!exp.cond.elseExp.isConstant)
10946             exp.isConstant = false;
10947
10948          FreeType(t);
10949          break;
10950       }
10951       case extensionCompoundExp:
10952       {
10953          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10954          {
10955             Statement last = exp.compound.compound.statements->last;
10956             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10957             {
10958                ((Expression)last.expressions->last).destType = exp.destType;
10959                if(exp.destType)
10960                   exp.destType.refCount++;
10961             }
10962             ProcessStatement(exp.compound);
10963             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10964             if(exp.expType)
10965                exp.expType.refCount++;
10966          }
10967          break;
10968       }
10969       case classExp:
10970       {
10971          Specifier spec = exp._classExp.specifiers->first;
10972          if(spec && spec.type == nameSpecifier)
10973          {
10974             exp.expType = MkClassType(spec.name);
10975             exp.expType.kind = subClassType;
10976             exp.byReference = true;
10977          }
10978          else
10979          {
10980             exp.expType = MkClassType("ecere::com::Class");
10981             exp.byReference = true;
10982          }
10983          break;
10984       }
10985       case classDataExp:
10986       {
10987          Class _class = thisClass ? thisClass : currentClass;
10988          if(_class)
10989          {
10990             Identifier id = exp.classData.id;
10991             char structName[1024];
10992             Expression classExp;
10993             strcpy(structName, "__ecereClassData_");
10994             FullClassNameCat(structName, _class.fullName, false);
10995             exp.type = pointerExp;
10996             exp.member.member = id;
10997             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10998                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10999             else
11000                classExp = MkExpIdentifier(MkIdentifier("class"));
11001
11002             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
11003                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
11004                   MkExpBrackets(MkListOne(MkExpOp(
11005                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
11006                         MkExpMember(classExp, MkIdentifier("data"))), '+',
11007                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
11008                      )));
11009
11010             ProcessExpressionType(exp);
11011             return;
11012          }
11013          break;
11014       }
11015       case arrayExp:
11016       {
11017          Type type = null;
11018          const char * typeString = null;
11019          char typeStringBuf[1024];
11020          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
11021             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
11022          {
11023             Class templateClass = exp.destType._class.registered;
11024             typeString = templateClass.templateArgs[2].dataTypeString;
11025          }
11026          else if(exp.list)
11027          {
11028             // Guess type from expressions in the array
11029             Expression e;
11030             for(e = exp.list->first; e; e = e.next)
11031             {
11032                ProcessExpressionType(e);
11033                if(e.expType)
11034                {
11035                   if(!type) { type = e.expType; type.refCount++; }
11036                   else
11037                   {
11038                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11039                      if(!MatchTypeExpression(e, type, null, false, true))
11040                      {
11041                         FreeType(type);
11042                         type = e.expType;
11043                         e.expType = null;
11044
11045                         e = exp.list->first;
11046                         ProcessExpressionType(e);
11047                         if(e.expType)
11048                         {
11049                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
11050                            if(!MatchTypeExpression(e, type, null, false, true))
11051                            {
11052                               FreeType(e.expType);
11053                               e.expType = null;
11054                               FreeType(type);
11055                               type = null;
11056                               break;
11057                            }
11058                         }
11059                      }
11060                   }
11061                   if(e.expType)
11062                   {
11063                      FreeType(e.expType);
11064                      e.expType = null;
11065                   }
11066                }
11067             }
11068             if(type)
11069             {
11070                typeStringBuf[0] = '\0';
11071                PrintTypeNoConst(type, typeStringBuf, false, true);
11072                typeString = typeStringBuf;
11073                FreeType(type);
11074                type = null;
11075             }
11076          }
11077          if(typeString)
11078          {
11079             /*
11080             (Container)& (struct BuiltInContainer)
11081             {
11082                ._vTbl = class(BuiltInContainer)._vTbl,
11083                ._class = class(BuiltInContainer),
11084                .refCount = 0,
11085                .data = (int[]){ 1, 7, 3, 4, 5 },
11086                .count = 5,
11087                .type = class(int),
11088             }
11089             */
11090             char templateString[1024];
11091             OldList * initializers = MkList();
11092             OldList * structInitializers = MkList();
11093             OldList * specs = MkList();
11094             Expression expExt;
11095             Declarator decl = SpecDeclFromString(typeString, specs, null);
11096             sprintf(templateString, "Container<%s>", typeString);
11097
11098             if(exp.list)
11099             {
11100                Expression e;
11101                type = ProcessTypeString(typeString, false);
11102                while((e = exp.list->first))
11103                {
11104                   exp.list->Remove(e);
11105                   e.destType = type;
11106                   type.refCount++;
11107                   ProcessExpressionType(e);
11108                   ListAdd(initializers, MkInitializerAssignment(e));
11109                }
11110                FreeType(type);
11111                delete exp.list;
11112             }
11113
11114             DeclareStruct(curExternal, "ecere::com::BuiltInContainer", false, true);
11115
11116             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11117                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11118             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11119                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11120             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11121                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11122             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11123                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11124                MkInitializerList(initializers))));
11125                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11126             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11127                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11128             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11129                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11130             exp.expType = ProcessTypeString(templateString, false);
11131             exp.type = bracketsExp;
11132             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11133                MkExpOp(null, '&',
11134                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11135                   MkInitializerList(structInitializers)))));
11136             ProcessExpressionType(expExt);
11137          }
11138          else
11139          {
11140             exp.expType = ProcessTypeString("Container", false);
11141             Compiler_Error($"Couldn't determine type of array elements\n");
11142          }
11143          break;
11144       }
11145    }
11146
11147    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11148    {
11149       FreeType(exp.expType);
11150       exp.expType = ReplaceThisClassType(thisClass);
11151    }
11152
11153    // Resolve structures here
11154    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11155    {
11156       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11157       // TODO: Fix members reference...
11158       if(symbol)
11159       {
11160          if(exp.expType.kind != enumType)
11161          {
11162             Type member;
11163             String enumName = CopyString(exp.expType.enumName);
11164
11165             // Fixed a memory leak on self-referencing C structs typedefs
11166             // by instantiating a new type rather than simply copying members
11167             // into exp.expType
11168             FreeType(exp.expType);
11169             exp.expType = Type { };
11170             exp.expType.kind = symbol.type.kind;
11171             exp.expType.refCount++;
11172             exp.expType.enumName = enumName;
11173
11174             exp.expType.members = symbol.type.members;
11175             for(member = symbol.type.members.first; member; member = member.next)
11176                member.refCount++;
11177          }
11178          else
11179          {
11180             NamedLink64 member;
11181             for(member = symbol.type.members.first; member; member = member.next)
11182             {
11183                NamedLink64 value { name = CopyString(member.name) };
11184                exp.expType.members.Add(value);
11185             }
11186          }
11187       }
11188    }
11189
11190    // Trying to do this here before conversion properties kick in and this becomes a new expression... (Fixing Class c; const char * a = c;)
11191    // Mark nohead classes as by reference, unless we're casting them to an integral type
11192    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11193       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11194          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11195           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11196    {
11197       exp.byReference = true;
11198    }
11199
11200    yylloc = exp.loc;
11201    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11202    else if(exp.destType && !exp.destType.keepCast)
11203    {
11204       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11205          exp.needTemplateCast = 1;
11206
11207       if(exp.destType.kind == voidType);
11208       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11209       {
11210          // Warn for casting unrelated types to/from struct classes
11211          bool invalidCast = false;
11212          if(inCompiler && exp.destType.count && exp.expType)
11213          {
11214             Class c1 = (exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
11215             Class c2 = (exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
11216             if(c1 && c1.type != structClass) c1 = null;
11217             if(c2 && c2.type != structClass) c2 = null;
11218             if((c1 && !exp.expType.byReference && !c2 && !exp.destType.isPointerType) || (c2 && !exp.destType.byReference && !c1 && !exp.expType.isPointerType))
11219                invalidCast = true;
11220          }
11221          if(!exp.destType.count || unresolved || invalidCast)
11222          {
11223             if(!exp.expType)
11224             {
11225                yylloc = exp.loc;
11226                if(exp.destType.kind != ellipsisType)
11227                {
11228                   char type2[1024];
11229                   type2[0] = '\0';
11230                   if(inCompiler)
11231                   {
11232                      char expString[10240];
11233                      expString[0] = '\0';
11234
11235                      PrintType(exp.destType, type2, false, true);
11236
11237                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11238                      if(unresolved)
11239                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11240                      else if(exp.type != dummyExp)
11241                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11242                   }
11243                }
11244                else
11245                {
11246                   char expString[10240] ;
11247                   expString[0] = '\0';
11248                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11249
11250                   if(unresolved)
11251                      Compiler_Error($"unresolved identifier %s\n", expString);
11252                   else if(exp.type != dummyExp)
11253                      Compiler_Error($"couldn't determine type of %s\n", expString);
11254                }
11255             }
11256             else
11257             {
11258                char type1[1024];
11259                char type2[1024];
11260                type1[0] = '\0';
11261                type2[0] = '\0';
11262                if(inCompiler)
11263                {
11264                   PrintType(exp.expType, type1, false, true);
11265                   PrintType(exp.destType, type2, false, true);
11266                }
11267
11268                //CheckExpressionType(exp, exp.destType, false);
11269
11270                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11271                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11272                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11273                else
11274                {
11275                   Expression nbExp = GetNonBracketsExp(exp);
11276                   bool skipWarning = false;
11277                   TypeKind kind = exp.destType.kind;
11278                   if(nbExp.type == conditionExp && nbExp.destType && !nbExp.destType.casted && nbExp.destType.kind == exp.destType.kind)
11279                      // The if/else operands have already been checked / warned about
11280                      skipWarning = true;
11281                   if((kind == charType || kind == shortType) && exp.destType.isSigned == exp.expType.signedBeforePromotion && nbExp.type == opExp && nbExp.op.exp1 && nbExp.op.exp2)
11282                   {
11283                      int op = nbExp.op.op;
11284                      Expression nbExp1, nbExp2;
11285                      TypeKind from;
11286
11287                      switch(op)
11288                      {
11289                         case '%': case '/':
11290                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11291                            from = nbExp1.expType.promotedFrom;
11292                            // Division and Modulo will not take more room than type before promotion
11293                            if(from == charType || (kind == shortType && from == shortType))
11294                               skipWarning = true;
11295                            break;
11296                         // Left shift
11297                         case LEFT_OP: case RIGHT_OP:
11298                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11299                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11300                            from = nbExp1.expType.promotedFrom;
11301                            // Right shift will not take more room than type before promotion
11302                            if(op == RIGHT_OP && (from == charType || (kind == shortType && from == shortType)))
11303                               skipWarning = true;
11304                            else if(nbExp2.isConstant && nbExp2.type == constantExp && (nbExp.op.op == RIGHT_OP || nbExp1.expType.bitMemberSize))
11305                            {
11306                               int n = (int)strtol(nbExp2.constant, null, 0);
11307                               int s = from == charType ? 8 : 16;
11308                               // Left shifting a bit member constrained in size may still fit in type before promotion
11309                               if(nbExp1.expType.bitMemberSize && nbExp1.expType.bitMemberSize < s)
11310                                  s = nbExp1.expType.bitMemberSize;
11311
11312                               // If right shifted enough things will fit in smaller type
11313                               if(nbExp.op.op == RIGHT_OP)
11314                                  s -= n;
11315                               else
11316                                  s += n;
11317                               if(s <= (kind == charType ? 8 : 16))
11318                                  skipWarning = true;
11319                            }
11320                            break;
11321                         case '-':
11322                            if(!exp.destType.isSigned)
11323                            {
11324                               nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11325                               nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11326                               from = nbExp2.expType.promotedFrom;
11327                               // Max value of unsigned type before promotion minus the same will always fit
11328                               if((from == charType || from == shortType) && nbExp1.isConstant && nbExp1.type == constantExp)
11329                               {
11330                                  int n = (int)strtol(nbExp1.constant, null, 0);
11331                                  if(n == (from == charType ? 255 : 65535))
11332                                     skipWarning = true;
11333                               }
11334                            }
11335                            break;
11336                         case '|':
11337                         {
11338                            TypeKind kind1, kind2;
11339                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11340                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11341                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11342                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11343                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) &&
11344                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11345                               skipWarning = true;
11346                            break;
11347                         }
11348                         case '&':
11349                         {
11350                            TypeKind kind1, kind2;
11351                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11352                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11353                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11354                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11355                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) ||
11356                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11357                               skipWarning = true;
11358                            break;
11359                         }
11360                      }
11361                   }
11362
11363                   if(!skipWarning)
11364                   {
11365                      char expString[10240];
11366                      expString[0] = '\0';
11367                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11368
11369 #ifdef _DEBUG
11370                      CheckExpressionType(exp, exp.destType, false, true);
11371 #endif
11372
11373                      // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11374                      if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11375                                         !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11376                                         !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11377                                         !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11378                      {
11379                         if(invalidCast)
11380                            Compiler_Error($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11381                         else
11382                            Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11383                      }
11384                   }
11385
11386                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11387                   if(!inCompiler)
11388                   {
11389                      FreeType(exp.expType);
11390                      exp.destType.refCount++;
11391                      exp.expType = exp.destType;
11392                   }
11393                }
11394             }
11395          }
11396       }
11397       // Cast function pointers to void * as eC already checked compatibility
11398       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11399               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11400       {
11401          Expression nbExp = GetNonBracketsExp(exp);
11402          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11403          {
11404             Expression e = MoveExpContents(exp);
11405             exp.cast.exp = MkExpBrackets(MkListOne(e));
11406             exp.type = castExp;
11407             exp.cast.exp.destType = exp.destType;
11408             if(exp.destType) exp.destType.refCount++;
11409             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11410          }
11411       }
11412    }
11413    else if(unresolved)
11414    {
11415       if(exp.identifier._class && exp.identifier._class.name)
11416          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11417       else if(exp.identifier.string && exp.identifier.string[0])
11418          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11419    }
11420    else if(!exp.expType && exp.type != dummyExp)
11421    {
11422       char expString[10240];
11423       expString[0] = '\0';
11424       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11425       Compiler_Error($"couldn't determine type of %s\n", expString);
11426    }
11427
11428    // Let's try to support any_object & typed_object here:
11429    if(inCompiler)
11430       ApplyAnyObjectLogic(exp);
11431
11432    // Mark nohead classes as by reference, unless we're casting them to an integral type
11433    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11434       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11435          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11436           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11437    {
11438       exp.byReference = true;
11439    }
11440    yylloc = oldyylloc;
11441 }
11442
11443 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11444 {
11445    // THIS CODE WILL FIND NEXT MEMBER...
11446    if(*curMember)
11447    {
11448       *curMember = (*curMember).next;
11449
11450       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11451       {
11452          *curMember = subMemberStack[--(*subMemberStackPos)];
11453          *curMember = (*curMember).next;
11454       }
11455
11456       // SKIP ALL PROPERTIES HERE...
11457       while((*curMember) && (*curMember).isProperty)
11458          *curMember = (*curMember).next;
11459
11460       if(subMemberStackPos)
11461       {
11462          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11463          {
11464             subMemberStack[(*subMemberStackPos)++] = *curMember;
11465
11466             *curMember = (*curMember).members.first;
11467             while(*curMember && (*curMember).isProperty)
11468                *curMember = (*curMember).next;
11469          }
11470       }
11471    }
11472    while(!*curMember)
11473    {
11474       if(!*curMember)
11475       {
11476          if(subMemberStackPos && *subMemberStackPos)
11477          {
11478             *curMember = subMemberStack[--(*subMemberStackPos)];
11479             *curMember = (*curMember).next;
11480          }
11481          else
11482          {
11483             Class lastCurClass = *curClass;
11484
11485             if(*curClass == _class) break;     // REACHED THE END
11486
11487             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11488             *curMember = (*curClass).membersAndProperties.first;
11489          }
11490
11491          while((*curMember) && (*curMember).isProperty)
11492             *curMember = (*curMember).next;
11493          if(subMemberStackPos)
11494          {
11495             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11496             {
11497                subMemberStack[(*subMemberStackPos)++] = *curMember;
11498
11499                *curMember = (*curMember).members.first;
11500                while(*curMember && (*curMember).isProperty)
11501                   *curMember = (*curMember).next;
11502             }
11503          }
11504       }
11505    }
11506 }
11507
11508
11509 static void ProcessInitializer(Initializer init, Type type)
11510 {
11511    switch(init.type)
11512    {
11513       case expInitializer:
11514          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11515          {
11516             // TESTING THIS FOR SHUTTING = 0 WARNING
11517             if(init.exp && !init.exp.destType)
11518             {
11519                FreeType(init.exp.destType);
11520                init.exp.destType = type;
11521                if(type) type.refCount++;
11522             }
11523             if(init.exp)
11524             {
11525                ProcessExpressionType(init.exp);
11526                init.isConstant = init.exp.isConstant;
11527             }
11528             break;
11529          }
11530          else
11531          {
11532             Expression exp = init.exp;
11533             Instantiation inst = exp.instance;
11534             MembersInit members;
11535
11536             init.type = listInitializer;
11537             init.list = MkList();
11538
11539             if(inst.members)
11540             {
11541                for(members = inst.members->first; members; members = members.next)
11542                {
11543                   if(members.type == dataMembersInit)
11544                   {
11545                      MemberInit member;
11546                      for(member = members.dataMembers->first; member; member = member.next)
11547                      {
11548                         ListAdd(init.list, member.initializer);
11549                         member.initializer = null;
11550                      }
11551                   }
11552                   // Discard all MembersInitMethod
11553                }
11554             }
11555             FreeExpression(exp);
11556          }
11557       case listInitializer:
11558       {
11559          Initializer i;
11560          Type initializerType = null;
11561          Class curClass = null;
11562          DataMember curMember = null;
11563          DataMember subMemberStack[256];
11564          int subMemberStackPos = 0;
11565
11566          if(type && type.kind == arrayType)
11567             initializerType = Dereference(type);
11568          else if(type && (type.kind == structType || type.kind == unionType))
11569             initializerType = type.members.first;
11570
11571          for(i = init.list->first; i; i = i.next)
11572          {
11573             if(type && type.kind == classType && type._class && type._class.registered)
11574             {
11575                // 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)
11576                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11577                // TODO: Generate error on initializing a private data member this way from another module...
11578                if(curMember)
11579                {
11580                   if(!curMember.dataType)
11581                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11582                   initializerType = curMember.dataType;
11583                }
11584             }
11585             ProcessInitializer(i, initializerType);
11586             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11587                initializerType = initializerType.next;
11588             if(!i.isConstant)
11589                init.isConstant = false;
11590          }
11591
11592          if(type && type.kind == arrayType)
11593             FreeType(initializerType);
11594
11595          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11596          {
11597             Compiler_Error($"Assigning list initializer to non list\n");
11598          }
11599          break;
11600       }
11601    }
11602 }
11603
11604 static void ProcessSpecifier(Specifier spec, bool declareStruct, bool warnClasses)
11605 {
11606    switch(spec.type)
11607    {
11608       case baseSpecifier:
11609       {
11610          if(spec.specifier == THISCLASS)
11611          {
11612             if(thisClass)
11613             {
11614                spec.type = nameSpecifier;
11615                spec.name = ReplaceThisClass(thisClass);
11616                spec.symbol = FindClass(spec.name);
11617                ProcessSpecifier(spec, declareStruct, false);
11618             }
11619          }
11620          break;
11621       }
11622       case nameSpecifier:
11623       {
11624          Symbol symbol = FindType(curContext, spec.name);
11625          if(symbol)
11626             DeclareType(curExternal, symbol.type, true, true);
11627          else if(spec.symbol /*&& declareStruct*/)
11628          {
11629             Class c = spec.symbol.registered;
11630             if(warnClasses && !c)
11631                Compiler_Warning("Undeclared class %s\n", spec.name);
11632             DeclareStruct(curExternal, spec.name, c && c.type == noHeadClass, declareStruct && c && c.type == structClass);
11633          }
11634          break;
11635       }
11636       case enumSpecifier:
11637       {
11638          Enumerator e;
11639          if(spec.list)
11640          {
11641             for(e = spec.list->first; e; e = e.next)
11642             {
11643                if(e.exp)
11644                   ProcessExpressionType(e.exp);
11645             }
11646          }
11647          // Fall through for IDE type processing
11648          if(inCompiler)
11649             break;
11650       }
11651       case structSpecifier:
11652       case unionSpecifier:
11653       {
11654          if(spec.definitions)
11655          {
11656             //ClassDef def;
11657             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11658             //if(symbol)
11659                ProcessClass(spec.definitions, symbol);
11660             /*else
11661             {
11662                for(def = spec.definitions->first; def; def = def.next)
11663                {
11664                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11665                      ProcessDeclaration(def.decl);
11666                }
11667             }*/
11668          }
11669          break;
11670       }
11671       /*
11672       case classSpecifier:
11673       {
11674          Symbol classSym = FindClass(spec.name);
11675          if(classSym && classSym.registered && classSym.registered.type == structClass)
11676             DeclareStruct(spec.name, false, true);
11677          break;
11678       }
11679       */
11680    }
11681 }
11682
11683
11684 static void ProcessDeclarator(Declarator decl, bool isFunction)
11685 {
11686    switch(decl.type)
11687    {
11688       case identifierDeclarator:
11689          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11690          {
11691             FreeSpecifier(decl.identifier._class);
11692             decl.identifier._class = null;
11693          }
11694          break;
11695       case arrayDeclarator:
11696          if(decl.array.exp)
11697             ProcessExpressionType(decl.array.exp);
11698       case structDeclarator:
11699       case bracketsDeclarator:
11700       case functionDeclarator:
11701       case pointerDeclarator:
11702       case extendedDeclarator:
11703       case extendedDeclaratorEnd:
11704       {
11705          Identifier id = null;
11706          Specifier classSpec = null;
11707          if(decl.type == functionDeclarator)
11708          {
11709             id = GetDeclId(decl);
11710             if(id && id._class)
11711             {
11712                classSpec = id._class;
11713                id._class = null;
11714             }
11715          }
11716          if(decl.declarator)
11717             ProcessDeclarator(decl.declarator, isFunction);
11718          if(decl.type == functionDeclarator)
11719          {
11720             if(classSpec)
11721             {
11722                TypeName param
11723                {
11724                   qualifiers = MkListOne(classSpec);
11725                   declarator = null;
11726                };
11727                if(!decl.function.parameters)
11728                   decl.function.parameters = MkList();
11729                decl.function.parameters->Insert(null, param);
11730             }
11731             if(decl.function.parameters)
11732             {
11733                TypeName param;
11734
11735                for(param = decl.function.parameters->first; param; param = param.next)
11736                {
11737                   if(param.qualifiers)
11738                   {
11739                      Specifier spec;
11740                      for(spec = param.qualifiers->first; spec; spec = spec.next)
11741                      {
11742                         if(spec.type == baseSpecifier)
11743                         {
11744                            if(spec.specifier == TYPED_OBJECT)
11745                            {
11746                               Declarator d = param.declarator;
11747                               TypeName newParam
11748                               {
11749                                  qualifiers = MkListOne(MkSpecifier(VOID));
11750                                  declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11751                               };
11752                               if(!d || d.type != pointerDeclarator)
11753                                  newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11754
11755                               FreeList(param.qualifiers, FreeSpecifier);
11756
11757                               param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11758                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11759
11760                               DeclareStruct(curExternal, "ecere::com::Class", false, true);
11761
11762                               decl.function.parameters->Insert(param, newParam);
11763                               param = newParam;
11764                               break;
11765                            }
11766                            else if(spec.specifier == ANY_OBJECT)
11767                            {
11768                               Declarator d = param.declarator;
11769
11770                               FreeList(param.qualifiers, FreeSpecifier);
11771
11772                               param.qualifiers = MkListOne(MkSpecifier(VOID));
11773                               if(!d || d.type != pointerDeclarator)
11774                                  param.qualifiers->Insert(null, MkSpecifier(CONST));
11775                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11776                               break;
11777                            }
11778                            else if(spec.specifier == THISCLASS)
11779                            {
11780                               if(thisClass)
11781                               {
11782                                  spec.type = nameSpecifier;
11783                                  spec.name = ReplaceThisClass(thisClass);
11784                                  spec.symbol = FindClass(spec.name);
11785                                  ProcessSpecifier(spec, false, false);
11786                               }
11787                               break;
11788                            }
11789                         }
11790                         else if(spec.type == nameSpecifier)
11791                         {
11792                            ProcessSpecifier(spec, isFunction, true);
11793                         }
11794                         else if((spec.type == structSpecifier || spec.type == unionSpecifier) && !spec.definitions && spec.id && spec.id.string)
11795                         {
11796                            Declarator d = param.declarator;
11797                            if(!d || d.type != pointerDeclarator)
11798                               DeclareStruct(curExternal, spec.id.string, false, true);
11799                         }
11800                      }
11801                   }
11802
11803                   if(param.declarator)
11804                      ProcessDeclarator(param.declarator, false);
11805                }
11806             }
11807          }
11808          break;
11809       }
11810    }
11811 }
11812
11813 static void ProcessDeclaration(Declaration decl, bool warnClasses)
11814 {
11815    yylloc = decl.loc;
11816    switch(decl.type)
11817    {
11818       case initDeclaration:
11819       {
11820          bool declareStruct = false;
11821          /*
11822          lineNum = decl.pos.line;
11823          column = decl.pos.col;
11824          */
11825
11826          if(decl.declarators)
11827          {
11828             InitDeclarator d;
11829
11830             for(d = decl.declarators->first; d; d = d.next)
11831             {
11832                Type type, subType;
11833                ProcessDeclarator(d.declarator, false);
11834
11835                type = ProcessType(decl.specifiers, d.declarator);
11836
11837                if(d.initializer)
11838                {
11839                   ProcessInitializer(d.initializer, type);
11840
11841                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11842
11843                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11844                      d.initializer.exp.type == instanceExp)
11845                   {
11846                      if(type.kind == classType && type._class ==
11847                         d.initializer.exp.expType._class)
11848                      {
11849                         Instantiation inst = d.initializer.exp.instance;
11850                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11851
11852                         d.initializer.exp.instance = null;
11853                         if(decl.specifiers)
11854                            FreeList(decl.specifiers, FreeSpecifier);
11855                         FreeList(decl.declarators, FreeInitDeclarator);
11856
11857                         d = null;
11858
11859                         decl.type = instDeclaration;
11860                         decl.inst = inst;
11861                      }
11862                   }
11863                }
11864                for(subType = type; subType;)
11865                {
11866                   if(subType.kind == classType)
11867                   {
11868                      declareStruct = true;
11869                      break;
11870                   }
11871                   else if(subType.kind == pointerType)
11872                      break;
11873                   else if(subType.kind == arrayType)
11874                      subType = subType.arrayType;
11875                   else
11876                      break;
11877                }
11878
11879                FreeType(type);
11880                if(!d) break;
11881             }
11882          }
11883
11884          if(decl.specifiers)
11885          {
11886             Specifier s;
11887             for(s = decl.specifiers->first; s; s = s.next)
11888             {
11889                ProcessSpecifier(s, declareStruct, true);
11890             }
11891          }
11892          break;
11893       }
11894       case instDeclaration:
11895       {
11896          ProcessInstantiationType(decl.inst);
11897          break;
11898       }
11899       case structDeclaration:
11900       {
11901          Specifier spec;
11902          Declarator d;
11903          bool declareStruct = false;
11904
11905          if(decl.declarators)
11906          {
11907             for(d = decl.declarators->first; d; d = d.next)
11908             {
11909                Type type = ProcessType(decl.specifiers, d.declarator);
11910                Type subType;
11911                ProcessDeclarator(d, false);
11912                for(subType = type; subType;)
11913                {
11914                   if(subType.kind == classType)
11915                   {
11916                      declareStruct = true;
11917                      break;
11918                   }
11919                   else if(subType.kind == pointerType)
11920                      break;
11921                   else if(subType.kind == arrayType)
11922                      subType = subType.arrayType;
11923                   else
11924                      break;
11925                }
11926                FreeType(type);
11927             }
11928          }
11929          if(decl.specifiers)
11930          {
11931             for(spec = decl.specifiers->first; spec; spec = spec.next)
11932                ProcessSpecifier(spec, declareStruct, warnClasses);
11933          }
11934          break;
11935       }
11936    }
11937 }
11938
11939 static FunctionDefinition curFunction;
11940
11941 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11942 {
11943    char propName[1024], propNameM[1024];
11944    char getName[1024], setName[1024];
11945    OldList * args;
11946
11947    DeclareProperty(curExternal, prop, setName, getName);
11948
11949    // eInstance_FireWatchers(object, prop);
11950    strcpy(propName, "__ecereProp_");
11951    FullClassNameCat(propName, prop._class.fullName, false);
11952    strcat(propName, "_");
11953    FullClassNameCat(propName, prop.name, true);
11954
11955    strcpy(propNameM, "__ecerePropM_");
11956    FullClassNameCat(propNameM, prop._class.fullName, false);
11957    strcat(propNameM, "_");
11958    FullClassNameCat(propNameM, prop.name, true);
11959
11960    if(prop.isWatchable)
11961    {
11962       args = MkList();
11963       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11964       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11965       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11966
11967       args = MkList();
11968       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11969       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11970       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11971
11972       DeclareFunctionUtil(curExternal, "eInstance_FireWatchers");
11973    }
11974
11975    {
11976       args = MkList();
11977       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11978       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11979       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11980
11981       args = MkList();
11982       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11983       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11984       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11985
11986       DeclareFunctionUtil(curExternal, "eInstance_FireSelfWatchers");
11987    }
11988
11989    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11990       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11991       curFunction.propSet.fireWatchersDone = true;
11992 }
11993
11994 static void ProcessStatement(Statement stmt)
11995 {
11996    yylloc = stmt.loc;
11997    /*
11998    lineNum = stmt.pos.line;
11999    column = stmt.pos.col;
12000    */
12001    switch(stmt.type)
12002    {
12003       case labeledStmt:
12004          ProcessStatement(stmt.labeled.stmt);
12005          break;
12006       case caseStmt:
12007          // This expression should be constant...
12008          if(stmt.caseStmt.exp)
12009          {
12010             FreeType(stmt.caseStmt.exp.destType);
12011             stmt.caseStmt.exp.destType = curSwitchType;
12012             if(curSwitchType) curSwitchType.refCount++;
12013             ProcessExpressionType(stmt.caseStmt.exp);
12014             ComputeExpression(stmt.caseStmt.exp);
12015          }
12016          if(stmt.caseStmt.stmt)
12017             ProcessStatement(stmt.caseStmt.stmt);
12018          break;
12019       case compoundStmt:
12020       {
12021          if(stmt.compound.context)
12022          {
12023             Declaration decl;
12024             Statement s;
12025
12026             Statement prevCompound = curCompound;
12027             Context prevContext = curContext;
12028
12029             if(!stmt.compound.isSwitch)
12030                curCompound = stmt;
12031             curContext = stmt.compound.context;
12032
12033             if(stmt.compound.declarations)
12034             {
12035                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
12036                   ProcessDeclaration(decl, true);
12037             }
12038             if(stmt.compound.statements)
12039             {
12040                for(s = stmt.compound.statements->first; s; s = s.next)
12041                   ProcessStatement(s);
12042             }
12043
12044             curContext = prevContext;
12045             curCompound = prevCompound;
12046          }
12047          break;
12048       }
12049       case expressionStmt:
12050       {
12051          Expression exp;
12052          if(stmt.expressions)
12053          {
12054             for(exp = stmt.expressions->first; exp; exp = exp.next)
12055                ProcessExpressionType(exp);
12056          }
12057          break;
12058       }
12059       case ifStmt:
12060       {
12061          Expression exp;
12062
12063          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
12064          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
12065          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
12066          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
12067          {
12068             ProcessExpressionType(exp);
12069          }
12070          if(stmt.ifStmt.stmt)
12071             ProcessStatement(stmt.ifStmt.stmt);
12072          if(stmt.ifStmt.elseStmt)
12073             ProcessStatement(stmt.ifStmt.elseStmt);
12074          break;
12075       }
12076       case switchStmt:
12077       {
12078          Type oldSwitchType = curSwitchType;
12079          if(stmt.switchStmt.exp)
12080          {
12081             Expression exp;
12082             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
12083             {
12084                if(!exp.next)
12085                {
12086                   /*
12087                   Type destType
12088                   {
12089                      kind = intType;
12090                      refCount = 1;
12091                   };
12092                   e.exp.destType = destType;
12093                   */
12094
12095                   ProcessExpressionType(exp);
12096                }
12097                if(!exp.next)
12098                   curSwitchType = exp.expType;
12099             }
12100          }
12101          ProcessStatement(stmt.switchStmt.stmt);
12102          curSwitchType = oldSwitchType;
12103          break;
12104       }
12105       case whileStmt:
12106       {
12107          if(stmt.whileStmt.exp)
12108          {
12109             Expression exp;
12110
12111             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
12112             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
12113             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
12114             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
12115             {
12116                ProcessExpressionType(exp);
12117             }
12118          }
12119          if(stmt.whileStmt.stmt)
12120             ProcessStatement(stmt.whileStmt.stmt);
12121          break;
12122       }
12123       case doWhileStmt:
12124       {
12125          if(stmt.doWhile.exp)
12126          {
12127             Expression exp;
12128
12129             if(stmt.doWhile.exp->last)
12130             {
12131                FreeType(((Expression)stmt.doWhile.exp->last).destType);
12132                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
12133                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
12134             }
12135             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
12136             {
12137                ProcessExpressionType(exp);
12138             }
12139          }
12140          if(stmt.doWhile.stmt)
12141             ProcessStatement(stmt.doWhile.stmt);
12142          break;
12143       }
12144       case forStmt:
12145       {
12146          Expression exp;
12147          if(stmt.forStmt.init)
12148             ProcessStatement(stmt.forStmt.init);
12149
12150          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
12151          {
12152             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
12153             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
12154             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
12155          }
12156
12157          if(stmt.forStmt.check)
12158             ProcessStatement(stmt.forStmt.check);
12159          if(stmt.forStmt.increment)
12160          {
12161             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
12162                ProcessExpressionType(exp);
12163          }
12164
12165          if(stmt.forStmt.stmt)
12166             ProcessStatement(stmt.forStmt.stmt);
12167          break;
12168       }
12169       case forEachStmt:
12170       {
12171          Identifier id = stmt.forEachStmt.id;
12172          OldList * exp = stmt.forEachStmt.exp;
12173          OldList * filter = stmt.forEachStmt.filter;
12174          Statement block = stmt.forEachStmt.stmt;
12175          char iteratorType[1024];
12176          Type source;
12177          Expression e;
12178          bool isBuiltin = exp && exp->last &&
12179             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12180               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12181          Expression arrayExp;
12182          const char * typeString = null;
12183          int builtinCount = 0;
12184
12185          for(e = exp ? exp->first : null; e; e = e.next)
12186          {
12187             if(!e.next)
12188             {
12189                FreeType(e.destType);
12190                e.destType = ProcessTypeString("Container", false);
12191             }
12192             if(!isBuiltin || e.next)
12193                ProcessExpressionType(e);
12194          }
12195
12196          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12197          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12198             eClass_IsDerived(source._class.registered, containerClass)))
12199          {
12200             Class _class = source ? source._class.registered : null;
12201             Symbol symbol;
12202             Expression expIt = null;
12203             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12204             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12205             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12206             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12207
12208             if(inCompiler)
12209             {
12210                stmt.type = compoundStmt;
12211
12212                stmt.compound.context = Context { };
12213                stmt.compound.context.parent = curContext;
12214                curContext = stmt.compound.context;
12215             }
12216
12217             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12218             {
12219                Class mapClass = eSystem_FindClass(privateModule, "Map");
12220                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12221                isCustomAVLTree = true;
12222                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12223                   isAVLTree = true;
12224                else */if(eClass_IsDerived(source._class.registered, mapClass))
12225                   isMap = true;
12226             }
12227             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12228             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12229             {
12230                Class listClass = eSystem_FindClass(privateModule, "List");
12231                isLinkList = true;
12232                isList = eClass_IsDerived(source._class.registered, listClass);
12233             }
12234
12235             if(inCompiler && isArray)
12236             {
12237                Declarator decl;
12238                OldList * specs = MkList();
12239                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12240                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12241                stmt.compound.declarations = MkListOne(
12242                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12243                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12244                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12245                      MkInitializerAssignment(MkExpBrackets(exp))))));
12246             }
12247             else if(isBuiltin)
12248             {
12249                Type type = null;
12250                char typeStringBuf[1024];
12251
12252                // TODO: Merge this code?
12253                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12254                if(((Expression)exp->last).type == castExp)
12255                {
12256                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12257                   if(typeName)
12258                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12259                }
12260
12261                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12262                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12263                   arrayExp.destType._class.registered.templateArgs)
12264                {
12265                   Class templateClass = arrayExp.destType._class.registered;
12266                   typeString = templateClass.templateArgs[2].dataTypeString;
12267                }
12268                else if(arrayExp.list)
12269                {
12270                   // Guess type from expressions in the array
12271                   Expression e;
12272                   for(e = arrayExp.list->first; e; e = e.next)
12273                   {
12274                      ProcessExpressionType(e);
12275                      if(e.expType)
12276                      {
12277                         if(!type) { type = e.expType; type.refCount++; }
12278                         else
12279                         {
12280                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12281                            if(!MatchTypeExpression(e, type, null, false, true))
12282                            {
12283                               FreeType(type);
12284                               type = e.expType;
12285                               e.expType = null;
12286
12287                               e = arrayExp.list->first;
12288                               ProcessExpressionType(e);
12289                               if(e.expType)
12290                               {
12291                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12292                                  if(!MatchTypeExpression(e, type, null, false, true))
12293                                  {
12294                                     FreeType(e.expType);
12295                                     e.expType = null;
12296                                     FreeType(type);
12297                                     type = null;
12298                                     break;
12299                                  }
12300                               }
12301                            }
12302                         }
12303                         if(e.expType)
12304                         {
12305                            FreeType(e.expType);
12306                            e.expType = null;
12307                         }
12308                      }
12309                   }
12310                   if(type)
12311                   {
12312                      typeStringBuf[0] = '\0';
12313                      PrintType(type, typeStringBuf, false, true);
12314                      typeString = typeStringBuf;
12315                      FreeType(type);
12316                   }
12317                }
12318                if(typeString)
12319                {
12320                   if(inCompiler)
12321                   {
12322                      OldList * initializers = MkList();
12323                      Declarator decl;
12324                      OldList * specs = MkList();
12325                      if(arrayExp.list)
12326                      {
12327                         Expression e;
12328
12329                         builtinCount = arrayExp.list->count;
12330                         type = ProcessTypeString(typeString, false);
12331                         while((e = arrayExp.list->first))
12332                         {
12333                            arrayExp.list->Remove(e);
12334                            e.destType = type;
12335                            type.refCount++;
12336                            ProcessExpressionType(e);
12337                            if(inCompiler)
12338                               ListAdd(initializers, MkInitializerAssignment(e));
12339                         }
12340                         FreeType(type);
12341                         delete arrayExp.list;
12342                      }
12343                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12344
12345                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12346                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12347
12348                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12349                         PlugDeclarator(
12350                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12351                            ), MkInitializerList(initializers)))));
12352                      FreeList(exp, FreeExpression);
12353                   }
12354                   else if(arrayExp.list)
12355                   {
12356                      Expression e;
12357                      type = ProcessTypeString(typeString, false);
12358                      for(e = arrayExp.list->first; e; e = e.next)
12359                      {
12360                         e.destType = type;
12361                         type.refCount++;
12362                         ProcessExpressionType(e);
12363                      }
12364                      FreeType(type);
12365                   }
12366                }
12367                else
12368                {
12369                   arrayExp.expType = ProcessTypeString("Container", false);
12370                   Compiler_Error($"Couldn't determine type of array elements\n");
12371                }
12372
12373                /*
12374                Declarator decl;
12375                OldList * specs = MkList();
12376
12377                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12378                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12379                stmt.compound.declarations = MkListOne(
12380                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12381                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12382                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12383                      MkInitializerAssignment(MkExpBrackets(exp))))));
12384                */
12385             }
12386             else if(inCompiler && isLinkList && !isList)
12387             {
12388                Declarator decl;
12389                OldList * specs = MkList();
12390                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12391                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12392                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12393                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12394                      MkInitializerAssignment(MkExpBrackets(exp))))));
12395             }
12396             /*else if(isCustomAVLTree)
12397             {
12398                Declarator decl;
12399                OldList * specs = MkList();
12400                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12401                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12402                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12403                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12404                      MkInitializerAssignment(MkExpBrackets(exp))))));
12405             }*/
12406             else if(inCompiler && _class.templateArgs)
12407             {
12408                if(isMap)
12409                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12410                else
12411                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12412
12413                stmt.compound.declarations = MkListOne(
12414                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12415                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12416                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12417             }
12418             if(inCompiler)
12419             {
12420                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12421
12422                if(block)
12423                {
12424                   // Reparent sub-contexts in this statement
12425                   switch(block.type)
12426                   {
12427                      case compoundStmt:
12428                         if(block.compound.context)
12429                            block.compound.context.parent = stmt.compound.context;
12430                         break;
12431                      case ifStmt:
12432                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12433                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12434                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12435                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12436                         break;
12437                      case switchStmt:
12438                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12439                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12440                         break;
12441                      case whileStmt:
12442                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12443                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12444                         break;
12445                      case doWhileStmt:
12446                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12447                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12448                         break;
12449                      case forStmt:
12450                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12451                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12452                         break;
12453                      case forEachStmt:
12454                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12455                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12456                         break;
12457                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12458                      case labeledStmt:
12459                      case caseStmt
12460                      case expressionStmt:
12461                      case gotoStmt:
12462                      case continueStmt:
12463                      case breakStmt
12464                      case returnStmt:
12465                      case asmStmt:
12466                      case badDeclarationStmt:
12467                      case fireWatchersStmt:
12468                      case stopWatchingStmt:
12469                      case watchStmt:
12470                      */
12471                   }
12472                }
12473
12474                if(filter)
12475                {
12476                   block = MkIfStmt(filter, block, null);
12477                }
12478                if(isArray)
12479                {
12480                   stmt.compound.statements = MkListOne(MkForStmt(
12481                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12482                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12483                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12484                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12485                      block));
12486                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12487                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12488                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12489                }
12490                else if(isBuiltin)
12491                {
12492                   char count[128];
12493                   //OldList * specs = MkList();
12494                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12495
12496                   sprintf(count, "%d", builtinCount);
12497
12498                   stmt.compound.statements = MkListOne(MkForStmt(
12499                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12500                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12501                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12502                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12503                      block));
12504
12505                   /*
12506                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12507                   stmt.compound.statements = MkListOne(MkForStmt(
12508                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12509                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12510                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12511                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12512                      block));
12513                  */
12514                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12515                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12516                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12517                }
12518                else if(isLinkList && !isList)
12519                {
12520                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12521                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12522                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12523                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12524                   {
12525                      stmt.compound.statements = MkListOne(MkForStmt(
12526                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12527                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12528                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12529                         block));
12530                   }
12531                   else
12532                   {
12533                      OldList * specs = MkList();
12534                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12535                      stmt.compound.statements = MkListOne(MkForStmt(
12536                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12537                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12538                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12539                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12540                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12541                         block));
12542                   }
12543                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12544                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12545                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12546                }
12547                /*else if(isCustomAVLTree)
12548                {
12549                   stmt.compound.statements = MkListOne(MkForStmt(
12550                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12551                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12552                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12553                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12554                      block));
12555
12556                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12557                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12558                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12559                }*/
12560                else
12561                {
12562                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12563                      MkIdentifier("Next")), null)), block));
12564                }
12565                ProcessExpressionType(expIt);
12566                if(stmt.compound.declarations->first)
12567                   ProcessDeclaration(stmt.compound.declarations->first, true);
12568
12569                if(symbol)
12570                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12571
12572                ProcessStatement(stmt);
12573             }
12574             else
12575                ProcessStatement(stmt.forEachStmt.stmt);
12576             if(inCompiler)
12577                curContext = stmt.compound.context.parent;
12578             break;
12579          }
12580          else
12581          {
12582             Compiler_Error($"Expression is not a container\n");
12583          }
12584          break;
12585       }
12586       case gotoStmt:
12587          break;
12588       case continueStmt:
12589          break;
12590       case breakStmt:
12591          break;
12592       case returnStmt:
12593       {
12594          Expression exp;
12595          if(stmt.expressions)
12596          {
12597             for(exp = stmt.expressions->first; exp; exp = exp.next)
12598             {
12599                if(!exp.next)
12600                {
12601                   if(curFunction && !curFunction.type)
12602                      curFunction.type = ProcessType(
12603                         curFunction.specifiers, curFunction.declarator);
12604                   FreeType(exp.destType);
12605                   // TODO: current property if not compiling
12606                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12607                   if(exp.destType) exp.destType.refCount++;
12608                }
12609                ProcessExpressionType(exp);
12610             }
12611          }
12612          break;
12613       }
12614       case badDeclarationStmt:
12615       {
12616          ProcessDeclaration(stmt.decl, true);
12617          break;
12618       }
12619       case asmStmt:
12620       {
12621          AsmField field;
12622          if(stmt.asmStmt.inputFields)
12623          {
12624             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12625                if(field.expression)
12626                   ProcessExpressionType(field.expression);
12627          }
12628          if(stmt.asmStmt.outputFields)
12629          {
12630             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12631                if(field.expression)
12632                   ProcessExpressionType(field.expression);
12633          }
12634          if(stmt.asmStmt.clobberedFields)
12635          {
12636             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12637             {
12638                if(field.expression)
12639                   ProcessExpressionType(field.expression);
12640             }
12641          }
12642          break;
12643       }
12644       case watchStmt:
12645       {
12646          PropertyWatch propWatch;
12647          OldList * watches = stmt._watch.watches;
12648          Expression object = stmt._watch.object;
12649          Expression watcher = stmt._watch.watcher;
12650          if(watcher)
12651             ProcessExpressionType(watcher);
12652          if(object)
12653             ProcessExpressionType(object);
12654
12655          if(inCompiler)
12656          {
12657             if(watcher || thisClass)
12658             {
12659                External external = curExternal;
12660                Context context = curContext;
12661
12662                stmt.type = expressionStmt;
12663                stmt.expressions = MkList();
12664
12665                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12666                {
12667                   ClassFunction func;
12668                   char watcherName[1024];
12669                   Class watcherClass = watcher ?
12670                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12671                   External createdExternal;
12672
12673                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12674                   if(propWatch.deleteWatch)
12675                      strcat(watcherName, "_delete");
12676                   else
12677                   {
12678                      Identifier propID;
12679                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12680                      {
12681                         strcat(watcherName, "_");
12682                         strcat(watcherName, propID.string);
12683                      }
12684                   }
12685
12686                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12687                   {
12688                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12689                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12690                      ProcessClassFunctionBody(func, propWatch.compound);
12691                      propWatch.compound = null;
12692
12693                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12694
12695                      FreeClassFunction(func);
12696
12697                      curExternal = createdExternal;
12698                      ProcessFunction(createdExternal.function);
12699
12700                      if(propWatch.deleteWatch)
12701                      {
12702                         OldList * args = MkList();
12703                         ListAdd(args, CopyExpression(object));
12704                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12705                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12706                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12707                      }
12708                      else
12709                      {
12710                         Class _class = object.expType._class.registered;
12711                         Identifier propID;
12712
12713                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12714                         {
12715                            char propName[1024];
12716                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12717                            if(prop)
12718                            {
12719                               char getName[1024], setName[1024];
12720                               OldList * args = MkList();
12721
12722                               DeclareProperty(createdExternal, prop, setName, getName);
12723
12724                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12725                               strcpy(propName, "__ecereProp_");
12726                               FullClassNameCat(propName, prop._class.fullName, false);
12727                               strcat(propName, "_");
12728                               FullClassNameCat(propName, prop.name, true);
12729
12730                               ListAdd(args, CopyExpression(object));
12731                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12732                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12733                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12734
12735                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12736
12737                               external.CreateUniqueEdge(createdExternal, true);
12738                            }
12739                            else
12740                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12741                         }
12742                      }
12743                   }
12744                   else
12745                      Compiler_Error($"Invalid watched object\n");
12746                }
12747
12748                curExternal = external;
12749                curContext = context;
12750
12751                if(watcher)
12752                   FreeExpression(watcher);
12753                if(object)
12754                   FreeExpression(object);
12755                FreeList(watches, FreePropertyWatch);
12756             }
12757             else
12758                Compiler_Error($"No observer specified and not inside a class\n");
12759          }
12760          else
12761          {
12762             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12763             {
12764                ProcessStatement(propWatch.compound);
12765             }
12766
12767          }
12768          break;
12769       }
12770       case fireWatchersStmt:
12771       {
12772          OldList * watches = stmt._watch.watches;
12773          Expression object = stmt._watch.object;
12774          Class _class;
12775          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12776          // printf("%X\n", watches);
12777          // printf("%X\n", stmt._watch.watches);
12778          if(object)
12779             ProcessExpressionType(object);
12780
12781          if(inCompiler)
12782          {
12783             _class = object ?
12784                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12785
12786             if(_class)
12787             {
12788                Identifier propID;
12789
12790                stmt.type = expressionStmt;
12791                stmt.expressions = MkList();
12792
12793                // Check if we're inside a property set
12794                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12795                {
12796                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12797                }
12798                else if(!watches)
12799                {
12800                   //Compiler_Error($"No property specified and not inside a property set\n");
12801                }
12802                if(watches)
12803                {
12804                   for(propID = watches->first; propID; propID = propID.next)
12805                   {
12806                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12807                      if(prop)
12808                      {
12809                         CreateFireWatcher(prop, object, stmt);
12810                      }
12811                      else
12812                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12813                   }
12814                }
12815                else
12816                {
12817                   // Fire all properties!
12818                   Property prop;
12819                   Class base;
12820                   for(base = _class; base; base = base.base)
12821                   {
12822                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12823                      {
12824                         if(prop.isProperty && prop.isWatchable)
12825                         {
12826                            CreateFireWatcher(prop, object, stmt);
12827                         }
12828                      }
12829                   }
12830                }
12831
12832                if(object)
12833                   FreeExpression(object);
12834                FreeList(watches, FreeIdentifier);
12835             }
12836             else
12837                Compiler_Error($"Invalid object specified and not inside a class\n");
12838          }
12839          break;
12840       }
12841       case stopWatchingStmt:
12842       {
12843          OldList * watches = stmt._watch.watches;
12844          Expression object = stmt._watch.object;
12845          Expression watcher = stmt._watch.watcher;
12846          Class _class;
12847          if(object)
12848             ProcessExpressionType(object);
12849          if(watcher)
12850             ProcessExpressionType(watcher);
12851          if(inCompiler)
12852          {
12853             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12854
12855             if(watcher || thisClass)
12856             {
12857                if(_class)
12858                {
12859                   Identifier propID;
12860
12861                   stmt.type = expressionStmt;
12862                   stmt.expressions = MkList();
12863
12864                   if(!watches)
12865                   {
12866                      OldList * args;
12867                      // eInstance_StopWatching(object, null, watcher);
12868                      args = MkList();
12869                      ListAdd(args, CopyExpression(object));
12870                      ListAdd(args, MkExpConstant("0"));
12871                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12872                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12873                   }
12874                   else
12875                   {
12876                      for(propID = watches->first; propID; propID = propID.next)
12877                      {
12878                         char propName[1024];
12879                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12880                         if(prop)
12881                         {
12882                            char getName[1024], setName[1024];
12883                            OldList * args = MkList();
12884
12885                            DeclareProperty(curExternal, prop, setName, getName);
12886
12887                            // eInstance_StopWatching(object, prop, watcher);
12888                            strcpy(propName, "__ecereProp_");
12889                            FullClassNameCat(propName, prop._class.fullName, false);
12890                            strcat(propName, "_");
12891                            FullClassNameCat(propName, prop.name, true);
12892
12893                            ListAdd(args, CopyExpression(object));
12894                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12895                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12896                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12897                         }
12898                         else
12899                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12900                      }
12901                   }
12902
12903                   if(object)
12904                      FreeExpression(object);
12905                   if(watcher)
12906                      FreeExpression(watcher);
12907                   FreeList(watches, FreeIdentifier);
12908                }
12909                else
12910                   Compiler_Error($"Invalid object specified and not inside a class\n");
12911             }
12912             else
12913                Compiler_Error($"No observer specified and not inside a class\n");
12914          }
12915          break;
12916       }
12917    }
12918 }
12919
12920 static void ProcessFunction(FunctionDefinition function)
12921 {
12922    Identifier id = GetDeclId(function.declarator);
12923    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12924    Type type = symbol ? symbol.type : null;
12925    Class oldThisClass = thisClass;
12926    Context oldTopContext = topContext;
12927
12928    yylloc = function.loc;
12929    // Process thisClass
12930
12931    if(type && type.thisClass)
12932    {
12933       Symbol classSym = type.thisClass;
12934       Class _class = type.thisClass.registered;
12935       char className[1024];
12936       char structName[1024];
12937       Declarator funcDecl;
12938       Symbol thisSymbol;
12939
12940       bool typedObject = false;
12941
12942       if(_class && !_class.base)
12943       {
12944          _class = currentClass;
12945          if(_class && !_class.symbol)
12946             _class.symbol = FindClass(_class.fullName);
12947          classSym = _class ? _class.symbol : null;
12948          typedObject = true;
12949       }
12950
12951       thisClass = _class;
12952
12953       if(inCompiler && _class)
12954       {
12955          if(type.kind == functionType)
12956          {
12957             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12958             {
12959                //TypeName param = symbol.type.params.first;
12960                Type param = symbol.type.params.first;
12961                symbol.type.params.Remove(param);
12962                //FreeTypeName(param);
12963                FreeType(param);
12964             }
12965             if(type.classObjectType != classPointer)
12966             {
12967                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12968                symbol.type.staticMethod = true;
12969                symbol.type.thisClass = null;
12970
12971                // HIGH DANGER: VERIFYING THIS...
12972                symbol.type.extraParam = false;
12973             }
12974          }
12975
12976          strcpy(className, "__ecereClass_");
12977          FullClassNameCat(className, _class.fullName, true);
12978
12979          structName[0] = 0;
12980          FullClassNameCat(structName, _class.fullName, false);
12981
12982          // [class] this
12983          funcDecl = GetFuncDecl(function.declarator);
12984          if(funcDecl)
12985          {
12986             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12987             {
12988                TypeName param = funcDecl.function.parameters->first;
12989                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12990                {
12991                   funcDecl.function.parameters->Remove(param);
12992                   FreeTypeName(param);
12993                }
12994             }
12995
12996             if(!function.propertyNoThis)
12997             {
12998                TypeName thisParam = null;
12999
13000                if(type.classObjectType != classPointer)
13001                {
13002                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
13003                   if(!funcDecl.function.parameters)
13004                      funcDecl.function.parameters = MkList();
13005                   funcDecl.function.parameters->Insert(null, thisParam);
13006                }
13007
13008                if(typedObject)
13009                {
13010                   if(type.classObjectType != classPointer)
13011                   {
13012                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
13013                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
13014                   }
13015
13016                   thisParam = TypeName
13017                   {
13018                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
13019                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
13020                   };
13021                   DeclareStruct(curExternal, "ecere::com::Class", false, true);
13022                   funcDecl.function.parameters->Insert(null, thisParam);
13023                }
13024             }
13025          }
13026
13027          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13028          {
13029             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13030             funcDecl = GetFuncDecl(initDecl.declarator);
13031             if(funcDecl)
13032             {
13033                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
13034                {
13035                   TypeName param = funcDecl.function.parameters->first;
13036                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
13037                   {
13038                      funcDecl.function.parameters->Remove(param);
13039                      FreeTypeName(param);
13040                   }
13041                }
13042
13043                if(type.classObjectType != classPointer)
13044                {
13045                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
13046                   {
13047                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
13048
13049                      if(!funcDecl.function.parameters)
13050                         funcDecl.function.parameters = MkList();
13051                      funcDecl.function.parameters->Insert(null, thisParam);
13052                   }
13053                }
13054             }
13055          }
13056       }
13057
13058       // Add this to the context
13059       if(function.body)
13060       {
13061          if(type.classObjectType != classPointer)
13062          {
13063             thisSymbol = Symbol
13064             {
13065                string = CopyString("this");
13066                type = classSym ? MkClassType(classSym.string) : null;
13067             };
13068             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
13069
13070             if(typedObject && thisSymbol.type)
13071             {
13072                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
13073                thisSymbol.type.byReference = type.byReference;
13074                thisSymbol.type.typedByReference = type.byReference;
13075             }
13076          }
13077       }
13078
13079       // Pointer to class data
13080       if(inCompiler && _class && _class.type == normalClass && type.classObjectType != classPointer)
13081       {
13082          DataMember member = null;
13083          {
13084             Class base;
13085             for(base = _class; base && base.type != systemClass; base = base.next)
13086             {
13087                for(member = base.membersAndProperties.first; member; member = member.next)
13088                   if(!member.isProperty)
13089                      break;
13090                if(member)
13091                   break;
13092             }
13093          }
13094          for(member = _class.membersAndProperties.first; member; member = member.next)
13095             if(!member.isProperty)
13096                break;
13097          if(member)
13098          {
13099             char pointerName[1024];
13100
13101             Declaration decl;
13102             Initializer initializer;
13103             Expression exp, bytePtr;
13104
13105             strcpy(pointerName, "__ecerePointer_");
13106             FullClassNameCat(pointerName, _class.fullName, false);
13107             {
13108                char className[1024];
13109                strcpy(className, "__ecereClass_");
13110                FullClassNameCat(className, classSym.string, true);
13111
13112                DeclareClass(curExternal, classSym, className);
13113             }
13114
13115             // ((byte *) this)
13116             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
13117
13118             if(_class.fixed)
13119             {
13120                Expression e;
13121                if(_class.offset && _class.offset == (_class.base.type == noHeadClass ? _class.base.memberOffset : _class.base.structSize))
13122                {
13123                   e = MkExpClassSize(MkSpecifierName(_class.base.fullName));
13124                   ProcessExpressionType(e);
13125                }
13126                else
13127                {
13128                   char string[256];
13129                   sprintf(string, "%d", _class.offset);  // Need Bootstrap Fix
13130                   e = MkExpConstant(string);
13131                }
13132                exp = QBrackets(MkExpOp(bytePtr, '+', e));
13133             }
13134             else
13135             {
13136                // ([bytePtr] + [className]->offset)
13137                exp = QBrackets(MkExpOp(bytePtr, '+',
13138                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
13139             }
13140
13141             // (this ? [exp] : 0)
13142             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
13143             exp.expType = Type
13144             {
13145                refCount = 1;
13146                kind = pointerType;
13147                type = Type { refCount = 1, kind = voidType };
13148             };
13149
13150             if(function.body)
13151             {
13152                yylloc = function.body.loc;
13153                // ([structName] *) [exp]
13154                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13155                initializer = MkInitializerAssignment(
13156                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13157
13158                // [structName] * [pointerName] = [initializer];
13159                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13160
13161                {
13162                   Context prevContext = curContext;
13163                   OldList * list;
13164                   curContext = function.body.compound.context;
13165
13166                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13167                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13168                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13169
13170                   curContext = prevContext;
13171                }
13172
13173                // WHY?
13174                decl.symbol = null;
13175
13176                if(!function.body.compound.declarations)
13177                   function.body.compound.declarations = MkList();
13178                function.body.compound.declarations->Insert(null, decl);
13179             }
13180          }
13181       }
13182
13183
13184       // Loop through the function and replace undeclared identifiers
13185       // which are a member of the class (methods, properties or data)
13186       // by "this.[member]"
13187    }
13188    else
13189       thisClass = null;
13190
13191    if(id)
13192    {
13193       FreeSpecifier(id._class);
13194       id._class = null;
13195
13196       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13197       {
13198          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13199          id = GetDeclId(initDecl.declarator);
13200
13201          FreeSpecifier(id._class);
13202          id._class = null;
13203       }
13204    }
13205    if(function.body)
13206       topContext = function.body.compound.context;
13207    {
13208       FunctionDefinition oldFunction = curFunction;
13209       curFunction = function;
13210       if(function.body)
13211          ProcessStatement(function.body);
13212
13213       // If this is a property set and no firewatchers has been done yet, add one here
13214       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13215       {
13216          Statement prevCompound = curCompound;
13217          Context prevContext = curContext;
13218
13219          Statement fireWatchers = MkFireWatchersStmt(null, null);
13220          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13221          ListAdd(function.body.compound.statements, fireWatchers);
13222
13223          curCompound = function.body;
13224          curContext = function.body.compound.context;
13225
13226          ProcessStatement(fireWatchers);
13227
13228          curContext = prevContext;
13229          curCompound = prevCompound;
13230
13231       }
13232
13233       curFunction = oldFunction;
13234    }
13235
13236    if(function.declarator)
13237    {
13238       ProcessDeclarator(function.declarator, true);
13239    }
13240
13241    topContext = oldTopContext;
13242    thisClass = oldThisClass;
13243 }
13244
13245 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13246 static void ProcessClass(OldList definitions, Symbol symbol)
13247 {
13248    ClassDef def;
13249    External external = curExternal;
13250    Class regClass = symbol ? symbol.registered : null;
13251
13252    // Process all functions
13253    for(def = definitions.first; def; def = def.next)
13254    {
13255       if(def.type == functionClassDef)
13256       {
13257          if(def.function.declarator)
13258             curExternal = def.function.declarator.symbol.pointerExternal;
13259          else
13260             curExternal = external;
13261
13262          ProcessFunction((FunctionDefinition)def.function);
13263       }
13264       else if(def.type == declarationClassDef)
13265       {
13266          if(def.decl.type == instDeclaration)
13267          {
13268             thisClass = regClass;
13269             ProcessInstantiationType(def.decl.inst);
13270             thisClass = null;
13271          }
13272          // Testing this
13273          else
13274          {
13275             Class backThisClass = thisClass;
13276             if(regClass) thisClass = regClass;
13277             ProcessDeclaration(def.decl, symbol ? true : false);
13278             thisClass = backThisClass;
13279          }
13280       }
13281       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13282       {
13283          MemberInit defProperty;
13284
13285          // Add this to the context
13286          Symbol thisSymbol = Symbol
13287          {
13288             string = CopyString("this");
13289             type = regClass ? MkClassType(regClass.fullName) : null;
13290          };
13291          globalContext.symbols.Add((BTNode)thisSymbol);
13292
13293          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13294          {
13295             thisClass = regClass;
13296             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13297             thisClass = null;
13298          }
13299
13300          globalContext.symbols.Remove((BTNode)thisSymbol);
13301          FreeSymbol(thisSymbol);
13302       }
13303       else if(def.type == propertyClassDef && def.propertyDef)
13304       {
13305          PropertyDef prop = def.propertyDef;
13306
13307          // Add this to the context
13308          thisClass = regClass;
13309          if(prop.setStmt)
13310          {
13311             if(regClass)
13312             {
13313                Symbol thisSymbol
13314                {
13315                   string = CopyString("this");
13316                   type = MkClassType(regClass.fullName);
13317                };
13318                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13319             }
13320
13321             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13322             ProcessStatement(prop.setStmt);
13323          }
13324          if(prop.getStmt)
13325          {
13326             if(regClass)
13327             {
13328                Symbol thisSymbol
13329                {
13330                   string = CopyString("this");
13331                   type = MkClassType(regClass.fullName);
13332                };
13333                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13334             }
13335
13336             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13337             ProcessStatement(prop.getStmt);
13338          }
13339          if(prop.issetStmt)
13340          {
13341             if(regClass)
13342             {
13343                Symbol thisSymbol
13344                {
13345                   string = CopyString("this");
13346                   type = MkClassType(regClass.fullName);
13347                };
13348                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13349             }
13350
13351             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13352             ProcessStatement(prop.issetStmt);
13353          }
13354
13355          thisClass = null;
13356       }
13357       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13358       {
13359          PropertyWatch propertyWatch = def.propertyWatch;
13360
13361          thisClass = regClass;
13362          if(propertyWatch.compound)
13363          {
13364             Symbol thisSymbol
13365             {
13366                string = CopyString("this");
13367                type = regClass ? MkClassType(regClass.fullName) : null;
13368             };
13369
13370             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13371
13372             curExternal = null;
13373             ProcessStatement(propertyWatch.compound);
13374          }
13375          thisClass = null;
13376       }
13377    }
13378 }
13379
13380 void DeclareFunctionUtil(External neededBy, const String s)
13381 {
13382    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13383    if(function)
13384    {
13385       char name[1024];
13386       name[0] = 0;
13387       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13388          strcpy(name, "__ecereFunction_");
13389       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13390       DeclareFunction(neededBy, function, name);
13391    }
13392    else if(neededBy)
13393       FindSymbol(s, globalContext, globalContext, false, false);
13394 }
13395
13396 bool reachedPass15;
13397
13398 void ComputeDataTypes()
13399 {
13400    External external;
13401
13402    currentClass = null;
13403
13404    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13405
13406    DeclareStruct(null, "ecere::com::Class", false, true);
13407    DeclareStruct(null, "ecere::com::Instance", false, true);
13408    DeclareStruct(null, "ecere::com::Property", false, true);
13409    DeclareStruct(null, "ecere::com::DataMember", false, true);
13410    DeclareStruct(null, "ecere::com::Method", false, true);
13411    DeclareStruct(null, "ecere::com::SerialBuffer", false, true);
13412    DeclareStruct(null, "ecere::com::ClassTemplateArgument", false, true);
13413
13414    DeclareFunctionUtil(null, "eSystem_New");
13415    DeclareFunctionUtil(null, "eSystem_New0");
13416    DeclareFunctionUtil(null, "eSystem_Renew");
13417    DeclareFunctionUtil(null, "eSystem_Renew0");
13418    DeclareFunctionUtil(null, "eSystem_Delete");
13419    DeclareFunctionUtil(null, "eClass_GetProperty");
13420    DeclareFunctionUtil(null, "eClass_SetProperty");
13421    DeclareFunctionUtil(null, "eInstance_FireSelfWatchers");
13422    DeclareFunctionUtil(null, "eInstance_SetMethod");
13423    DeclareFunctionUtil(null, "eInstance_IncRef");
13424    DeclareFunctionUtil(null, "eInstance_StopWatching");
13425    DeclareFunctionUtil(null, "eInstance_Watch");
13426    DeclareFunctionUtil(null, "eInstance_FireWatchers");
13427    reachedPass15 = true;
13428
13429    for(external = ast->first; external; external = external.next)
13430    {
13431       afterExternal = curExternal = external;
13432       if(external.type == functionExternal)
13433       {
13434          if(memoryGuard)
13435          {
13436             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13437             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13438          }
13439
13440          currentClass = external.function._class;
13441          ProcessFunction(external.function);
13442       }
13443       // There shouldn't be any _class member access here anyways...
13444       else if(external.type == declarationExternal)
13445       {
13446          if(memoryGuard && external.declaration && external.declaration.type == instDeclaration)
13447          {
13448             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13449             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13450          }
13451
13452          currentClass = null;
13453          if(external.declaration)
13454             ProcessDeclaration(external.declaration, true);
13455       }
13456       else if(external.type == classExternal)
13457       {
13458          ClassDefinition _class = external._class;
13459          currentClass = external.symbol.registered;
13460          if(memoryGuard)
13461          {
13462             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13463             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13464          }
13465          if(_class.definitions)
13466          {
13467             ProcessClass(_class.definitions, _class.symbol);
13468          }
13469          if(inCompiler)
13470          {
13471             // Free class data...
13472             ast->Remove(external);
13473             delete external;
13474          }
13475       }
13476       else if(external.type == nameSpaceExternal)
13477       {
13478          thisNameSpace = external.id.string;
13479       }
13480    }
13481    currentClass = null;
13482    thisNameSpace = null;
13483    curExternal = null;
13484 }