compiler/libec: Casts where function pointers are expected
[sdk] / compiler / libec / src / pass15.ec
1 import "ecdefs"
2
3 #define uint _uint
4 #include <stdlib.h>  // For strtoll
5 #undef uint
6
7 // UNTIL IMPLEMENTED IN GRAMMAR
8 #define ACCESS_CLASSDATA(_class, baseClass) \
9    (_class ? ((void *)(((char *)_class.data) + baseClass.offsetClass)) : null)
10
11 #define YYLTYPE Location
12 #include "grammar.h"
13
14 extern OldList * ast;
15 extern int returnCode;
16 extern Expression parsedExpression;
17 extern bool yydebug;
18 public void SetYydebug(bool b) { yydebug = b; }
19 extern bool echoOn;
20
21 void resetScanner();
22
23 // TODO: Reset this to 0 on reinitialization
24 int propWatcherID;
25
26 int expression_yyparse();
27 static Statement curCompound;
28 External curExternal, afterExternal;
29 static Type curSwitchType;
30 static Class currentClass;
31 Class thisClass;
32 public void SetThisClass(Class c) { thisClass = c; } public Class GetThisClass() { return thisClass; }
33 static char * thisNameSpace;
34 /*static */Class containerClass;
35 bool thisClassParams = true;
36
37 uint internalValueCounter;
38
39 #ifdef _DEBUG
40 Time findSymbolTotalTime;
41 #endif
42
43 // WARNING: PrintExpression CONCATENATES to string. Please initialize.
44 /*static */public void PrintExpression(Expression exp, char * string)
45 {
46    //if(inCompiler)
47    {
48       TempFile f { };
49       int count;
50       bool backOutputLineNumbers = outputLineNumbers;
51       outputLineNumbers = false;
52
53       if(exp)
54          OutputExpression(exp, f);
55       f.Seek(0, start);
56       count = strlen(string);
57       count += f.Read(string + count, 1, 1023);
58       string[count] = '\0';
59       delete f;
60
61       outputLineNumbers = backOutputLineNumbers;
62    }
63 }
64
65 Type ProcessTemplateParameterType(TemplateParameter param)
66 {
67    if(param && param.type == TemplateParameterType::type && (param.dataType || param.dataTypeString))
68    {
69       // TOFIX: Will need to free this Type
70       if(!param.baseType)
71       {
72          if(param.dataTypeString)
73             param.baseType = ProcessTypeString(param.dataTypeString, false);
74          else
75             param.baseType = ProcessType(param.dataType.specifiers, param.dataType.decl);
76       }
77       return param.baseType;
78    }
79    return null;
80 }
81
82 bool NeedCast(Type type1, Type type2)
83 {
84    if(!type1 || !type2 || type1.keepCast || type2.keepCast) return true;
85
86    if(type1.kind == templateType && type2.kind == int64Type && type2.passAsTemplate == false)
87    {
88       return false;
89    }
90
91    if(type1.kind == type2.kind)
92    {
93       switch(type1.kind)
94       {
95          case _BoolType:
96          case charType:
97          case shortType:
98          case intType:
99          case int64Type:
100          case intPtrType:
101          case intSizeType:
102             if(type1.passAsTemplate && !type2.passAsTemplate)
103                return true;
104             return type1.isSigned != type2.isSigned;
105          case classType:
106             return type1._class != type2._class;
107          case pointerType:
108             return (type1.type && type2.type && type1.type.constant != type2.type.constant) || NeedCast(type1.type, type2.type);
109          default:
110             return true; //false; ????
111       }
112    }
113    return true;
114 }
115
116 static void ReplaceClassMembers(Expression exp, Class _class)
117 {
118    if(exp.type == identifierExp && exp.identifier)
119    {
120       Identifier id = exp.identifier;
121       Context ctx;
122       Symbol symbol = null;
123       if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
124       {
125          // First, check if the identifier is declared inside the function
126          for(ctx = curContext; ctx != topContext.parent && !symbol; ctx = ctx.parent)
127          {
128             symbol = (Symbol)ctx.symbols.FindString(id.string);
129             if(symbol) break;
130          }
131       }
132
133       // If it is not, check if it is a member of the _class
134       if(!symbol && ((!id._class || (id._class.name && !strcmp(id._class.name, "property"))) || (id.classSym && eClass_IsDerived(_class, id.classSym.registered))))
135       {
136          Property prop = eClass_FindProperty(_class, id.string, privateModule);
137          Method method = null;
138          DataMember member = null;
139          ClassProperty classProp = null;
140          if(!prop)
141          {
142             method = eClass_FindMethod(_class, id.string, privateModule);
143          }
144          if(!prop && !method)
145             member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
146          if(!prop && !method && !member)
147          {
148             classProp = eClass_FindClassProperty(_class, id.string);
149          }
150          if(prop || method || member || classProp)
151          {
152             // Replace by this.[member]
153             exp.type = memberExp;
154             exp.member.member = id;
155             exp.member.memberType = unresolvedMember;
156             exp.member.exp = QMkExpId("this");
157             //exp.member.exp.loc = exp.loc;
158             exp.addedThis = true;
159          }
160          else if(_class && _class.templateParams.first)
161          {
162             Class sClass;
163             for(sClass = _class; sClass; sClass = sClass.base)
164             {
165                if(sClass.templateParams.first)
166                {
167                   ClassTemplateParameter param;
168                   for(param = sClass.templateParams.first; param; param = param.next)
169                   {
170                      if(param.type == expression && !strcmp(param.name, id.string))
171                      {
172                         Expression argExp = GetTemplateArgExpByName(param.name, _class, TemplateParameterType::expression);
173
174                         if(argExp)
175                         {
176                            Declarator decl;
177                            OldList * specs = MkList();
178
179                            FreeIdentifier(exp.member.member);
180
181                            ProcessExpressionType(argExp);
182
183                            decl = SpecDeclFromString(param.dataTypeString, specs, null);
184
185                            exp.expType = ProcessType(specs, decl);
186
187                            // *[expType] *[argExp]
188                            exp.type = bracketsExp;
189                            exp.list = MkListOne(MkExpOp(null, '*',
190                               MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpOp(null, '&', argExp))));
191                         }
192                      }
193                   }
194                }
195             }
196          }
197       }
198    }
199 }
200
201 ////////////////////////////////////////////////////////////////////////
202 // PRINTING ////////////////////////////////////////////////////////////
203 ////////////////////////////////////////////////////////////////////////
204
205 public char * PrintInt(int64 result)
206 {
207    char temp[100];
208    if(result > MAXINT)
209       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
210    else
211       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
212    if(result > MAXINT || result < MININT)
213       strcat(temp, "LL");
214    return CopyString(temp);
215 }
216
217 public char * PrintUInt(uint64 result)
218 {
219    char temp[100];
220    if(result > MAXDWORD)
221       sprintf(temp, FORMAT64HEXLL /*"0x%I64X"*/, result);
222    else if(result > MAXINT)
223       sprintf(temp, FORMAT64HEX /*"0x%I64X"*/, result);
224    else
225       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
226    return CopyString(temp);
227 }
228
229 public char *  PrintInt64(int64 result)
230 {
231    char temp[100];
232    if(result > MAXINT || result < MININT)
233       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
234    else
235       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
236    return CopyString(temp);
237 }
238
239 public char * PrintUInt64(uint64 result)
240 {
241    char temp[100];
242    if(result > MAXDWORD)
243       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
244    else if(result > MAXINT)
245       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
246    else
247       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
248    return CopyString(temp);
249 }
250
251 public char * PrintHexUInt(uint64 result)
252 {
253    char temp[100];
254    if(result > MAXDWORD)
255       sprintf(temp, FORMAT64HEX /*"0x%I64xLL"*/, result);
256    else
257       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
258    if(result > MAXDWORD)
259       strcat(temp, "LL");
260    return CopyString(temp);
261 }
262
263 public char * PrintHexUInt64(uint64 result)
264 {
265    char temp[100];
266    if(result > MAXDWORD)
267       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
268    else
269       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
270    return CopyString(temp);
271 }
272
273 public char * PrintShort(short result)
274 {
275    char temp[100];
276    sprintf(temp, "%d", (unsigned short)result);
277    return CopyString(temp);
278 }
279
280 public char * PrintUShort(unsigned short result)
281 {
282    char temp[100];
283    if(result > 32767)
284       sprintf(temp, "0x%X", (int)result);
285    else
286       sprintf(temp, "%d", (int)result);
287    return CopyString(temp);
288 }
289
290 public char * PrintChar(char result)
291 {
292    char temp[100];
293    if(result > 0 && isprint(result))
294       sprintf(temp, "'%c'", result);
295    else if(result < 0)
296       sprintf(temp, "%d", (int)result);
297    else
298       //sprintf(temp, "%#X", result);
299       sprintf(temp, "0x%X", (unsigned char)result);
300    return CopyString(temp);
301 }
302
303 public char * PrintUChar(unsigned char result)
304 {
305    char temp[100];
306    sprintf(temp, "0x%X", result);
307    return CopyString(temp);
308 }
309
310 public char * PrintFloat(float result)
311 {
312    char temp[350];
313    if(result.isInf)
314    {
315       if(result.signBit)
316          strcpy(temp, "-inf");
317       else
318          strcpy(temp, "inf");
319    }
320    else if(result.isNan)
321    {
322       if(result.signBit)
323          strcpy(temp, "-nan");
324       else
325          strcpy(temp, "nan");
326    }
327    else
328       sprintf(temp, "%.16ff", result);
329    return CopyString(temp);
330 }
331
332 public char * PrintDouble(double result)
333 {
334    char temp[350];
335    if(result.isInf)
336    {
337       if(result.signBit)
338          strcpy(temp, "-inf");
339       else
340          strcpy(temp, "inf");
341    }
342    else if(result.isNan)
343    {
344       if(result.signBit)
345          strcpy(temp, "-nan");
346       else
347          strcpy(temp, "nan");
348    }
349    else
350       sprintf(temp, "%.16f", result);
351    return CopyString(temp);
352 }
353
354 ////////////////////////////////////////////////////////////////////////
355 ////////////////////////////////////////////////////////////////////////
356
357 //public Operand GetOperand(Expression exp);
358
359 #define GETVALUE(name, t) \
360    public bool GetOp##name(Operand op2, t * value2) \
361    {                                                        \
362       if(op2.kind == intType && op2.type.isSigned) *value2 = (t) op2.i; \
363       else if(op2.kind == intType) *value2 = (t) op2.ui;                 \
364       else if(op2.kind == int64Type && op2.type.isSigned) *value2 = (t) op2.i64; \
365       else if(op2.kind == int64Type) *value2 = (t) op2.ui64;                 \
366       else if(op2.kind == intSizeType && op2.type.isSigned) *value2 = (t) op2.i64; \
367       else if(op2.kind == intSizeType) *value2 = (t) op2.ui64; \
368       else if(op2.kind == intPtrType && op2.type.isSigned) *value2 = (t) op2.i64; \
369       else if(op2.kind == intPtrType) *value2 = (t) op2.ui64;                 \
370       else if(op2.kind == shortType && op2.type.isSigned) *value2 = (t) op2.s;   \
371       else if(op2.kind == shortType) *value2 = (t) op2.us;                        \
372       else if(op2.kind == charType && op2.type.isSigned) *value2 = (t) op2.c;    \
373       else if(op2.kind == _BoolType || op2.kind == charType) *value2 = (t) op2.uc; \
374       else if(op2.kind == floatType) *value2 = (t) op2.f;                         \
375       else if(op2.kind == doubleType) *value2 = (t) op2.d;                        \
376       else if(op2.kind == pointerType) *value2 = (t) op2.ui64;                    \
377       else                                                                          \
378          return false;                                                              \
379       return true;                                                                  \
380    } \
381    public bool Get##name(Expression exp, t * value2) \
382    {                                                        \
383       Operand op2 = GetOperand(exp);                        \
384       return GetOp##name(op2, value2); \
385    }
386
387 // To help the debugger currently not preprocessing...
388 #define HELP(x) x
389
390 GETVALUE(Int, HELP(int));
391 GETVALUE(UInt, HELP(unsigned int));
392 GETVALUE(Int64, HELP(int64));
393 GETVALUE(UInt64, HELP(uint64));
394 GETVALUE(IntPtr, HELP(intptr));
395 GETVALUE(UIntPtr, HELP(uintptr));
396 GETVALUE(IntSize, HELP(intsize));
397 GETVALUE(UIntSize, HELP(uintsize));
398 GETVALUE(Short, HELP(short));
399 GETVALUE(UShort, HELP(unsigned short));
400 GETVALUE(Char, HELP(char));
401 GETVALUE(UChar, HELP(unsigned char));
402 GETVALUE(Float, HELP(float));
403 GETVALUE(Double, HELP(double));
404
405 void ComputeExpression(Expression exp);
406
407 void ComputeClassMembers(Class _class, bool isMember)
408 {
409    DataMember member = isMember ? (DataMember) _class : null;
410    Context context = isMember ? null : SetupTemplatesContext(_class);
411    if(member || ((_class.type == bitClass || _class.type == normalClass || _class.type == structClass || _class.type == noHeadClass) &&
412                  (_class.type == bitClass || (!_class.structSize || _class.structSize == _class.offset)) && _class.computeSize))
413    {
414       int unionMemberOffset = 0;
415       int bitFields = 0;
416
417       /*
418       if(!member && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass) && _class.memberOffset && _class.memberOffset > _class.base.structSize)
419          _class.memberOffset = (_class.base && _class.base.type != systemClass) ? _class.base.structSize : 0;
420       */
421
422       if(member)
423       {
424          member.memberOffset = 0;
425          if(targetBits < sizeof(void *) * 8)
426             member.structAlignment = 0;
427       }
428       else if(targetBits < sizeof(void *) * 8)
429          _class.structAlignment = 0;
430
431       // Confusion here: non struct classes seem to have their memberOffset restart at 0 at each hierarchy level
432       if(!member && ((_class.type == normalClass || _class.type == noHeadClass) || (_class.type == structClass && _class.memberOffset && _class.memberOffset > _class.base.structSize)))
433          _class.memberOffset = (_class.base && _class.type == structClass) ? _class.base.structSize : 0;
434
435       if(!member && _class.destructionWatchOffset)
436          _class.memberOffset += sizeof(OldList);
437
438       // To avoid reentrancy...
439       //_class.structSize = -1;
440
441       {
442          DataMember dataMember;
443          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
444          {
445             if(!dataMember.isProperty)
446             {
447                if(dataMember.type == normalMember && dataMember.dataTypeString && !dataMember.dataType)
448                {
449                   dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
450                   /*if(!dataMember.dataType)
451                      dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
452                      */
453                }
454             }
455          }
456       }
457
458       {
459          DataMember dataMember;
460          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
461          {
462             if(!dataMember.isProperty && (dataMember.type != normalMember || dataMember.dataTypeString))
463             {
464                if(!isMember && _class.type == bitClass && dataMember.dataType)
465                {
466                   BitMember bitMember = (BitMember) dataMember;
467                   uint64 mask = 0;
468                   int d;
469
470                   ComputeTypeSize(dataMember.dataType);
471
472                   if(bitMember.pos == -1) bitMember.pos = _class.memberOffset;
473                   if(!bitMember.size) bitMember.size = dataMember.dataType.size * 8;
474
475                   _class.memberOffset = bitMember.pos + bitMember.size;
476                   for(d = 0; d<bitMember.size; d++)
477                   {
478                      if(d)
479                         mask <<= 1;
480                      mask |= 1;
481                   }
482                   bitMember.mask = mask << bitMember.pos;
483                }
484                else if(dataMember.type == normalMember && dataMember.dataType)
485                {
486                   int size;
487                   int alignment = 0;
488
489                   // Prevent infinite recursion
490                   if(dataMember.dataType.kind != classType ||
491                      ((!dataMember.dataType._class || !dataMember.dataType._class.registered || dataMember.dataType._class.registered != _class ||
492                      _class.type != structClass)))
493                      ComputeTypeSize(dataMember.dataType);
494
495                   if(dataMember.dataType.bitFieldCount)
496                   {
497                      bitFields += dataMember.dataType.bitFieldCount;
498                      size = 0;
499                   }
500                   else
501                   {
502                      if(bitFields)
503                      {
504                         int size = (bitFields + 7) / 8;
505
506                         if(isMember)
507                         {
508                            // TESTING THIS PADDING CODE
509                            if(alignment)
510                            {
511                               member.structAlignment = Max(member.structAlignment, alignment);
512
513                               if(member.memberOffset % alignment)
514                                  member.memberOffset += alignment - (member.memberOffset % alignment);
515                            }
516
517                            dataMember.offset = member.memberOffset;
518                            if(member.type == unionMember)
519                               unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
520                            else
521                            {
522                               member.memberOffset += size;
523                            }
524                         }
525                         else
526                         {
527                            // TESTING THIS PADDING CODE
528                            if(alignment)
529                            {
530                               _class.structAlignment = Max(_class.structAlignment, alignment);
531
532                               if(_class.memberOffset % alignment)
533                                  _class.memberOffset += alignment - (_class.memberOffset % alignment);
534                            }
535
536                            dataMember.offset = _class.memberOffset;
537                            _class.memberOffset += size;
538                         }
539                         bitFields = 0;
540                      }
541                      size = dataMember.dataType.size;
542                      alignment = dataMember.dataType.alignment;
543                   }
544
545                   if(isMember)
546                   {
547                      // TESTING THIS PADDING CODE
548                      if(alignment)
549                      {
550                         member.structAlignment = Max(member.structAlignment, alignment);
551
552                         if(member.memberOffset % alignment)
553                            member.memberOffset += alignment - (member.memberOffset % alignment);
554                      }
555
556                      dataMember.offset = member.memberOffset;
557                      if(member.type == unionMember)
558                         unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
559                      else
560                      {
561                         member.memberOffset += size;
562                      }
563                   }
564                   else
565                   {
566                      // TESTING THIS PADDING CODE
567                      if(alignment)
568                      {
569                         _class.structAlignment = Max(_class.structAlignment, alignment);
570
571                         if(_class.memberOffset % alignment)
572                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
573                      }
574
575                      dataMember.offset = _class.memberOffset;
576                      _class.memberOffset += size;
577                   }
578                }
579                else
580                {
581                   int alignment;
582
583                   ComputeClassMembers((Class)dataMember, true);
584                   alignment = dataMember.structAlignment;
585
586                   if(isMember)
587                   {
588                      if(alignment)
589                      {
590                         if(member.memberOffset % alignment)
591                            member.memberOffset += alignment - (member.memberOffset % alignment);
592
593                         member.structAlignment = Max(member.structAlignment, alignment);
594                      }
595                      dataMember.offset = member.memberOffset;
596                      if(member.type == unionMember)
597                         unionMemberOffset = Max(unionMemberOffset, dataMember.memberOffset);
598                      else
599                         member.memberOffset += dataMember.memberOffset;
600                   }
601                   else
602                   {
603                      if(alignment)
604                      {
605                         if(_class.memberOffset % alignment)
606                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
607                         _class.structAlignment = Max(_class.structAlignment, alignment);
608                      }
609                      dataMember.offset = _class.memberOffset;
610                      _class.memberOffset += dataMember.memberOffset;
611                   }
612                }
613             }
614          }
615          if(bitFields)
616          {
617             int alignment = 0;
618             int size = (bitFields + 7) / 8;
619
620             if(isMember)
621             {
622                // TESTING THIS PADDING CODE
623                if(alignment)
624                {
625                   member.structAlignment = Max(member.structAlignment, alignment);
626
627                   if(member.memberOffset % alignment)
628                      member.memberOffset += alignment - (member.memberOffset % alignment);
629                }
630
631                if(member.type == unionMember)
632                   unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
633                else
634                {
635                   member.memberOffset += size;
636                }
637             }
638             else
639             {
640                // TESTING THIS PADDING CODE
641                if(alignment)
642                {
643                   _class.structAlignment = Max(_class.structAlignment, alignment);
644
645                   if(_class.memberOffset % alignment)
646                      _class.memberOffset += alignment - (_class.memberOffset % alignment);
647                }
648                _class.memberOffset += size;
649             }
650             bitFields = 0;
651          }
652       }
653       if(member && member.type == unionMember)
654       {
655          member.memberOffset = unionMemberOffset;
656       }
657
658       if(!isMember)
659       {
660          /*if(_class.type == structClass)
661             _class.size = _class.memberOffset;
662          else
663          */
664
665          if(_class.type != bitClass)
666          {
667             int extra = 0;
668             if(_class.structAlignment)
669             {
670                if(_class.memberOffset % _class.structAlignment)
671                   extra += _class.structAlignment - (_class.memberOffset % _class.structAlignment);
672             }
673             _class.structSize = (_class.base ? (_class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize) : 0) + _class.memberOffset + extra;
674             if(!member)
675             {
676                Property prop;
677                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
678                {
679                   if(prop.isProperty && prop.isWatchable)
680                   {
681                      prop.watcherOffset = _class.structSize;
682                      _class.structSize += sizeof(OldList);
683                   }
684                }
685             }
686
687             // Fix Derivatives
688             {
689                OldLink derivative;
690                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
691                {
692                   Class deriv = derivative.data;
693
694                   if(deriv.computeSize)
695                   {
696                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
697                      deriv.offset = /*_class.offset + */_class.structSize;
698                      deriv.memberOffset = 0;
699                      // ----------------------
700
701                      deriv.structSize = deriv.offset;
702
703                      ComputeClassMembers(deriv, false);
704                   }
705                }
706             }
707          }
708       }
709    }
710    if(context)
711       FinishTemplatesContext(context);
712 }
713
714 public void ComputeModuleClasses(Module module)
715 {
716    Class _class;
717    OldLink subModule;
718
719    for(subModule = module.modules.first; subModule; subModule = subModule.next)
720       ComputeModuleClasses(subModule.data);
721    for(_class = module.classes.first; _class; _class = _class.next)
722       ComputeClassMembers(_class, false);
723 }
724
725
726 public int ComputeTypeSize(Type type)
727 {
728    uint size = type ? type.size : 0;
729    if(!size && type && !type.computing)
730    {
731       type.computing = true;
732       switch(type.kind)
733       {
734          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
735          case charType: type.alignment = size = sizeof(char); break;
736          case intType: type.alignment = size = sizeof(int); break;
737          case int64Type: type.alignment = size = sizeof(int64); break;
738          case intPtrType: type.alignment = size = targetBits / 8; break;
739          case intSizeType: type.alignment = size = targetBits / 8; break;
740          case longType: type.alignment = size = sizeof(long); break;
741          case shortType: type.alignment = size = sizeof(short); break;
742          case floatType: type.alignment = size = sizeof(float); break;
743          case doubleType: type.alignment = size = sizeof(double); break;
744          case classType:
745          {
746             Class _class = type._class ? type._class.registered : null;
747
748             if(_class && _class.type == structClass)
749             {
750                // Ensure all members are properly registered
751                ComputeClassMembers(_class, false);
752                type.alignment = _class.structAlignment;
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                size = type.alignment = targetBits / 8; // sizeof(Instance *);
768             break;
769          }
770          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */break;
771          case arrayType:
772             if(type.arraySizeExp)
773             {
774                ProcessExpressionType(type.arraySizeExp);
775                ComputeExpression(type.arraySizeExp);
776                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType &&
777                   type.arraySizeExp.expType.kind != shortType &&
778                   type.arraySizeExp.expType.kind != charType &&
779                   type.arraySizeExp.expType.kind != longType &&
780                   type.arraySizeExp.expType.kind != int64Type &&
781                   type.arraySizeExp.expType.kind != intSizeType &&
782                   type.arraySizeExp.expType.kind != intPtrType &&
783                   type.arraySizeExp.expType.kind != enumType &&
784                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
785                {
786                   Location oldLoc = yylloc;
787                   // bool isConstant = type.arraySizeExp.isConstant;
788                   char expression[10240];
789                   expression[0] = '\0';
790                   type.arraySizeExp.expType = null;
791                   yylloc = type.arraySizeExp.loc;
792                   if(inCompiler)
793                      PrintExpression(type.arraySizeExp, expression);
794                   Compiler_Error($"Array size not constant int (%s)\n", expression);
795                   yylloc = oldLoc;
796                }
797                GetInt(type.arraySizeExp, &type.arraySize);
798             }
799             else if(type.enumClass)
800             {
801                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
802                {
803                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
804                }
805                else
806                   type.arraySize = 0;
807             }
808             else
809             {
810                // Unimplemented auto size
811                type.arraySize = 0;
812             }
813
814             size = ComputeTypeSize(type.type) * type.arraySize;
815             if(type.type)
816                type.alignment = type.type.alignment;
817
818             break;
819          case structType:
820          {
821             Type member;
822             for(member = type.members.first; member; member = member.next)
823             {
824                uint addSize = ComputeTypeSize(member);
825
826                member.offset = size;
827                if(member.alignment && size % member.alignment)
828                   member.offset += member.alignment - (size % member.alignment);
829                size = member.offset;
830
831                type.alignment = Max(type.alignment, member.alignment);
832                size += addSize;
833             }
834             if(type.alignment && size % type.alignment)
835                size += type.alignment - (size % type.alignment);
836             break;
837          }
838          case unionType:
839          {
840             Type member;
841             for(member = type.members.first; member; member = member.next)
842             {
843                uint addSize = ComputeTypeSize(member);
844
845                member.offset = size;
846                if(member.alignment && size % member.alignment)
847                   member.offset += member.alignment - (size % member.alignment);
848                size = member.offset;
849
850                type.alignment = Max(type.alignment, member.alignment);
851                size = Max(size, addSize);
852             }
853             if(type.alignment && size % type.alignment)
854                size += type.alignment - (size % type.alignment);
855             break;
856          }
857          case templateType:
858          {
859             TemplateParameter param = type.templateParameter;
860             Type baseType = ProcessTemplateParameterType(param);
861             if(baseType)
862             {
863                size = ComputeTypeSize(baseType);
864                type.alignment = baseType.alignment;
865             }
866             else
867                type.alignment = size = sizeof(uint64);
868             break;
869          }
870          case enumType:
871          {
872             type.alignment = size = sizeof(enum { test });
873             break;
874          }
875          case thisClassType:
876          {
877             type.alignment = size = targetBits / 8; //sizeof(void *);
878             break;
879          }
880       }
881       type.size = size;
882       type.computing = false;
883    }
884    return size;
885 }
886
887
888 /*static */int AddMembers(OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
889 {
890    // This function is in need of a major review when implementing private members etc.
891    DataMember topMember = isMember ? (DataMember) _class : null;
892    uint totalSize = 0;
893    uint maxSize = 0;
894    int alignment;
895    uint size;
896    DataMember member;
897    int anonID = 1;
898    Context context = isMember ? null : SetupTemplatesContext(_class);
899    if(addedPadding)
900       *addedPadding = false;
901
902    if(!isMember && _class.base)
903    {
904       maxSize = _class.structSize;
905       //if(_class.base.type != systemClass) // Commented out with new Instance _class
906       {
907          // DANGER: Testing this noHeadClass here...
908          if(_class.type == structClass || _class.type == noHeadClass)
909             /*totalSize = */AddMembers(declarations, _class.base, false, &totalSize, topClass, null);
910          else
911          {
912             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
913             if(maxSize > baseSize)
914                maxSize -= baseSize;
915             else
916                maxSize = 0;
917          }
918       }
919    }
920
921    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
922    {
923       if(!member.isProperty)
924       {
925          switch(member.type)
926          {
927             case normalMember:
928             {
929                if(member.dataTypeString)
930                {
931                   OldList * specs = MkList(), * decls = MkList();
932                   Declarator decl;
933
934                   decl = SpecDeclFromString(member.dataTypeString, specs,
935                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
936                   ListAdd(decls, MkStructDeclarator(decl, null));
937                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
938
939                   if(!member.dataType)
940                      member.dataType = ProcessType(specs, decl);
941
942                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
943
944                   {
945                      Type type = ProcessType(specs, decl);
946                      DeclareType(member.dataType, false, false);
947                      FreeType(type);
948                   }
949                   /*
950                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
951                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
952                      DeclareStruct(member.dataType._class.string, false);
953                   */
954
955                   ComputeTypeSize(member.dataType);
956                   size = member.dataType.size;
957                   alignment = member.dataType.alignment;
958
959                   if(alignment)
960                   {
961                      if(totalSize % alignment)
962                         totalSize += alignment - (totalSize % alignment);
963                   }
964                   totalSize += size;
965                }
966                break;
967             }
968             case unionMember:
969             case structMember:
970             {
971                OldList * specs = MkList(), * list = MkList();
972                char id[100];
973                sprintf(id, "__anon%d", anonID++);
974
975                size = 0;
976                AddMembers(list, (Class)member, true, &size, topClass, null);
977                ListAdd(specs,
978                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
979                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, MkListOne(MkDeclaratorIdentifier(MkIdentifier(id))),null)));
980                alignment = member.structAlignment;
981
982                if(alignment)
983                {
984                   if(totalSize % alignment)
985                      totalSize += alignment - (totalSize % alignment);
986                }
987                totalSize += size;
988                break;
989             }
990          }
991       }
992    }
993    if(retSize)
994    {
995       if(topMember && topMember.type == unionMember)
996          *retSize = Max(*retSize, totalSize);
997       else
998          *retSize += totalSize;
999    }
1000    else if(totalSize < maxSize && _class.type != systemClass)
1001    {
1002       int autoPadding = 0;
1003       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
1004          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
1005       if(totalSize + autoPadding < maxSize)
1006       {
1007          char sizeString[50];
1008          sprintf(sizeString, "%d", maxSize - totalSize);
1009          ListAdd(declarations,
1010             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
1011             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
1012          if(addedPadding)
1013             *addedPadding = true;
1014       }
1015    }
1016    if(context)
1017       FinishTemplatesContext(context);
1018    return topMember ? topMember.memberID : _class.memberID;
1019 }
1020
1021 static int DeclareMembers(Class _class, bool isMember)
1022 {
1023    DataMember topMember = isMember ? (DataMember) _class : null;
1024    DataMember member;
1025    Context context = isMember ? null : SetupTemplatesContext(_class);
1026
1027    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1028       DeclareMembers(_class.base, false);
1029
1030    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1031    {
1032       if(!member.isProperty)
1033       {
1034          switch(member.type)
1035          {
1036             case normalMember:
1037             {
1038                /*
1039                if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
1040                   member.dataType._class.registered && member.dataType._class.registered.type == structClass)
1041                   DeclareStruct(member.dataType._class.string, false);
1042                   */
1043                if(!member.dataType && member.dataTypeString)
1044                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1045                if(member.dataType)
1046                   DeclareType(member.dataType, false, false);
1047                break;
1048             }
1049             case unionMember:
1050             case structMember:
1051             {
1052                DeclareMembers((Class)member, true);
1053                break;
1054             }
1055          }
1056       }
1057    }
1058    if(context)
1059       FinishTemplatesContext(context);
1060
1061    return topMember ? topMember.memberID : _class.memberID;
1062 }
1063
1064 static void IdentifyAnonStructs(OldList/*<ClassDef>*/ *  definitions)
1065 {
1066    ClassDef def;
1067    int anonID = 1;
1068    for(def = definitions->first; def; def = def.next)
1069    {
1070       if(def.type == declarationClassDef)
1071       {
1072          Declaration decl = def.decl;
1073          if(decl && decl.specifiers)
1074          {
1075             Specifier spec;
1076             bool isStruct = false;
1077             for(spec = decl.specifiers->first; spec; spec = spec.next)
1078             {
1079                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1080                {
1081                   if(spec.definitions)
1082                      IdentifyAnonStructs(spec.definitions);
1083                   isStruct = true;
1084                }
1085             }
1086             if(isStruct)
1087             {
1088                Declarator d = null;
1089                if(decl.declarators)
1090                {
1091                   for(d = decl.declarators->first; d; d = d.next)
1092                   {
1093                      Identifier idDecl = GetDeclId(d);
1094                      if(idDecl)
1095                         break;
1096                   }
1097                }
1098                if(!d)
1099                {
1100                   char id[100];
1101                   sprintf(id, "__anon%d", anonID++);
1102                   if(!decl.declarators)
1103                      decl.declarators = MkList();
1104                   ListAdd(decl.declarators, MkDeclaratorIdentifier(MkIdentifier(id)));
1105                }
1106             }
1107          }
1108       }
1109    }
1110 }
1111
1112 void DeclareStruct(const char * name, bool skipNoHead)
1113 {
1114    External external = null;
1115    Symbol classSym = FindClass(name);
1116
1117    if(!inCompiler || !classSym) return;
1118
1119    // We don't need any declaration for bit classes...
1120    if(classSym.registered &&
1121       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1122       return;
1123
1124    /*if(classSym.registered.templateClass)
1125       return DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1126    */
1127
1128    if(classSym.registered && classSym.imported && !classSym.declaredStructSym)
1129    {
1130       // Add typedef struct
1131       Declaration decl;
1132       OldList * specifiers, * declarators;
1133       OldList * declarations = null;
1134       char structName[1024];
1135       Specifier spec = null;
1136       external = (classSym.registered && classSym.registered.type == structClass) ?
1137          classSym.pointerExternal : classSym.structExternal;
1138
1139       // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1140       // Moved this one up because DeclareClass done later will need it
1141
1142       classSym.declaring++;
1143
1144       if(strchr(classSym.string, '<'))
1145       {
1146          if(classSym.registered.templateClass)
1147          {
1148             DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1149             classSym.declaring--;
1150          }
1151          return;
1152       }
1153
1154       //if(!skipNoHead)
1155          DeclareMembers(classSym.registered, false);
1156
1157       structName[0] = 0;
1158       FullClassNameCat(structName, name, false);
1159
1160       if(external && external.declaration && external.declaration.specifiers)
1161       {
1162          for(spec = external.declaration.specifiers->first; spec; spec = spec.next)
1163          {
1164             if(spec.type == structSpecifier || spec.type == unionSpecifier)
1165                break;
1166          }
1167       }
1168
1169       /*if(!external)
1170          external = MkExternalDeclaration(null);*/
1171
1172       if(!skipNoHead && (!spec || !spec.definitions))
1173       {
1174          bool addedPadding = false;
1175          classSym.declaredStructSym = true;
1176
1177          declarations = MkList();
1178
1179          AddMembers(declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1180
1181          //ListAdd(specifiers, MkSpecifier(TYPEDEF));
1182          //ListAdd(specifiers, MkStructOrUnion(structSpecifier, null, declarations));
1183
1184          if(!declarations->count || (declarations->count == 1 && addedPadding))
1185          {
1186             FreeList(declarations, FreeClassDef);
1187             declarations = null;
1188          }
1189       }
1190       if(skipNoHead || declarations)
1191       {
1192          if(spec)
1193          {
1194             if(declarations)
1195                spec.definitions = declarations;
1196
1197             if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1198             {
1199                // TODO: Fix this
1200                //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1201
1202                // DANGER
1203                if(classSym.structExternal)
1204                   ast->Move(classSym.structExternal, curExternal.prev);
1205                ast->Move(classSym.pointerExternal, curExternal.prev);
1206
1207                classSym.id = curExternal.symbol.idCode;
1208                classSym.idCode = curExternal.symbol.idCode;
1209                // external = classSym.pointerExternal;
1210                //external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1211             }
1212          }
1213          else
1214          {
1215             if(!external)
1216                external = MkExternalDeclaration(null);
1217
1218             specifiers = MkList();
1219             declarators = MkList();
1220             ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1221
1222             /*
1223             d = MkDeclaratorIdentifier(MkIdentifier(structName));
1224             ListAdd(declarators, MkInitDeclarator(d, null));
1225             */
1226             external.declaration = decl = MkDeclaration(specifiers, declarators);
1227             if(decl.symbol && !decl.symbol.pointerExternal)
1228                decl.symbol.pointerExternal = external;
1229
1230             // For simple classes, keep the declaration as the external to move around
1231             if(classSym.registered && classSym.registered.type == structClass)
1232             {
1233                char className[1024];
1234                strcpy(className, "__ecereClass_");
1235                FullClassNameCat(className, classSym.string, true);
1236                //MangleClassName(className);
1237
1238                // Testing This
1239                DeclareClass(classSym, className);
1240
1241                external.symbol = classSym;
1242                classSym.pointerExternal = external;
1243                classSym.id = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1244                classSym.idCode = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1245             }
1246             else
1247             {
1248                char className[1024];
1249                strcpy(className, "__ecereClass_");
1250                FullClassNameCat(className, classSym.string, true);
1251                //MangleClassName(className);
1252
1253                // TOFIX: TESTING THIS...
1254                classSym.structExternal = external;
1255                DeclareClass(classSym, className);
1256                external.symbol = classSym;
1257             }
1258
1259             //if(curExternal)
1260                ast->Insert(curExternal ? curExternal.prev : null, external);
1261          }
1262       }
1263
1264       classSym.declaring--;
1265    }
1266    else
1267    {
1268       if(classSym.structExternal && classSym.structExternal.declaration && classSym.structExternal.declaration.specifiers)
1269       {
1270          Specifier spec;
1271          for(spec = classSym.structExternal.declaration.specifiers->first; spec; spec = spec.next)
1272          {
1273             IdentifyAnonStructs(spec.definitions);
1274          }
1275       }
1276
1277       if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1278       {
1279          // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1280          // Moved this one up because DeclareClass done later will need it
1281
1282          // TESTING THIS:
1283          classSym.declaring++;
1284
1285          //if(!skipNoHead)
1286          {
1287             if(classSym.registered)
1288                DeclareMembers(classSym.registered, false);
1289          }
1290
1291          if(classSym.registered && (classSym.registered.type == structClass || classSym.registered.type == noHeadClass))
1292          {
1293             // TODO: Fix this
1294             //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1295
1296             // DANGER
1297             if(classSym.structExternal)
1298                ast->Move(classSym.structExternal, curExternal.prev);
1299             ast->Move(classSym.pointerExternal, curExternal.prev);
1300
1301             classSym.id = curExternal.symbol.idCode;
1302             classSym.idCode = curExternal.symbol.idCode;
1303             // external = classSym.pointerExternal;
1304             // external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1305          }
1306
1307          classSym.declaring--;
1308       }
1309    }
1310    //return external;
1311 }
1312
1313 void DeclareProperty(Property prop, char * setName, char * getName)
1314 {
1315    Symbol symbol = prop.symbol;
1316
1317    strcpy(setName, "__ecereProp_");
1318    FullClassNameCat(setName, prop._class.fullName, false);
1319    strcat(setName, "_Set_");
1320    // strcat(setName, prop.name);
1321    FullClassNameCat(setName, prop.name, true);
1322    //MangleClassName(setName);
1323
1324    strcpy(getName, "__ecereProp_");
1325    FullClassNameCat(getName, prop._class.fullName, false);
1326    strcat(getName, "_Get_");
1327    FullClassNameCat(getName, prop.name, true);
1328    // strcat(getName, prop.name);
1329
1330    // To support "char *" property
1331    //MangleClassName(getName);
1332
1333    if(prop._class.type == structClass)
1334       DeclareStruct(prop._class.fullName, false);
1335
1336    if(!symbol || curExternal.symbol.idCode < symbol.id)
1337    {
1338       bool imported = false;
1339       bool dllImport = false;
1340
1341       if(!symbol || symbol._import)
1342       {
1343          if(!symbol)
1344          {
1345             Symbol classSym;
1346             if(!prop._class.symbol)
1347                prop._class.symbol = FindClass(prop._class.fullName);
1348             classSym = prop._class.symbol;
1349             if(classSym && !classSym._import)
1350             {
1351                ModuleImport module;
1352
1353                if(prop._class.module)
1354                   module = FindModule(prop._class.module);
1355                else
1356                   module = mainModule;
1357
1358                classSym._import = ClassImport
1359                {
1360                   name = CopyString(prop._class.fullName);
1361                   isRemote = prop._class.isRemote;
1362                };
1363                module.classes.Add(classSym._import);
1364             }
1365             symbol = prop.symbol = Symbol { };
1366             symbol._import = (ClassImport)PropertyImport
1367             {
1368                name = CopyString(prop.name);
1369                isVirtual = false; //prop.isVirtual;
1370                hasSet = prop.Set ? true : false;
1371                hasGet = prop.Get ? true : false;
1372             };
1373             if(classSym)
1374                classSym._import.properties.Add(symbol._import);
1375          }
1376          imported = true;
1377          // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1378          if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1379             prop._class.module.importType != staticImport)
1380             dllImport = true;
1381       }
1382
1383       if(!symbol.type)
1384       {
1385          Context context = SetupTemplatesContext(prop._class);
1386          symbol.type = ProcessTypeString(prop.dataTypeString, false);
1387          FinishTemplatesContext(context);
1388       }
1389
1390       // Get
1391       if(prop.Get)
1392       {
1393          if(!symbol.externalGet || symbol.externalGet.type == functionExternal)
1394          {
1395             Declaration decl;
1396             OldList * specifiers, * declarators;
1397             Declarator d;
1398             OldList * params;
1399             Specifier spec;
1400             External external;
1401             Declarator typeDecl;
1402             bool simple = false;
1403
1404             specifiers = MkList();
1405             declarators = MkList();
1406             params = MkList();
1407
1408             ListAdd(params, MkTypeName(MkListOne(MkSpecifierName /*MkClassName*/(prop._class.fullName)),
1409                MkDeclaratorIdentifier(MkIdentifier("this"))));
1410
1411             d = MkDeclaratorIdentifier(MkIdentifier(getName));
1412             //if(imported)
1413             if(dllImport)
1414                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1415
1416             {
1417                Context context = SetupTemplatesContext(prop._class);
1418                typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1419                FinishTemplatesContext(context);
1420             }
1421
1422             // Make sure the simple _class's type is declared
1423             for(spec = specifiers->first; spec; spec = spec.next)
1424             {
1425                if(spec.type == nameSpecifier /*SpecifierClass*/)
1426                {
1427                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1428                   {
1429                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1430                      symbol._class = classSym.registered;
1431                      if(classSym.registered && classSym.registered.type == structClass)
1432                      {
1433                         DeclareStruct(spec.name, false);
1434                         simple = true;
1435                      }
1436                   }
1437                }
1438             }
1439
1440             if(!simple)
1441                d = PlugDeclarator(typeDecl, d);
1442             else
1443             {
1444                ListAdd(params, MkTypeName(specifiers,
1445                   PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1446                specifiers = MkList();
1447             }
1448
1449             d = MkDeclaratorFunction(d, params);
1450
1451             //if(imported)
1452             if(dllImport)
1453                specifiers->Insert(null, MkSpecifier(EXTERN));
1454             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1455                specifiers->Insert(null, MkSpecifier(STATIC));
1456             if(simple)
1457                ListAdd(specifiers, MkSpecifier(VOID));
1458
1459             ListAdd(declarators, MkInitDeclarator(d, null));
1460
1461             decl = MkDeclaration(specifiers, declarators);
1462
1463             external = MkExternalDeclaration(decl);
1464             ast->Insert(curExternal.prev, external);
1465             external.symbol = symbol;
1466             symbol.externalGet = external;
1467
1468             ReplaceThisClassSpecifiers(specifiers, prop._class);
1469
1470             if(typeDecl)
1471                FreeDeclarator(typeDecl);
1472          }
1473          else
1474          {
1475             // Move declaration higher...
1476             ast->Move(symbol.externalGet, curExternal.prev);
1477          }
1478       }
1479
1480       // Set
1481       if(prop.Set)
1482       {
1483          if(!symbol.externalSet || symbol.externalSet.type == functionExternal)
1484          {
1485             Declaration decl;
1486             OldList * specifiers, * declarators;
1487             Declarator d;
1488             OldList * params;
1489             Specifier spec;
1490             External external;
1491             Declarator typeDecl;
1492
1493             declarators = MkList();
1494             params = MkList();
1495
1496             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1497             if(!prop.conversion || prop._class.type == structClass)
1498             {
1499                ListAdd(params, MkTypeName(MkListOne(MkSpecifierName/*MkClassName*/(prop._class.fullName)),
1500                   MkDeclaratorIdentifier(MkIdentifier("this"))));
1501             }
1502
1503             specifiers = MkList();
1504
1505             {
1506                Context context = SetupTemplatesContext(prop._class);
1507                typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1508                   MkDeclaratorIdentifier(MkIdentifier("value")));
1509                FinishTemplatesContext(context);
1510             }
1511             if(!strcmp(prop._class.base.fullName, "eda::Row") || !strcmp(prop._class.base.fullName, "eda::Id"))
1512                specifiers->Insert(null, MkSpecifier(CONST));
1513
1514             ListAdd(params, MkTypeName(specifiers, d));
1515
1516             d = MkDeclaratorIdentifier(MkIdentifier(setName));
1517             //if(imported)
1518             if(dllImport)
1519                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1520             d = MkDeclaratorFunction(d, params);
1521
1522             // Make sure the simple _class's type is declared
1523             for(spec = specifiers->first; spec; spec = spec.next)
1524             {
1525                if(spec.type == nameSpecifier /*SpecifierClass*/)
1526                {
1527                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1528                   {
1529                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1530                      symbol._class = classSym.registered;
1531                      if(classSym.registered && classSym.registered.type == structClass)
1532                         DeclareStruct(spec.name, false);
1533                   }
1534                }
1535             }
1536
1537             ListAdd(declarators, MkInitDeclarator(d, null));
1538
1539             specifiers = MkList();
1540             //if(imported)
1541             if(dllImport)
1542                specifiers->Insert(null, MkSpecifier(EXTERN));
1543             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1544                specifiers->Insert(null, MkSpecifier(STATIC));
1545
1546             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1547             if(!prop.conversion || prop._class.type == structClass)
1548                ListAdd(specifiers, MkSpecifier(VOID));
1549             else
1550                ListAdd(specifiers, MkSpecifierName/*MkClassName*/(prop._class.fullName));
1551
1552             decl = MkDeclaration(specifiers, declarators);
1553
1554             external = MkExternalDeclaration(decl);
1555             ast->Insert(curExternal.prev, external);
1556             external.symbol = symbol;
1557             symbol.externalSet = external;
1558
1559             ReplaceThisClassSpecifiers(specifiers, prop._class);
1560          }
1561          else
1562          {
1563             // Move declaration higher...
1564             ast->Move(symbol.externalSet, curExternal.prev);
1565          }
1566       }
1567
1568       // Property (for Watchers)
1569       if(!symbol.externalPtr)
1570       {
1571          Declaration decl;
1572          External external;
1573          OldList * specifiers = MkList();
1574          char propName[1024];
1575
1576          if(imported)
1577             specifiers->Insert(null, MkSpecifier(EXTERN));
1578          else
1579          {
1580             specifiers->Insert(null, MkSpecifier(STATIC));
1581             specifiers->Add(MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
1582          }
1583
1584          ListAdd(specifiers, MkSpecifierName("Property"));
1585
1586          strcpy(propName, "__ecereProp_");
1587          FullClassNameCat(propName, prop._class.fullName, false);
1588          strcat(propName, "_");
1589          FullClassNameCat(propName, prop.name, true);
1590          // strcat(propName, prop.name);
1591          //MangleClassName(propName);
1592
1593          {
1594             OldList * list = MkList();
1595             ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1596
1597             if(!imported)
1598             {
1599                strcpy(propName, "__ecerePropM_");
1600                FullClassNameCat(propName, prop._class.fullName, false);
1601                strcat(propName, "_");
1602                // strcat(propName, prop.name);
1603                FullClassNameCat(propName, prop.name, true);
1604
1605                //MangleClassName(propName);
1606
1607                ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1608             }
1609             decl = MkDeclaration(specifiers, list);
1610          }
1611
1612          external = MkExternalDeclaration(decl);
1613          ast->Insert(curExternal.prev, external);
1614          external.symbol = symbol;
1615          symbol.externalPtr = external;
1616       }
1617       else
1618       {
1619          // Move declaration higher...
1620          ast->Move(symbol.externalPtr, curExternal.prev);
1621       }
1622
1623       symbol.id = curExternal.symbol.idCode;
1624    }
1625 }
1626
1627 // ***************** EXPRESSION PROCESSING ***************************
1628 public Type Dereference(Type source)
1629 {
1630    Type type = null;
1631    if(source)
1632    {
1633       if(source.kind == pointerType || source.kind == arrayType)
1634       {
1635          type = source.type;
1636          source.type.refCount++;
1637       }
1638       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1639       {
1640          type = Type
1641          {
1642             kind = charType;
1643             refCount = 1;
1644          };
1645       }
1646       // Support dereferencing of no head classes for now...
1647       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1648       {
1649          type = source;
1650          source.refCount++;
1651       }
1652       else
1653          Compiler_Error($"cannot dereference type\n");
1654    }
1655    return type;
1656 }
1657
1658 static Type Reference(Type source)
1659 {
1660    Type type = null;
1661    if(source)
1662    {
1663       type = Type
1664       {
1665          kind = pointerType;
1666          type = source;
1667          refCount = 1;
1668       };
1669       source.refCount++;
1670    }
1671    return type;
1672 }
1673
1674 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1675 {
1676    Identifier ident = member.identifiers ? member.identifiers->first : null;
1677    bool found = false;
1678    DataMember dataMember = null;
1679    Method method = null;
1680    bool freeType = false;
1681
1682    yylloc = member.loc;
1683
1684    if(!ident)
1685    {
1686       if(curMember)
1687       {
1688          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1689          if(*curMember)
1690          {
1691             found = true;
1692             dataMember = *curMember;
1693          }
1694       }
1695    }
1696    else
1697    {
1698       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1699       DataMember _subMemberStack[256];
1700       int _subMemberStackPos = 0;
1701
1702       // FILL MEMBER STACK
1703       if(!thisMember)
1704          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1705       if(thisMember)
1706       {
1707          dataMember = thisMember;
1708          if(curMember && thisMember.memberAccess == publicAccess)
1709          {
1710             *curMember = thisMember;
1711             *curClass = thisMember._class;
1712             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1713             *subMemberStackPos = _subMemberStackPos;
1714          }
1715          found = true;
1716       }
1717       else
1718       {
1719          // Setting a method
1720          method = eClass_FindMethod(_class, ident.string, privateModule);
1721          if(method && method.type == virtualMethod)
1722             found = true;
1723          else
1724             method = null;
1725       }
1726    }
1727
1728    if(found)
1729    {
1730       Type type = null;
1731       if(dataMember)
1732       {
1733          if(!dataMember.dataType && dataMember.dataTypeString)
1734          {
1735             //Context context = SetupTemplatesContext(dataMember._class);
1736             Context context = SetupTemplatesContext(_class);
1737             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1738             FinishTemplatesContext(context);
1739          }
1740          type = dataMember.dataType;
1741       }
1742       else if(method)
1743       {
1744          // This is for destination type...
1745          if(!method.dataType)
1746             ProcessMethodType(method);
1747          //DeclareMethod(method);
1748          // method.dataType = ((Symbol)method.symbol)->type;
1749          type = method.dataType;
1750       }
1751
1752       if(ident && ident.next)
1753       {
1754          for(ident = ident.next; ident && type; ident = ident.next)
1755          {
1756             if(type.kind == classType)
1757             {
1758                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1759                if(!dataMember)
1760                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1761                if(dataMember)
1762                   type = dataMember.dataType;
1763             }
1764             else if(type.kind == structType || type.kind == unionType)
1765             {
1766                Type memberType;
1767                for(memberType = type.members.first; memberType; memberType = memberType.next)
1768                {
1769                   if(!strcmp(memberType.name, ident.string))
1770                   {
1771                      type = memberType;
1772                      break;
1773                   }
1774                }
1775             }
1776          }
1777       }
1778
1779       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1780       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1781       {
1782          int id = 0;
1783          ClassTemplateParameter curParam = null;
1784          Class sClass;
1785          for(sClass = _class; sClass; sClass = sClass.base)
1786          {
1787             id = 0;
1788             if(sClass.templateClass) sClass = sClass.templateClass;
1789             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1790             {
1791                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1792                {
1793                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1794                   {
1795                      if(sClass.templateClass) sClass = sClass.templateClass;
1796                      id += sClass.templateParams.count;
1797                   }
1798                   break;
1799                }
1800                id++;
1801             }
1802             if(curParam) break;
1803          }
1804
1805          if(curParam)
1806          {
1807             ClassTemplateArgument arg = _class.templateArgs[id];
1808             if(arg.dataTypeString)
1809             {
1810                bool constant = type.constant;
1811                // FreeType(type);
1812                type = ProcessTypeString(arg.dataTypeString, false);
1813                if(type.kind == classType && constant) type.constant = true;
1814                else if(type.kind == pointerType)
1815                {
1816                   Type t = type.type;
1817                   while(t.kind == pointerType) t = t.type;
1818                   if(constant) t.constant = constant;
1819                }
1820                freeType = true;
1821                if(type && _class.templateClass)
1822                   type.passAsTemplate = true;
1823                if(type)
1824                {
1825                   // type.refCount++;
1826                   /*if(!exp.destType)
1827                   {
1828                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1829                      exp.destType.refCount++;
1830                   }*/
1831                }
1832             }
1833          }
1834       }
1835       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1836       {
1837          Class expClass = type._class.registered;
1838          Class cClass = null;
1839          int paramCount = 0;
1840          int lastParam = -1;
1841
1842          char templateString[1024];
1843          ClassTemplateParameter param;
1844          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1845          for(cClass = expClass; cClass; cClass = cClass.base)
1846          {
1847             int p = 0;
1848             if(cClass.templateClass) cClass = cClass.templateClass;
1849             for(param = cClass.templateParams.first; param; param = param.next)
1850             {
1851                int id = p;
1852                Class sClass;
1853                ClassTemplateArgument arg;
1854                for(sClass = cClass.base; sClass; sClass = sClass.base)
1855                {
1856                   if(sClass.templateClass) sClass = sClass.templateClass;
1857                   id += sClass.templateParams.count;
1858                }
1859                arg = expClass.templateArgs[id];
1860
1861                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1862                {
1863                   ClassTemplateParameter cParam;
1864                   //int p = numParams - sClass.templateParams.count;
1865                   int p = 0;
1866                   Class nextClass;
1867                   if(sClass.templateClass) sClass = sClass.templateClass;
1868
1869                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1870                   {
1871                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1872                      p += nextClass.templateParams.count;
1873                   }
1874
1875                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1876                   {
1877                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1878                      {
1879                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1880                         {
1881                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1882                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1883                            break;
1884                         }
1885                      }
1886                   }
1887                }
1888
1889                {
1890                   char argument[256];
1891                   argument[0] = '\0';
1892                   /*if(arg.name)
1893                   {
1894                      strcat(argument, arg.name.string);
1895                      strcat(argument, " = ");
1896                   }*/
1897                   switch(param.type)
1898                   {
1899                      case expression:
1900                      {
1901                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1902                         char expString[1024];
1903                         OldList * specs = MkList();
1904                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1905                         Expression exp;
1906                         char * string = PrintHexUInt64(arg.expression.ui64);
1907                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1908                         delete string;
1909
1910                         ProcessExpressionType(exp);
1911                         ComputeExpression(exp);
1912                         expString[0] = '\0';
1913                         PrintExpression(exp, expString);
1914                         strcat(argument, expString);
1915                         //delete exp;
1916                         FreeExpression(exp);
1917                         break;
1918                      }
1919                      case identifier:
1920                      {
1921                         strcat(argument, arg.member.name);
1922                         break;
1923                      }
1924                      case TemplateParameterType::type:
1925                      {
1926                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1927                            strcat(argument, arg.dataTypeString);
1928                         break;
1929                      }
1930                   }
1931                   if(argument[0])
1932                   {
1933                      if(paramCount) strcat(templateString, ", ");
1934                      if(lastParam != p - 1)
1935                      {
1936                         strcat(templateString, param.name);
1937                         strcat(templateString, " = ");
1938                      }
1939                      strcat(templateString, argument);
1940                      paramCount++;
1941                      lastParam = p;
1942                   }
1943                   p++;
1944                }
1945             }
1946          }
1947          {
1948             int len = strlen(templateString);
1949             if(templateString[len-1] == '<')
1950                len--;
1951             else
1952             {
1953                if(templateString[len-1] == '>')
1954                   templateString[len++] = ' ';
1955                templateString[len++] = '>';
1956             }
1957             templateString[len++] = '\0';
1958          }
1959          {
1960             Context context = SetupTemplatesContext(_class);
1961             if(freeType) FreeType(type);
1962             type = ProcessTypeString(templateString, false);
1963             freeType = true;
1964             FinishTemplatesContext(context);
1965          }
1966       }
1967
1968       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1969       {
1970          ProcessExpressionType(member.initializer.exp);
1971          if(!member.initializer.exp.expType)
1972          {
1973             if(inCompiler)
1974             {
1975                char expString[10240];
1976                expString[0] = '\0';
1977                PrintExpression(member.initializer.exp, expString);
1978                ChangeCh(expString, '\n', ' ');
1979                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1980             }
1981          }
1982          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1983          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
1984          {
1985             Compiler_Error($"incompatible instance method %s\n", ident.string);
1986          }
1987       }
1988       else if(member.initializer)
1989       {
1990          /*
1991          FreeType(member.exp.destType);
1992          member.exp.destType = type;
1993          if(member.exp.destType)
1994             member.exp.destType.refCount++;
1995          ProcessExpressionType(member.exp);
1996          */
1997
1998          ProcessInitializer(member.initializer, type);
1999       }
2000       if(freeType) FreeType(type);
2001    }
2002    else
2003    {
2004       if(_class && _class.type == unitClass)
2005       {
2006          if(member.initializer)
2007          {
2008             /*
2009             FreeType(member.exp.destType);
2010             member.exp.destType = MkClassType(_class.fullName);
2011             ProcessExpressionType(member.initializer, type);
2012             */
2013             Type type = MkClassType(_class.fullName);
2014             ProcessInitializer(member.initializer, type);
2015             FreeType(type);
2016          }
2017       }
2018       else
2019       {
2020          if(member.initializer)
2021          {
2022             //ProcessExpressionType(member.exp);
2023             ProcessInitializer(member.initializer, null);
2024          }
2025          if(ident)
2026          {
2027             if(method)
2028             {
2029                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2030             }
2031             else if(_class)
2032             {
2033                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2034                if(inCompiler)
2035                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2036             }
2037          }
2038          else if(_class)
2039             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2040       }
2041    }
2042 }
2043
2044 void ProcessInstantiationType(Instantiation inst)
2045 {
2046    yylloc = inst.loc;
2047    if(inst._class)
2048    {
2049       MembersInit members;
2050       Symbol classSym; // = inst._class.symbol; // FindClass(inst._class.name);
2051       Class _class;
2052
2053       /*if(!inst._class.symbol)
2054          inst._class.symbol = FindClass(inst._class.name);*/
2055       classSym = inst._class.symbol;
2056       _class = classSym ? classSym.registered : null;
2057
2058       // DANGER: Patch for mutex not declaring its struct when not needed
2059       if(!_class || _class.type != noHeadClass)
2060          DeclareStruct(inst._class.name, false); //_class && _class.type == noHeadClass);
2061
2062       afterExternal = afterExternal ? afterExternal : curExternal;
2063
2064       if(inst.exp)
2065          ProcessExpressionType(inst.exp);
2066
2067       inst.isConstant = true;
2068       if(inst.members)
2069       {
2070          DataMember curMember = null;
2071          Class curClass = null;
2072          DataMember subMemberStack[256];
2073          int subMemberStackPos = 0;
2074
2075          for(members = inst.members->first; members; members = members.next)
2076          {
2077             switch(members.type)
2078             {
2079                case methodMembersInit:
2080                {
2081                   char name[1024];
2082                   static uint instMethodID = 0;
2083                   External external = curExternal;
2084                   Context context = curContext;
2085                   Declarator declarator = members.function.declarator;
2086                   Identifier nameID = GetDeclId(declarator);
2087                   char * unmangled = nameID ? nameID.string : null;
2088                   Expression exp;
2089                   External createdExternal = null;
2090
2091                   if(inCompiler)
2092                   {
2093                      char number[16];
2094                      //members.function.dontMangle = true;
2095                      strcpy(name, "__ecereInstMeth_");
2096                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2097                      strcat(name, "_");
2098                      strcat(name, nameID.string);
2099                      strcat(name, "_");
2100                      sprintf(number, "_%08d", instMethodID++);
2101                      strcat(name, number);
2102                      nameID.string = CopyString(name);
2103                   }
2104
2105                   // Do modifications here...
2106                   if(declarator)
2107                   {
2108                      Symbol symbol = declarator.symbol;
2109                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2110
2111                      if(method && method.type == virtualMethod)
2112                      {
2113                         symbol.method = method;
2114                         ProcessMethodType(method);
2115
2116                         if(!symbol.type.thisClass)
2117                         {
2118                            if(method.dataType.thisClass && currentClass &&
2119                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2120                            {
2121                               if(!currentClass.symbol)
2122                                  currentClass.symbol = FindClass(currentClass.fullName);
2123                               symbol.type.thisClass = currentClass.symbol;
2124                            }
2125                            else
2126                            {
2127                               if(!_class.symbol)
2128                                  _class.symbol = FindClass(_class.fullName);
2129                               symbol.type.thisClass = _class.symbol;
2130                            }
2131                         }
2132                         // TESTING THIS HERE:
2133                         DeclareType(symbol.type, true, true);
2134
2135                      }
2136                      else if(classSym)
2137                      {
2138                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2139                            unmangled, classSym.string);
2140                      }
2141                   }
2142
2143                   //declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2144                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2145
2146                   if(nameID)
2147                   {
2148                      FreeSpecifier(nameID._class);
2149                      nameID._class = null;
2150                   }
2151
2152                   if(inCompiler)
2153                   {
2154                      //Type type = declarator.symbol.type;
2155                      External oldExternal = curExternal;
2156
2157                      // *** Commented this out... Any negative impact? Yes: makes double prototypes declarations... Why was it commented out?
2158                      // *** It was commented out for problems such as
2159                      /*
2160                            class VirtualDesktop : Window
2161                            {
2162                               clientSize = Size { };
2163                               Timer timer
2164                               {
2165                                  bool DelayExpired()
2166                                  {
2167                                     clientSize.w;
2168                                     return true;
2169                                  }
2170                               };
2171                            }
2172                      */
2173                      // Commented Out: Good for bet.ec in Poker (Otherwise: obj\bet.c:187: error: `currentBet' undeclared (first use in this function))
2174
2175                      declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2176
2177                      /*
2178                      if(strcmp(declarator.symbol.string, name))
2179                      {
2180                         printf("TOCHECK: Look out for this\n");
2181                         delete declarator.symbol.string;
2182                         declarator.symbol.string = CopyString(name);
2183                      }
2184
2185                      if(!declarator.symbol.parent && globalContext.symbols.root != (BTNode)declarator.symbol)
2186                      {
2187                         printf("TOCHECK: Will this ever be in a list? Yes.\n");
2188                         excludedSymbols->Remove(declarator.symbol);
2189                         globalContext.symbols.Add((BTNode)declarator.symbol);
2190                         if(strstr(declarator.symbol.string), "::")
2191                            globalContext.hasNameSpace = true;
2192
2193                      }
2194                      */
2195
2196                      //curExternal = curExternal.prev;
2197                      //afterExternal = afterExternal->next;
2198
2199                      //ProcessFunction(afterExternal->function);
2200
2201                      //curExternal = afterExternal;
2202                      {
2203                         External externalDecl;
2204                         externalDecl = MkExternalDeclaration(null);
2205                         ast->Insert(oldExternal.prev, externalDecl);
2206
2207                         // Which function does this process?
2208                         if(createdExternal.function)
2209                         {
2210                            ProcessFunction(createdExternal.function);
2211
2212                            //curExternal = oldExternal;
2213
2214                            {
2215                               //Declaration decl = MkDeclaration(members.function.specifiers, MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2216
2217                               Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
2218                                  MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2219
2220                               //externalDecl = MkExternalDeclaration(decl);
2221
2222                               //***** ast->Insert(external.prev, externalDecl);
2223                               //ast->Insert(curExternal.prev, externalDecl);
2224                               externalDecl.declaration = decl;
2225                               if(decl.symbol && !decl.symbol.pointerExternal)
2226                                  decl.symbol.pointerExternal = externalDecl;
2227
2228                               // Trying this out...
2229                               declarator.symbol.pointerExternal = externalDecl;
2230                            }
2231                         }
2232                      }
2233                   }
2234                   else if(declarator)
2235                   {
2236                      curExternal = declarator.symbol.pointerExternal;
2237                      ProcessFunction((FunctionDefinition)members.function);
2238                   }
2239                   curExternal = external;
2240                   curContext = context;
2241
2242                   if(inCompiler)
2243                   {
2244                      FreeClassFunction(members.function);
2245
2246                      // In this pass, turn this into a MemberInitData
2247                      exp = QMkExpId(name);
2248                      members.type = dataMembersInit;
2249                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2250
2251                      delete unmangled;
2252                   }
2253                   break;
2254                }
2255                case dataMembersInit:
2256                {
2257                   if(members.dataMembers && classSym)
2258                   {
2259                      MemberInit member;
2260                      Location oldyyloc = yylloc;
2261                      for(member = members.dataMembers->first; member; member = member.next)
2262                      {
2263                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2264                         if(member.initializer && !member.initializer.isConstant)
2265                            inst.isConstant = false;
2266                      }
2267                      yylloc = oldyyloc;
2268                   }
2269                   break;
2270                }
2271             }
2272          }
2273       }
2274    }
2275 }
2276
2277 static void DeclareType(Type type, bool declarePointers, bool declareParams)
2278 {
2279    // OPTIMIZATIONS: TESTING THIS...
2280    if(inCompiler)
2281    {
2282       if(type.kind == functionType)
2283       {
2284          Type param;
2285          if(declareParams)
2286          {
2287             for(param = type.params.first; param; param = param.next)
2288                DeclareType(param, declarePointers, true);
2289          }
2290          DeclareType(type.returnType, declarePointers, true);
2291       }
2292       else if(type.kind == pointerType && declarePointers)
2293          DeclareType(type.type, declarePointers, false);
2294       else if(type.kind == classType)
2295       {
2296          if(type._class.registered && (type._class.registered.type == structClass || type._class.registered.type == noHeadClass) && !type._class.declaring)
2297             DeclareStruct(type._class.registered.fullName, type._class.registered.type == noHeadClass);
2298       }
2299       else if(type.kind == structType || type.kind == unionType)
2300       {
2301          Type member;
2302          for(member = type.members.first; member; member = member.next)
2303             DeclareType(member, false, false);
2304       }
2305       else if(type.kind == arrayType)
2306          DeclareType(type.arrayType, declarePointers, false);
2307    }
2308 }
2309
2310 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2311 {
2312    ClassTemplateArgument * arg = null;
2313    int id = 0;
2314    ClassTemplateParameter curParam = null;
2315    Class sClass;
2316    for(sClass = _class; sClass; sClass = sClass.base)
2317    {
2318       id = 0;
2319       if(sClass.templateClass) sClass = sClass.templateClass;
2320       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2321       {
2322          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2323          {
2324             for(sClass = sClass.base; sClass; sClass = sClass.base)
2325             {
2326                if(sClass.templateClass) sClass = sClass.templateClass;
2327                id += sClass.templateParams.count;
2328             }
2329             break;
2330          }
2331          id++;
2332       }
2333       if(curParam) break;
2334    }
2335    if(curParam)
2336    {
2337       arg = &_class.templateArgs[id];
2338       if(arg && param.type == type)
2339          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2340    }
2341    return arg;
2342 }
2343
2344 public Context SetupTemplatesContext(Class _class)
2345 {
2346    Context context = PushContext();
2347    context.templateTypesOnly = true;
2348    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2349    {
2350       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2351       for(; param; param = param.next)
2352       {
2353          if(param.type == type && param.identifier)
2354          {
2355             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2356             curContext.templateTypes.Add((BTNode)type);
2357          }
2358       }
2359    }
2360    else if(_class)
2361    {
2362       Class sClass;
2363       for(sClass = _class; sClass; sClass = sClass.base)
2364       {
2365          ClassTemplateParameter p;
2366          for(p = sClass.templateParams.first; p; p = p.next)
2367          {
2368             //OldList * specs = MkList();
2369             //Declarator decl = null;
2370             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2371             if(p.type == type)
2372             {
2373                TemplateParameter param = p.param;
2374                TemplatedType type;
2375                if(!param)
2376                {
2377                   // ADD DATA TYPE HERE...
2378                   p.param = param = TemplateParameter
2379                   {
2380                      identifier = MkIdentifier(p.name), type = p.type,
2381                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2382                   };
2383                }
2384                type = TemplatedType { key = (uintptr)p.name, param = param };
2385                curContext.templateTypes.Add((BTNode)type);
2386             }
2387          }
2388       }
2389    }
2390    return context;
2391 }
2392
2393 public void FinishTemplatesContext(Context context)
2394 {
2395    PopContext(context);
2396    FreeContext(context);
2397    delete context;
2398 }
2399
2400 public void ProcessMethodType(Method method)
2401 {
2402    if(!method.dataType)
2403    {
2404       Context context = SetupTemplatesContext(method._class);
2405
2406       method.dataType = ProcessTypeString(method.dataTypeString, false);
2407
2408       FinishTemplatesContext(context);
2409
2410       if(method.type != virtualMethod && method.dataType)
2411       {
2412          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2413          {
2414             if(!method._class.symbol)
2415                method._class.symbol = FindClass(method._class.fullName);
2416             method.dataType.thisClass = method._class.symbol;
2417          }
2418       }
2419
2420       // Why was this commented out? Working fine without now...
2421
2422       /*
2423       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2424          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2425          */
2426    }
2427
2428    /*
2429    if(type)
2430    {
2431       char * par = strstr(type, "(");
2432       char * classOp = null;
2433       int classOpLen = 0;
2434       if(par)
2435       {
2436          int c;
2437          for(c = par-type-1; c >= 0; c++)
2438          {
2439             if(type[c] == ':' && type[c+1] == ':')
2440             {
2441                classOp = type + c - 1;
2442                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2443                {
2444                   classOp--;
2445                   classOpLen++;
2446                }
2447                break;
2448             }
2449             else if(!isspace(type[c]))
2450                break;
2451          }
2452       }
2453       if(classOp)
2454       {
2455          char temp[1024];
2456          int typeLen = strlen(type);
2457          memcpy(temp, classOp, classOpLen);
2458          temp[classOpLen] = '\0';
2459          if(temp[0])
2460             _class = eSystem_FindClass(module, temp);
2461          else
2462             _class = null;
2463          method.dataTypeString = new char[typeLen - classOpLen + 1];
2464          memcpy(method.dataTypeString, type, classOp - type);
2465          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2466       }
2467       else
2468          method.dataTypeString = type;
2469    }
2470    */
2471 }
2472
2473
2474 public void ProcessPropertyType(Property prop)
2475 {
2476    if(!prop.dataType)
2477    {
2478       Context context = SetupTemplatesContext(prop._class);
2479       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2480       FinishTemplatesContext(context);
2481    }
2482 }
2483
2484 public void DeclareMethod(Method method, const char * name)
2485 {
2486    Symbol symbol = method.symbol;
2487    if(!symbol || (!symbol.pointerExternal && method.type == virtualMethod) || symbol.id > (curExternal ? curExternal.symbol.idCode : -1))
2488    {
2489       //bool imported = false;
2490       bool dllImport = false;
2491
2492       if(!method.dataType)
2493          method.dataType = ProcessTypeString(method.dataTypeString, false);
2494
2495       if(!symbol || symbol._import || method.type == virtualMethod)
2496       {
2497          if(!symbol || method.type == virtualMethod)
2498          {
2499             Symbol classSym;
2500             if(!method._class.symbol)
2501                method._class.symbol = FindClass(method._class.fullName);
2502             classSym = method._class.symbol;
2503             if(!classSym._import)
2504             {
2505                ModuleImport module;
2506
2507                if(method._class.module && method._class.module.name)
2508                   module = FindModule(method._class.module);
2509                else
2510                   module = mainModule;
2511                classSym._import = ClassImport
2512                {
2513                   name = CopyString(method._class.fullName);
2514                   isRemote = method._class.isRemote;
2515                };
2516                module.classes.Add(classSym._import);
2517             }
2518             if(!symbol)
2519             {
2520                symbol = method.symbol = Symbol { };
2521             }
2522             if(!symbol._import)
2523             {
2524                symbol._import = (ClassImport)MethodImport
2525                {
2526                   name = CopyString(method.name);
2527                   isVirtual = method.type == virtualMethod;
2528                };
2529                classSym._import.methods.Add(symbol._import);
2530             }
2531             if(!symbol)
2532             {
2533                // Set the symbol type
2534                /*
2535                if(!type.thisClass)
2536                {
2537                   type.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2538                }
2539                else if(type.thisClass == (void *)-1)
2540                {
2541                   type.thisClass = null;
2542                }
2543                */
2544                // symbol.type = ProcessTypeString(method.dataTypeString, false);
2545                symbol.type = method.dataType;
2546                if(symbol.type) symbol.type.refCount++;
2547             }
2548             /*
2549             if(!method.thisClass || strcmp(method.thisClass, "void"))
2550                symbol.type.params.Insert(null,
2551                   MkClassType(method.thisClass ? method.thisClass : method._class.fullName));
2552             */
2553          }
2554          if(!method.dataType.dllExport)
2555          {
2556             //imported = true;
2557             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2558                dllImport = true;
2559          }
2560       }
2561
2562       /* MOVING THIS UP
2563       if(!method.dataType)
2564          method.dataType = ((Symbol)method.symbol).type;
2565          //ProcessMethodType(method);
2566       */
2567
2568       if(method.type != virtualMethod && method.dataType)
2569          DeclareType(method.dataType, true, true);
2570
2571       if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2572       {
2573          // We need a declaration here :)
2574          Declaration decl;
2575          OldList * specifiers, * declarators;
2576          Declarator d;
2577          Declarator funcDecl;
2578          External external;
2579
2580          specifiers = MkList();
2581          declarators = MkList();
2582
2583          //if(imported)
2584          if(dllImport)
2585             ListAdd(specifiers, MkSpecifier(EXTERN));
2586          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2587             ListAdd(specifiers, MkSpecifier(STATIC));
2588
2589          if(method.type == virtualMethod)
2590          {
2591             ListAdd(specifiers, MkSpecifier(INT));
2592             d = MkDeclaratorIdentifier(MkIdentifier(name));
2593          }
2594          else
2595          {
2596             d = MkDeclaratorIdentifier(MkIdentifier(name));
2597             //if(imported)
2598             if(dllImport)
2599                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2600             {
2601                Context context = SetupTemplatesContext(method._class);
2602                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2603                FinishTemplatesContext(context);
2604             }
2605             funcDecl = GetFuncDecl(d);
2606
2607             if(dllImport)
2608             {
2609                Specifier spec, next;
2610                for(spec = specifiers->first; spec; spec = next)
2611                {
2612                   next = spec.next;
2613                   if(spec.type == extendedSpecifier)
2614                   {
2615                      specifiers->Remove(spec);
2616                      FreeSpecifier(spec);
2617                   }
2618                }
2619             }
2620
2621             // Add this parameter if not a static method
2622             if(method.dataType && !method.dataType.staticMethod)
2623             {
2624                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2625                {
2626                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2627                   TypeName thisParam = MkTypeName(MkListOne(
2628                      MkSpecifierName/*MkClassName*/(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2629                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2630                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2631                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2632
2633                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2634                   {
2635                      TypeName param = funcDecl.function.parameters->first;
2636                      funcDecl.function.parameters->Remove(param);
2637                      FreeTypeName(param);
2638                   }
2639
2640                   if(!funcDecl.function.parameters)
2641                      funcDecl.function.parameters = MkList();
2642                   funcDecl.function.parameters->Insert(null, thisParam);
2643                }
2644             }
2645             // Make sure we don't have empty parameter declarations for static methods...
2646             /*
2647             else if(!funcDecl.function.parameters)
2648             {
2649                funcDecl.function.parameters = MkList();
2650                funcDecl.function.parameters->Insert(null,
2651                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2652             }*/
2653          }
2654          // TESTING THIS:
2655          ProcessDeclarator(d);
2656
2657          ListAdd(declarators, MkInitDeclarator(d, null));
2658
2659          decl = MkDeclaration(specifiers, declarators);
2660
2661          ReplaceThisClassSpecifiers(specifiers, method._class);
2662
2663          // Keep a different symbol for the function definition than the declaration...
2664          if(symbol.pointerExternal)
2665          {
2666             Symbol functionSymbol { };
2667
2668             // Copy symbol
2669             {
2670                *functionSymbol = *symbol;
2671                functionSymbol.string = CopyString(symbol.string);
2672                if(functionSymbol.type)
2673                   functionSymbol.type.refCount++;
2674             }
2675
2676             excludedSymbols->Add(functionSymbol);
2677             symbol.pointerExternal.symbol = functionSymbol;
2678          }
2679          external = MkExternalDeclaration(decl);
2680          if(curExternal)
2681             ast->Insert(curExternal ? curExternal.prev : null, external);
2682          external.symbol = symbol;
2683          symbol.pointerExternal = external;
2684       }
2685       else if(ast)
2686       {
2687          // Move declaration higher...
2688          ast->Move(symbol.pointerExternal, curExternal.prev);
2689       }
2690
2691       symbol.id = curExternal ? curExternal.symbol.idCode : MAXINT;
2692    }
2693 }
2694
2695 char * ReplaceThisClass(Class _class)
2696 {
2697    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2698    {
2699       bool first = true;
2700       int p = 0;
2701       ClassTemplateParameter param;
2702       int lastParam = -1;
2703
2704       char className[1024];
2705       strcpy(className, _class.fullName);
2706       for(param = _class.templateParams.first; param; param = param.next)
2707       {
2708          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2709          {
2710             if(first) strcat(className, "<");
2711             if(!first) strcat(className, ", ");
2712             if(lastParam + 1 != p)
2713             {
2714                strcat(className, param.name);
2715                strcat(className, " = ");
2716             }
2717             strcat(className, param.name);
2718             first = false;
2719             lastParam = p;
2720          }
2721          p++;
2722       }
2723       if(!first)
2724       {
2725          int len = strlen(className);
2726          if(className[len-1] == '>') className[len++] = ' ';
2727          className[len++] = '>';
2728          className[len++] = '\0';
2729       }
2730       return CopyString(className);
2731    }
2732    else
2733       return CopyString(_class.fullName);
2734 }
2735
2736 Type ReplaceThisClassType(Class _class)
2737 {
2738    Type type;
2739    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2740    {
2741       bool first = true;
2742       int p = 0;
2743       ClassTemplateParameter param;
2744       int lastParam = -1;
2745       char className[1024];
2746       strcpy(className, _class.fullName);
2747
2748       for(param = _class.templateParams.first; param; param = param.next)
2749       {
2750          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2751          {
2752             if(first) strcat(className, "<");
2753             if(!first) strcat(className, ", ");
2754             if(lastParam + 1 != p)
2755             {
2756                strcat(className, param.name);
2757                strcat(className, " = ");
2758             }
2759             strcat(className, param.name);
2760             first = false;
2761             lastParam = p;
2762          }
2763          p++;
2764       }
2765       if(!first)
2766       {
2767          int len = strlen(className);
2768          if(className[len-1] == '>') className[len++] = ' ';
2769          className[len++] = '>';
2770          className[len++] = '\0';
2771       }
2772       type = MkClassType(className);
2773       //type = ProcessTypeString(className, false);
2774    }
2775    else
2776    {
2777       type = MkClassType(_class.fullName);
2778       //type = ProcessTypeString(_class.fullName, false);
2779    }
2780    //type.wasThisClass = true;
2781    return type;
2782 }
2783
2784 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2785 {
2786    if(specs != null && _class)
2787    {
2788       Specifier spec;
2789       for(spec = specs.first; spec; spec = spec.next)
2790       {
2791          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2792          {
2793             spec.type = nameSpecifier;
2794             spec.name = ReplaceThisClass(_class);
2795             spec.symbol = FindClass(spec.name); //_class.symbol;
2796          }
2797       }
2798    }
2799 }
2800
2801 // Returns imported or not
2802 bool DeclareFunction(GlobalFunction function, char * name)
2803 {
2804    Symbol symbol = function.symbol;
2805    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2806    {
2807       bool imported = false;
2808       bool dllImport = false;
2809
2810       if(!function.dataType)
2811       {
2812          function.dataType = ProcessTypeString(function.dataTypeString, false);
2813          if(!function.dataType.thisClass)
2814             function.dataType.staticMethod = true;
2815       }
2816
2817       if(inCompiler)
2818       {
2819          if(!symbol)
2820          {
2821             ModuleImport module = FindModule(function.module);
2822             // WARNING: This is not added anywhere...
2823             symbol = function.symbol = Symbol {  };
2824
2825             if(module.name)
2826             {
2827                if(!function.dataType.dllExport)
2828                {
2829                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2830                   module.functions.Add(symbol._import);
2831                }
2832             }
2833             // Set the symbol type
2834             {
2835                symbol.type = ProcessTypeString(function.dataTypeString, false);
2836                if(!symbol.type.thisClass)
2837                   symbol.type.staticMethod = true;
2838             }
2839          }
2840          imported = symbol._import ? true : false;
2841          if(imported && function.module != privateModule && function.module.importType != staticImport)
2842             dllImport = true;
2843       }
2844
2845       DeclareType(function.dataType, true, true);
2846
2847       if(inCompiler)
2848       {
2849          if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2850          {
2851             // We need a declaration here :)
2852             Declaration decl;
2853             OldList * specifiers, * declarators;
2854             Declarator d;
2855             Declarator funcDecl;
2856             External external;
2857
2858             specifiers = MkList();
2859             declarators = MkList();
2860
2861             //if(imported)
2862                ListAdd(specifiers, MkSpecifier(EXTERN));
2863             /*
2864             else
2865                ListAdd(specifiers, MkSpecifier(STATIC));
2866             */
2867
2868             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2869             //if(imported)
2870             if(dllImport)
2871                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2872
2873             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2874             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2875             if(function.module.importType == staticImport)
2876             {
2877                Specifier spec;
2878                for(spec = specifiers->first; spec; spec = spec.next)
2879                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2880                   {
2881                      specifiers->Remove(spec);
2882                      FreeSpecifier(spec);
2883                      break;
2884                   }
2885             }
2886
2887             funcDecl = GetFuncDecl(d);
2888
2889             // Make sure we don't have empty parameter declarations for static methods...
2890             if(funcDecl && !funcDecl.function.parameters)
2891             {
2892                funcDecl.function.parameters = MkList();
2893                funcDecl.function.parameters->Insert(null,
2894                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2895             }
2896
2897             ListAdd(declarators, MkInitDeclarator(d, null));
2898
2899             {
2900                Context oldCtx = curContext;
2901                curContext = globalContext;
2902                decl = MkDeclaration(specifiers, declarators);
2903                curContext = oldCtx;
2904             }
2905
2906             // Keep a different symbol for the function definition than the declaration...
2907             if(symbol.pointerExternal)
2908             {
2909                Symbol functionSymbol { };
2910                // Copy symbol
2911                {
2912                   *functionSymbol = *symbol;
2913                   functionSymbol.string = CopyString(symbol.string);
2914                   if(functionSymbol.type)
2915                      functionSymbol.type.refCount++;
2916                }
2917
2918                excludedSymbols->Add(functionSymbol);
2919
2920                symbol.pointerExternal.symbol = functionSymbol;
2921             }
2922             external = MkExternalDeclaration(decl);
2923             if(curExternal)
2924                ast->Insert(curExternal.prev, external);
2925             external.symbol = symbol;
2926             symbol.pointerExternal = external;
2927          }
2928          else
2929          {
2930             // Move declaration higher...
2931             ast->Move(symbol.pointerExternal, curExternal.prev);
2932          }
2933
2934          if(curExternal)
2935             symbol.id = curExternal.symbol.idCode;
2936       }
2937    }
2938    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2939 }
2940
2941 void DeclareGlobalData(GlobalData data)
2942 {
2943    Symbol symbol = data.symbol;
2944    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2945    {
2946       if(inCompiler)
2947       {
2948          if(!symbol)
2949             symbol = data.symbol = Symbol { };
2950       }
2951       if(!data.dataType)
2952          data.dataType = ProcessTypeString(data.dataTypeString, false);
2953       DeclareType(data.dataType, true, true);
2954       if(inCompiler)
2955       {
2956          if(!symbol.pointerExternal)
2957          {
2958             // We need a declaration here :)
2959             Declaration decl;
2960             OldList * specifiers, * declarators;
2961             Declarator d;
2962             External external;
2963
2964             specifiers = MkList();
2965             declarators = MkList();
2966
2967             ListAdd(specifiers, MkSpecifier(EXTERN));
2968             d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2969             d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2970
2971             ListAdd(declarators, MkInitDeclarator(d, null));
2972
2973             decl = MkDeclaration(specifiers, declarators);
2974             external = MkExternalDeclaration(decl);
2975             if(curExternal)
2976                ast->Insert(curExternal.prev, external);
2977             external.symbol = symbol;
2978             symbol.pointerExternal = external;
2979          }
2980          else
2981          {
2982             // Move declaration higher...
2983             ast->Move(symbol.pointerExternal, curExternal.prev);
2984          }
2985
2986          if(curExternal)
2987             symbol.id = curExternal.symbol.idCode;
2988       }
2989    }
2990 }
2991
2992 class Conversion : struct
2993 {
2994    Conversion prev, next;
2995    Property convert;
2996    bool isGet;
2997    Type resultType;
2998 };
2999
3000 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
3001 {
3002    bool status = true;
3003    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
3004       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
3005    {
3006       Class sourceClass = source.kind == classType ? source._class.registered : null;
3007       Class destClass = dest.kind == classType ? dest._class.registered : null;
3008       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
3009          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
3010       {
3011          Type sourceType = source, destType = dest;
3012          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
3013          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
3014          if(!destType.constant && sourceType.constant)
3015          {
3016             status = false;
3017             if(warn)
3018                Compiler_Warning($"discarding const qualifier\n");
3019          }
3020       }
3021    }
3022    return status;
3023 }
3024
3025 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
3026                        bool isConversionExploration, bool warnConst)
3027 {
3028    if(source && dest)
3029    {
3030       if(warnConst)
3031          CheckConstCompatibility(source, dest, true);
3032       // Property convert;
3033
3034       if(source.kind == templateType && dest.kind != templateType)
3035       {
3036          Type type = ProcessTemplateParameterType(source.templateParameter);
3037          if(type) source = type;
3038       }
3039
3040       if(dest.kind == templateType && source.kind != templateType)
3041       {
3042          Type type = ProcessTemplateParameterType(dest.templateParameter);
3043          if(type) dest = type;
3044       }
3045
3046       if(dest.classObjectType == typedObject && dest.kind != functionType)
3047       {
3048          if(source.classObjectType != anyObject)
3049             return true;
3050          else
3051          {
3052             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
3053             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
3054             {
3055                return true;
3056             }
3057          }
3058       }
3059       else
3060       {
3061          if(source.kind != functionType && source.classObjectType == anyObject)
3062             return true;
3063          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
3064             return true;
3065       }
3066
3067       if((dest.kind == structType && source.kind == structType) ||
3068          (dest.kind == unionType && source.kind == unionType))
3069       {
3070          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
3071              (source.members.first && source.members.first == dest.members.first))
3072             return true;
3073       }
3074
3075       if(dest.kind == ellipsisType && source.kind != voidType)
3076          return true;
3077
3078       if(dest.kind == pointerType && dest.type.kind == voidType &&
3079          ((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))
3080          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
3081
3082          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
3083
3084          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
3085          return true;
3086       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
3087          ((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))
3088          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
3089          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
3090
3091          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
3092          return true;
3093
3094       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
3095       {
3096          if(source._class.registered && source._class.registered.type == unitClass)
3097          {
3098             if(conversions != null)
3099             {
3100                if(source._class.registered == dest._class.registered)
3101                   return true;
3102             }
3103             else
3104             {
3105                Class sourceBase, destBase;
3106                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
3107                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
3108                if(sourceBase == destBase)
3109                   return true;
3110             }
3111          }
3112          // Don't match enum inheriting from other enum if resolving enumeration values
3113          // TESTING: !dest.classObjectType
3114          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
3115             (enumBaseType ||
3116                (!source._class.registered || source._class.registered.type != enumClass) ||
3117                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
3118             return true;
3119          else
3120          {
3121             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
3122             if(enumBaseType &&
3123                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
3124                ((source._class && source._class.registered && source._class.registered.type != enumClass) || source.kind == classType)) // Added this here for a base enum to be acceptable for a derived enum (#139)
3125             {
3126                if(eClass_IsDerived(dest._class.registered, source._class.registered))
3127                {
3128                   return true;
3129                }
3130             }
3131          }
3132       }
3133
3134       // JUST ADDED THIS...
3135       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
3136          return true;
3137
3138       if(doConversion)
3139       {
3140          // Just added this for Straight conversion of ColorAlpha => Color
3141          if(source.kind == classType)
3142          {
3143             Class _class;
3144             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3145             {
3146                Property convert;
3147                for(convert = _class.conversions.first; convert; convert = convert.next)
3148                {
3149                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3150                   {
3151                      Conversion after = (conversions != null) ? conversions.last : null;
3152
3153                      if(!convert.dataType)
3154                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3155                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
3156                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3157                         MatchTypes(convert.dataType, dest, conversions, null, null,
3158                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
3159                               convert.dataType.kind == classType, false, true, warnConst))
3160                      {
3161                         if(!conversions && !convert.Get)
3162                            return true;
3163                         else if(conversions != null)
3164                         {
3165                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3166                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3167                               (dest.kind != classType || dest._class.registered != _class.base))
3168                               return true;
3169                            else
3170                            {
3171                               Conversion conv { convert = convert, isGet = true };
3172                               // conversions.Add(conv);
3173                               conversions.Insert(after, conv);
3174
3175                               return true;
3176                            }
3177                         }
3178                      }
3179                   }
3180                }
3181             }
3182          }
3183
3184          // MOVING THIS??
3185
3186          if(dest.kind == classType)
3187          {
3188             Class _class;
3189             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3190             {
3191                Property convert;
3192                for(convert = _class.conversions.first; convert; convert = convert.next)
3193                {
3194                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3195                   {
3196                      Type constType = null;
3197                      bool success = false;
3198                      // Conversion after = (conversions != null) ? conversions.last : null;
3199
3200                      if(!convert.dataType)
3201                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3202
3203                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3204                      {
3205                         Type ptrType { };
3206                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3207                         CopyTypeInto(ptrType, convert.dataType.type);
3208                         ptrType.constant = true;
3209                      }
3210
3211                      // Just added this equality check to prevent recursion.... Make it safer?
3212                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3213                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3214                      {
3215                         if(!conversions && !convert.Set)
3216                            success = true;
3217                         else if(conversions != null)
3218                         {
3219                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3220                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3221                               (source.kind != classType || source._class.registered != _class.base))
3222                               success = true;
3223                            else
3224                            {
3225                               // *** Testing this! ***
3226                               Conversion conv { convert = convert };
3227                               conversions.Add(conv);
3228                               //conversions.Insert(after, conv);
3229                               success = true;
3230                            }
3231                         }
3232                      }
3233                      if(constType)
3234                         FreeType(constType);
3235                      if(success)
3236                         return true;
3237                   }
3238                }
3239             }
3240             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3241             {
3242                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3243                   (source.kind != classType || source._class.registered.type != structClass))
3244                   return true;
3245             }*/
3246
3247             // TESTING THIS... IS THIS OK??
3248             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3249             {
3250                if(!dest._class.registered.dataType)
3251                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3252                // Only support this for classes...
3253                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3254                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3255                {
3256                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3257                   {
3258                      return true;
3259                   }
3260                }
3261             }
3262          }
3263
3264          // Moved this lower
3265          if(source.kind == classType)
3266          {
3267             Class _class;
3268             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3269             {
3270                Property convert;
3271                for(convert = _class.conversions.first; convert; convert = convert.next)
3272                {
3273                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3274                   {
3275                      Conversion after = (conversions != null) ? conversions.last : null;
3276
3277                      if(!convert.dataType)
3278                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3279                      if(convert.dataType != source &&
3280                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3281                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3282                      {
3283                         if(!conversions && !convert.Get)
3284                            return true;
3285                         else if(conversions != null)
3286                         {
3287                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3288                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3289                               (dest.kind != classType || dest._class.registered != _class.base))
3290                               return true;
3291                            else
3292                            {
3293                               Conversion conv { convert = convert, isGet = true };
3294
3295                               // conversions.Add(conv);
3296                               conversions.Insert(after, conv);
3297                               return true;
3298                            }
3299                         }
3300                      }
3301                   }
3302                }
3303             }
3304
3305             // TESTING THIS... IS THIS OK??
3306             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3307             {
3308                if(!source._class.registered.dataType)
3309                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3310                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3311                {
3312                   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))
3313                      return true;
3314                   // For bool to be accepted by byte, short, etc.
3315                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3316                      return true;
3317                }
3318             }
3319          }
3320       }
3321
3322       if(source.kind == classType || source.kind == subClassType)
3323          ;
3324       else if(dest.kind == source.kind &&
3325          (dest.kind != structType && dest.kind != unionType &&
3326           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3327           return true;
3328       // RECENTLY ADDED THESE
3329       else if(dest.kind == doubleType && source.kind == floatType)
3330          return true;
3331       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3332          return true;
3333       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3334          return true;
3335       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3336          return true;
3337       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3338          return true;
3339       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3340          return true;
3341       else if(source.kind == enumType &&
3342          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3343           return true;
3344       else if(dest.kind == enumType && !isConversionExploration &&
3345          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3346           return true;
3347       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3348               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3349       {
3350          Type paramSource, paramDest;
3351
3352          if(dest.kind == methodType)
3353             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3354          if(source.kind == methodType)
3355             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3356
3357          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3358          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3359          if(dest.kind == methodType)
3360             dest = dest.method.dataType;
3361          if(source.kind == methodType)
3362             source = source.method.dataType;
3363
3364          paramSource = source.params.first;
3365          if(paramSource && paramSource.kind == voidType) paramSource = null;
3366          paramDest = dest.params.first;
3367          if(paramDest && paramDest.kind == voidType) paramDest = null;
3368
3369
3370          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3371             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3372          {
3373             // Source thisClass must be derived from destination thisClass
3374             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3375                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3376             {
3377                if(paramDest && paramDest.kind == classType)
3378                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3379                else
3380                   Compiler_Error($"method class should not take an object\n");
3381                return false;
3382             }
3383             paramDest = paramDest.next;
3384          }
3385          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3386          {
3387             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3388             {
3389                if(dest.thisClass)
3390                {
3391                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3392                   {
3393                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3394                      return false;
3395                   }
3396                }
3397                else
3398                {
3399                   // THIS WAS BACKWARDS:
3400                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3401                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3402                   {
3403                      if(owningClassDest)
3404                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3405                      else
3406                         Compiler_Error($"overriding class expected to be derived from method class\n");
3407                      return false;
3408                   }
3409                }
3410                paramSource = paramSource.next;
3411             }
3412             else
3413             {
3414                if(dest.thisClass)
3415                {
3416                   // Source thisClass must be derived from destination thisClass
3417                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3418                   {
3419                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3420                      return false;
3421                   }
3422                }
3423                else
3424                {
3425                   // THIS WAS BACKWARDS TOO??
3426                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3427                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3428                   {
3429                      //if(owningClass)
3430                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3431                      //else
3432                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3433                      return false;
3434                   }
3435                }
3436             }
3437          }
3438
3439
3440          // Source return type must be derived from destination return type
3441          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3442          {
3443             Compiler_Warning($"incompatible return type for function\n");
3444             return false;
3445          }
3446          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3447          else
3448             CheckConstCompatibility(dest.returnType, source.returnType, true);
3449
3450          // Check parameters
3451
3452          for(; paramDest; paramDest = paramDest.next)
3453          {
3454             if(!paramSource)
3455             {
3456                //Compiler_Warning($"not enough parameters\n");
3457                Compiler_Error($"not enough parameters\n");
3458                return false;
3459             }
3460             {
3461                Type paramDestType = paramDest;
3462                Type paramSourceType = paramSource;
3463                Type type = paramDestType;
3464
3465                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3466                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3467                   paramSource.kind != templateType)
3468                {
3469                   int id = 0;
3470                   ClassTemplateParameter curParam = null;
3471                   Class sClass;
3472                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3473                   {
3474                      id = 0;
3475                      if(sClass.templateClass) sClass = sClass.templateClass;
3476                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3477                      {
3478                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3479                         {
3480                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3481                            {
3482                               if(sClass.templateClass) sClass = sClass.templateClass;
3483                               id += sClass.templateParams.count;
3484                            }
3485                            break;
3486                         }
3487                         id++;
3488                      }
3489                      if(curParam) break;
3490                   }
3491
3492                   if(curParam)
3493                   {
3494                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3495                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3496                   }
3497                }
3498
3499                // paramDest must be derived from paramSource
3500                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3501                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3502                {
3503                   char type[1024];
3504                   type[0] = 0;
3505                   PrintType(paramDest, type, false, true);
3506                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3507
3508                   if(paramDestType != paramDest)
3509                      FreeType(paramDestType);
3510                   return false;
3511                }
3512                if(paramDestType != paramDest)
3513                   FreeType(paramDestType);
3514             }
3515
3516             paramSource = paramSource.next;
3517          }
3518          if(paramSource)
3519          {
3520             Compiler_Error($"too many parameters\n");
3521             return false;
3522          }
3523          return true;
3524       }
3525       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3526       {
3527          return true;
3528       }
3529       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3530          (source.kind == arrayType || source.kind == pointerType))
3531       {
3532          if(MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3533             return true;
3534       }
3535    }
3536    return false;
3537 }
3538
3539 static void FreeConvert(Conversion convert)
3540 {
3541    if(convert.resultType)
3542       FreeType(convert.resultType);
3543 }
3544
3545 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3546                               char * string, OldList conversions)
3547 {
3548    BTNamedLink link;
3549
3550    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3551    {
3552       Class _class = link.data;
3553       if(_class.type == enumClass)
3554       {
3555          OldList converts { };
3556          Type type { };
3557          type.kind = classType;
3558
3559          if(!_class.symbol)
3560             _class.symbol = FindClass(_class.fullName);
3561          type._class = _class.symbol;
3562
3563          if(MatchTypes(type, dest, &converts, null, null, true, false, false, false, false))
3564          {
3565             NamedLink64 value;
3566             Class enumClass = eSystem_FindClass(privateModule, "enum");
3567             if(enumClass)
3568             {
3569                Class baseClass;
3570                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3571                {
3572                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3573                   for(value = e.values.first; value; value = value.next)
3574                   {
3575                      if(!strcmp(value.name, string))
3576                         break;
3577                   }
3578                   if(value)
3579                   {
3580                      FreeExpContents(sourceExp);
3581                      FreeType(sourceExp.expType);
3582
3583                      sourceExp.isConstant = true;
3584                      sourceExp.expType = MkClassType(baseClass.fullName);
3585                      //if(inCompiler)
3586                      {
3587                         char constant[256];
3588                         sourceExp.type = constantExp;
3589                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3590                            sprintf(constant, FORMAT64D, value.data);
3591                         else
3592                            sprintf(constant, FORMAT64HEXLL, value.data);
3593                         sourceExp.constant = CopyString(constant);
3594                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3595                      }
3596
3597                      while(converts.first)
3598                      {
3599                         Conversion convert = converts.first;
3600                         converts.Remove(convert);
3601                         conversions.Add(convert);
3602                      }
3603                      delete type;
3604                      return true;
3605                   }
3606                }
3607             }
3608          }
3609          if(converts.first)
3610             converts.Free(FreeConvert);
3611          delete type;
3612       }
3613    }
3614    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3615       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3616          return true;
3617    return false;
3618 }
3619
3620 public bool ModuleVisibility(Module searchIn, Module searchFor)
3621 {
3622    SubModule subModule;
3623
3624    if(searchFor == searchIn)
3625       return true;
3626
3627    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3628    {
3629       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3630       {
3631          if(ModuleVisibility(subModule.module, searchFor))
3632             return true;
3633       }
3634    }
3635    return false;
3636 }
3637
3638 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3639 {
3640    Module module;
3641
3642    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3643       return true;
3644    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3645       return true;
3646    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3647       return true;
3648
3649    for(module = mainModule.application.allModules.first; module; module = module.next)
3650    {
3651       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3652          return true;
3653    }
3654    return false;
3655 }
3656
3657 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3658 {
3659    Type source;
3660    Type realDest = dest;
3661    Type backupSourceExpType = null;
3662    Expression computedExp = sourceExp;
3663    dest.refCount++;
3664
3665    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3666       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3667    {
3668       computedExp = CopyExpression(sourceExp);        // Keep the original expression, but compute for checking enum ranges
3669       ComputeExpression(computedExp /*sourceExp*/);
3670    }
3671
3672    source = sourceExp.expType;
3673
3674    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3675    {
3676       if(computedExp != sourceExp)
3677       {
3678          FreeExpression(computedExp);
3679          computedExp = sourceExp;
3680       }
3681       FreeType(dest);
3682       return true;
3683    }
3684
3685    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3686    {
3687        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3688        {
3689           Class sourceBase, destBase;
3690           for(sourceBase = source._class.registered;
3691               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3692               sourceBase = sourceBase.base);
3693           for(destBase = dest._class.registered;
3694               destBase && destBase.base && destBase.base.type != systemClass;
3695               destBase = destBase.base);
3696           //if(source._class.registered == dest._class.registered)
3697           if(sourceBase == destBase)
3698           {
3699             if(computedExp != sourceExp)
3700             {
3701                FreeExpression(computedExp);
3702                computedExp = sourceExp;
3703             }
3704             FreeType(dest);
3705             return true;
3706          }
3707       }
3708    }
3709
3710    if(source)
3711    {
3712       OldList * specs;
3713       bool flag = false;
3714       int64 value = MAXINT;
3715
3716       source.refCount++;
3717
3718       if(computedExp.type == constantExp)
3719       {
3720          if(source.isSigned)
3721             value = strtoll(computedExp.constant, null, 0);
3722          else
3723             value = strtoull(computedExp.constant, null, 0);
3724       }
3725       else if(computedExp.type == opExp && sourceExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3726       {
3727          if(source.isSigned)
3728             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3729          else
3730             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3731       }
3732       if(computedExp != sourceExp)
3733       {
3734          FreeExpression(computedExp);
3735          computedExp = sourceExp;
3736       }
3737
3738       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3739          !strcmp(source._class.registered.fullName, "ecere::com::unichar"))
3740       {
3741          FreeType(source);
3742          source = Type { kind = intType, isSigned = false, refCount = 1 };
3743       }
3744
3745       if(dest.kind == classType)
3746       {
3747          Class _class = dest._class ? dest._class.registered : null;
3748
3749          if(_class && _class.type == unitClass)
3750          {
3751             if(source.kind != classType)
3752             {
3753                Type tempType { };
3754                Type tempDest, tempSource;
3755
3756                for(; _class.base.type != systemClass; _class = _class.base);
3757                tempSource = dest;
3758                tempDest = tempType;
3759
3760                tempType.kind = classType;
3761                if(!_class.symbol)
3762                   _class.symbol = FindClass(_class.fullName);
3763
3764                tempType._class = _class.symbol;
3765                tempType.truth = dest.truth;
3766                if(tempType._class)
3767                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3768
3769                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3770                backupSourceExpType = sourceExp.expType;
3771                sourceExp.expType = dest; dest.refCount++;
3772                //sourceExp.expType = MkClassType(_class.fullName);
3773                flag = true;
3774
3775                delete tempType;
3776             }
3777          }
3778
3779
3780          // Why wasn't there something like this?
3781          if(_class && _class.type == bitClass && source.kind != classType)
3782          {
3783             if(!dest._class.registered.dataType)
3784                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3785             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3786             {
3787                FreeType(source);
3788                FreeType(sourceExp.expType);
3789                source = sourceExp.expType = MkClassType(dest._class.string);
3790                source.refCount++;
3791
3792                //source.kind = classType;
3793                //source._class = dest._class;
3794             }
3795          }
3796
3797          // Adding two enumerations
3798          /*
3799          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3800          {
3801             if(!source._class.registered.dataType)
3802                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3803             if(!dest._class.registered.dataType)
3804                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3805
3806             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3807             {
3808                FreeType(source);
3809                source = sourceExp.expType = MkClassType(dest._class.string);
3810                source.refCount++;
3811
3812                //source.kind = classType;
3813                //source._class = dest._class;
3814             }
3815          }*/
3816
3817          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3818          {
3819             OldList * specs = MkList();
3820             Declarator decl;
3821             char string[1024];
3822
3823             ReadString(string, sourceExp.string);
3824             decl = SpecDeclFromString(string, specs, null);
3825
3826             FreeExpContents(sourceExp);
3827             FreeType(sourceExp.expType);
3828
3829             sourceExp.type = classExp;
3830             sourceExp._classExp.specifiers = specs;
3831             sourceExp._classExp.decl = decl;
3832             sourceExp.expType = dest;
3833             dest.refCount++;
3834
3835             FreeType(source);
3836             FreeType(dest);
3837             if(backupSourceExpType) FreeType(backupSourceExpType);
3838             return true;
3839          }
3840       }
3841       else if(source.kind == classType)
3842       {
3843          Class _class = source._class ? source._class.registered : null;
3844
3845          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || /*_class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3846          {
3847             /*
3848             if(dest.kind != classType)
3849             {
3850                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3851                if(!source._class.registered.dataType)
3852                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3853
3854                FreeType(dest);
3855                dest = MkClassType(source._class.string);
3856                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3857                //   dest = MkClassType(source._class.string);
3858             }
3859             */
3860
3861             if(dest.kind != classType)
3862             {
3863                Type tempType { };
3864                Type tempDest, tempSource;
3865
3866                if(!source._class.registered.dataType)
3867                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3868
3869                for(; _class.base.type != systemClass; _class = _class.base);
3870                tempDest = source;
3871                tempSource = tempType;
3872                tempType.kind = classType;
3873                tempType._class = FindClass(_class.fullName);
3874                tempType.truth = source.truth;
3875                tempType.classObjectType = source.classObjectType;
3876
3877                if(tempType._class)
3878                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3879
3880                // PUT THIS BACK TESTING UNITS?
3881                if(conversions.last)
3882                {
3883                   ((Conversion)(conversions.last)).resultType = dest;
3884                   dest.refCount++;
3885                }
3886
3887                FreeType(sourceExp.expType);
3888                sourceExp.expType = MkClassType(_class.fullName);
3889                sourceExp.expType.truth = source.truth;
3890                sourceExp.expType.classObjectType = source.classObjectType;
3891
3892                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3893
3894                if(!sourceExp.destType)
3895                {
3896                   FreeType(sourceExp.destType);
3897                   sourceExp.destType = sourceExp.expType;
3898                   if(sourceExp.expType)
3899                      sourceExp.expType.refCount++;
3900                }
3901                //flag = true;
3902                //source = _class.dataType;
3903
3904
3905                // TOCHECK: TESTING THIS NEW CODE
3906                if(!_class.dataType)
3907                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3908                FreeType(dest);
3909                dest = MkClassType(source._class.string);
3910                dest.truth = source.truth;
3911                dest.classObjectType = source.classObjectType;
3912
3913                FreeType(source);
3914                source = _class.dataType;
3915                source.refCount++;
3916
3917                delete tempType;
3918             }
3919          }
3920       }
3921
3922       if(!flag)
3923       {
3924          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3925          {
3926             FreeType(source);
3927             FreeType(dest);
3928             return true;
3929          }
3930       }
3931
3932       // Implicit Casts
3933       /*
3934       if(source.kind == classType)
3935       {
3936          Class _class = source._class.registered;
3937          if(_class.type == unitClass)
3938          {
3939             if(!_class.dataType)
3940                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3941             source = _class.dataType;
3942          }
3943       }*/
3944
3945       if(dest.kind == classType)
3946       {
3947          Class _class = dest._class ? dest._class.registered : null;
3948          bool fittingValue = false;
3949          if(_class && _class.type == enumClass)
3950          {
3951             Class enumClass = eSystem_FindClass(privateModule, "enum");
3952             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3953             if(c && value >= 0 && value <= c.largest)
3954                fittingValue = true;
3955          }
3956
3957          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3958             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3959          {
3960             if(_class.type == normalClass || _class.type == noHeadClass)
3961             {
3962                Expression newExp { };
3963                *newExp = *sourceExp;
3964                if(sourceExp.destType) sourceExp.destType.refCount++;
3965                if(sourceExp.expType)  sourceExp.expType.refCount++;
3966                sourceExp.type = castExp;
3967                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3968                sourceExp.cast.exp = newExp;
3969                FreeType(sourceExp.expType);
3970                sourceExp.expType = null;
3971                ProcessExpressionType(sourceExp);
3972
3973                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3974                if(!inCompiler)
3975                {
3976                   FreeType(sourceExp.expType);
3977                   sourceExp.expType = dest;
3978                }
3979
3980                FreeType(source);
3981                if(inCompiler) FreeType(dest);
3982
3983                if(backupSourceExpType) FreeType(backupSourceExpType);
3984                return true;
3985             }
3986
3987             if(!_class.dataType)
3988                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3989             FreeType(dest);
3990             dest = _class.dataType;
3991             dest.refCount++;
3992          }
3993
3994          // Accept lower precision types for units, since we want to keep the unit type
3995          if(dest.kind == doubleType &&
3996             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3997              source.kind == charType || source.kind == _BoolType))
3998          {
3999             specs = MkListOne(MkSpecifier(DOUBLE));
4000          }
4001          else if(dest.kind == floatType &&
4002             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
4003             source.kind == _BoolType || source.kind == doubleType))
4004          {
4005             specs = MkListOne(MkSpecifier(FLOAT));
4006          }
4007          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
4008             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
4009          {
4010             specs = MkList();
4011             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4012             ListAdd(specs, MkSpecifier(INT64));
4013          }
4014          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
4015             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
4016          {
4017             specs = MkList();
4018             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4019             ListAdd(specs, MkSpecifier(INT));
4020          }
4021          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
4022             source.kind == floatType || source.kind == doubleType))
4023          {
4024             specs = MkList();
4025             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4026             ListAdd(specs, MkSpecifier(SHORT));
4027          }
4028          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
4029             source.kind == floatType || source.kind == doubleType))
4030          {
4031             specs = MkList();
4032             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4033             ListAdd(specs, MkSpecifier(CHAR));
4034          }
4035          else
4036          {
4037             FreeType(source);
4038             FreeType(dest);
4039             if(backupSourceExpType)
4040             {
4041                // Failed to convert: revert previous exp type
4042                if(sourceExp.expType) FreeType(sourceExp.expType);
4043                sourceExp.expType = backupSourceExpType;
4044             }
4045             return false;
4046          }
4047       }
4048       else if(dest.kind == doubleType &&
4049          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
4050           source.kind == _BoolType || source.kind == charType))
4051       {
4052          specs = MkListOne(MkSpecifier(DOUBLE));
4053       }
4054       else if(dest.kind == floatType &&
4055          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
4056       {
4057          specs = MkListOne(MkSpecifier(FLOAT));
4058       }
4059       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
4060          (value == 1 || value == 0))
4061       {
4062          specs = MkList();
4063          ListAdd(specs, MkSpecifier(BOOL));
4064       }
4065       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
4066          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
4067       {
4068          specs = MkList();
4069          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4070          ListAdd(specs, MkSpecifier(CHAR));
4071       }
4072       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
4073          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
4074       {
4075          specs = MkList();
4076          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4077          ListAdd(specs, MkSpecifier(SHORT));
4078       }
4079       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
4080       {
4081          specs = MkList();
4082          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4083          ListAdd(specs, MkSpecifier(INT));
4084       }
4085       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
4086       {
4087          specs = MkList();
4088          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4089          ListAdd(specs, MkSpecifier(INT64));
4090       }
4091       else if(dest.kind == enumType &&
4092          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
4093       {
4094          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
4095       }
4096       else
4097       {
4098          FreeType(source);
4099          FreeType(dest);
4100          if(backupSourceExpType)
4101          {
4102             // Failed to convert: revert previous exp type
4103             if(sourceExp.expType) FreeType(sourceExp.expType);
4104             sourceExp.expType = backupSourceExpType;
4105          }
4106          return false;
4107       }
4108
4109       if(!flag && !sourceExp.opDestType)
4110       {
4111          Expression newExp { };
4112          *newExp = *sourceExp;
4113          newExp.prev = null;
4114          newExp.next = null;
4115          if(sourceExp.destType) sourceExp.destType.refCount++;
4116          if(sourceExp.expType)  sourceExp.expType.refCount++;
4117
4118          sourceExp.type = castExp;
4119          if(realDest.kind == classType)
4120          {
4121             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
4122             FreeList(specs, FreeSpecifier);
4123          }
4124          else
4125             sourceExp.cast.typeName = MkTypeName(specs, null);
4126          if(newExp.type == opExp)
4127          {
4128             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
4129          }
4130          else
4131             sourceExp.cast.exp = newExp;
4132
4133          FreeType(sourceExp.expType);
4134          sourceExp.expType = null;
4135          ProcessExpressionType(sourceExp);
4136       }
4137       else
4138          FreeList(specs, FreeSpecifier);
4139
4140       FreeType(dest);
4141       FreeType(source);
4142       if(backupSourceExpType) FreeType(backupSourceExpType);
4143
4144       return true;
4145    }
4146    else
4147    {
4148       if(computedExp != sourceExp)
4149       {
4150          FreeExpression(computedExp);
4151          computedExp = sourceExp;
4152       }
4153
4154       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4155       if(sourceExp.type == identifierExp)
4156       {
4157          Identifier id = sourceExp.identifier;
4158          if(dest.kind == classType)
4159          {
4160             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4161             {
4162                Class _class = dest._class.registered;
4163                Class enumClass = eSystem_FindClass(privateModule, "enum");
4164                if(enumClass)
4165                {
4166                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4167                   {
4168                      NamedLink64 value;
4169                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4170                      for(value = e.values.first; value; value = value.next)
4171                      {
4172                         if(!strcmp(value.name, id.string))
4173                            break;
4174                      }
4175                      if(value)
4176                      {
4177                         FreeExpContents(sourceExp);
4178                         FreeType(sourceExp.expType);
4179
4180                         sourceExp.isConstant = true;
4181                         sourceExp.expType = MkClassType(_class.fullName);
4182                         //if(inCompiler)
4183                         {
4184                            sourceExp.type = constantExp;
4185                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4186                               sourceExp.constant = PrintInt64(value.data);
4187                            else
4188                               sourceExp.constant = PrintUInt64(value.data);
4189                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4190                         }
4191                         FreeType(dest);
4192                         return true;
4193                      }
4194                   }
4195                }
4196             }
4197          }
4198
4199          // Loop through all enum classes
4200          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4201          {
4202             FreeType(dest);
4203             return true;
4204          }
4205       }
4206       FreeType(dest);
4207    }
4208    return false;
4209 }
4210
4211 #define TERTIARY(o, name, m, t, p) \
4212    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4213    {                                                              \
4214       exp.type = constantExp;                                    \
4215       exp.string = p(op1.m ? op2.m : op3.m);                     \
4216       if(!exp.expType) \
4217          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4218       return true;                                                \
4219    }
4220
4221 #define BINARY(o, name, m, t, p) \
4222    static bool name(Expression exp, Operand op1, Operand op2)   \
4223    {                                                              \
4224       t value2 = op2.m;                                           \
4225       exp.type = constantExp;                                    \
4226       exp.string = p((t)(op1.m o value2));                     \
4227       if(!exp.expType) \
4228          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4229       return true;                                                \
4230    }
4231
4232 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4233    static bool name(Expression exp, Operand op1, Operand op2)   \
4234    {                                                              \
4235       t value2 = op2.m;                                           \
4236       exp.type = constantExp;                                    \
4237       exp.string = p(value2 ? (op1.m o value2) : 0);             \
4238       if(!exp.expType) \
4239          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4240       return true;                                                \
4241    }
4242
4243 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4244    static bool name(Expression exp, Operand op1, Operand op2)   \
4245    {                                                              \
4246       t value2 = op2.m;                                           \
4247       exp.type = constantExp;                                    \
4248       exp.string = p(op1.m o value2);             \
4249       if(!exp.expType) \
4250          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4251       return true;                                                \
4252    }
4253
4254 #define UNARY(o, name, m, t, p) \
4255    static bool name(Expression exp, Operand op1)                \
4256    {                                                              \
4257       exp.type = constantExp;                                    \
4258       exp.string = p((t)(o op1.m));                                   \
4259       if(!exp.expType) \
4260          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4261       return true;                                                \
4262    }
4263
4264 #define OPERATOR_ALL(macro, o, name) \
4265    macro(o, Int##name, i, int, PrintInt) \
4266    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4267    macro(o, Int64##name, i64, int64, PrintInt64) \
4268    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4269    macro(o, Short##name, s, short, PrintShort) \
4270    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4271    macro(o, Char##name, c, char, PrintChar) \
4272    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4273    macro(o, Float##name, f, float, PrintFloat) \
4274    macro(o, Double##name, d, double, PrintDouble)
4275
4276 #define OPERATOR_INTTYPES(macro, o, name) \
4277    macro(o, Int##name, i, int, PrintInt) \
4278    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4279    macro(o, Int64##name, i64, int64, PrintInt64) \
4280    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4281    macro(o, Short##name, s, short, PrintShort) \
4282    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4283    macro(o, Char##name, c, char, PrintChar) \
4284    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4285
4286 #define OPERATOR_REALTYPES(macro, o, name) \
4287    macro(o, Float##name, f, float, PrintFloat) \
4288    macro(o, Double##name, d, double, PrintDouble)
4289
4290 // binary arithmetic
4291 OPERATOR_ALL(BINARY, +, Add)
4292 OPERATOR_ALL(BINARY, -, Sub)
4293 OPERATOR_ALL(BINARY, *, Mul)
4294 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4295 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4296 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4297
4298 // unary arithmetic
4299 OPERATOR_ALL(UNARY, -, Neg)
4300
4301 // unary arithmetic increment and decrement
4302 OPERATOR_ALL(UNARY, ++, Inc)
4303 OPERATOR_ALL(UNARY, --, Dec)
4304
4305 // binary arithmetic assignment
4306 OPERATOR_ALL(BINARY, =, Asign)
4307 OPERATOR_ALL(BINARY, +=, AddAsign)
4308 OPERATOR_ALL(BINARY, -=, SubAsign)
4309 OPERATOR_ALL(BINARY, *=, MulAsign)
4310 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4311 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4312 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4313
4314 // binary bitwise
4315 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4316 OPERATOR_INTTYPES(BINARY, |, BitOr)
4317 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4318 OPERATOR_INTTYPES(BINARY, <<, LShift)
4319 OPERATOR_INTTYPES(BINARY, >>, RShift)
4320
4321 // unary bitwise
4322 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4323
4324 // binary bitwise assignment
4325 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4326 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4327 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4328 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4329 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4330
4331 // unary logical negation
4332 OPERATOR_INTTYPES(UNARY, !, Not)
4333
4334 // binary logical equality
4335 OPERATOR_ALL(BINARY, ==, Equ)
4336 OPERATOR_ALL(BINARY, !=, Nqu)
4337
4338 // binary logical
4339 OPERATOR_ALL(BINARY, &&, And)
4340 OPERATOR_ALL(BINARY, ||, Or)
4341
4342 // binary logical relational
4343 OPERATOR_ALL(BINARY, >, Grt)
4344 OPERATOR_ALL(BINARY, <, Sma)
4345 OPERATOR_ALL(BINARY, >=, GrtEqu)
4346 OPERATOR_ALL(BINARY, <=, SmaEqu)
4347
4348 // tertiary condition operator
4349 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4350
4351 //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
4352 #define OPERATOR_TABLE_ALL(name, type) \
4353     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4354                           type##Neg, \
4355                           type##Inc, type##Dec, \
4356                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4357                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4358                           type##BitNot, \
4359                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4360                           type##Not, \
4361                           type##Equ, type##Nqu, \
4362                           type##And, type##Or, \
4363                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4364                         }; \
4365
4366 #define OPERATOR_TABLE_INTTYPES(name, type) \
4367     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4368                           type##Neg, \
4369                           type##Inc, type##Dec, \
4370                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4371                           null, null, null, null, null, \
4372                           null, \
4373                           null, null, null, null, null, \
4374                           null, \
4375                           type##Equ, type##Nqu, \
4376                           type##And, type##Or, \
4377                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4378                         }; \
4379
4380 OPERATOR_TABLE_ALL(int, Int)
4381 OPERATOR_TABLE_ALL(uint, UInt)
4382 OPERATOR_TABLE_ALL(int64, Int64)
4383 OPERATOR_TABLE_ALL(uint64, UInt64)
4384 OPERATOR_TABLE_ALL(short, Short)
4385 OPERATOR_TABLE_ALL(ushort, UShort)
4386 OPERATOR_TABLE_INTTYPES(float, Float)
4387 OPERATOR_TABLE_INTTYPES(double, Double)
4388 OPERATOR_TABLE_ALL(char, Char)
4389 OPERATOR_TABLE_ALL(uchar, UChar)
4390
4391 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4392 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4393 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4394 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4395 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4396 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4397 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4398 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4399
4400 public void ReadString(char * output,  char * string)
4401 {
4402    int len = strlen(string);
4403    int c,d = 0;
4404    bool quoted = false, escaped = false;
4405    for(c = 0; c<len; c++)
4406    {
4407       char ch = string[c];
4408       if(escaped)
4409       {
4410          switch(ch)
4411          {
4412             case 'n': output[d] = '\n'; break;
4413             case 't': output[d] = '\t'; break;
4414             case 'a': output[d] = '\a'; break;
4415             case 'b': output[d] = '\b'; break;
4416             case 'f': output[d] = '\f'; break;
4417             case 'r': output[d] = '\r'; break;
4418             case 'v': output[d] = '\v'; break;
4419             case '\\': output[d] = '\\'; break;
4420             case '\"': output[d] = '\"'; break;
4421             case '\'': output[d] = '\''; break;
4422             default: output[d] = ch;
4423          }
4424          d++;
4425          escaped = false;
4426       }
4427       else
4428       {
4429          if(ch == '\"')
4430             quoted ^= true;
4431          else if(quoted)
4432          {
4433             if(ch == '\\')
4434                escaped = true;
4435             else
4436                output[d++] = ch;
4437          }
4438       }
4439    }
4440    output[d] = '\0';
4441 }
4442
4443 // String Unescape Copy
4444
4445 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4446 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4447 public int UnescapeString(char * d, char * s, int len)
4448 {
4449    int j = 0, k = 0;
4450    char ch;
4451    while(j < len && (ch = s[j]))
4452    {
4453       switch(ch)
4454       {
4455          case '\\':
4456             switch((ch = s[++j]))
4457             {
4458                case 'n': d[k] = '\n'; break;
4459                case 't': d[k] = '\t'; break;
4460                case 'a': d[k] = '\a'; break;
4461                case 'b': d[k] = '\b'; break;
4462                case 'f': d[k] = '\f'; break;
4463                case 'r': d[k] = '\r'; break;
4464                case 'v': d[k] = '\v'; break;
4465                case '\\': d[k] = '\\'; break;
4466                case '\"': d[k] = '\"'; break;
4467                case '\'': d[k] = '\''; break;
4468                default: d[k] = '\\'; d[k] = ch;
4469             }
4470             break;
4471          default:
4472             d[k] = ch;
4473       }
4474       j++, k++;
4475    }
4476    d[k] = '\0';
4477    return k;
4478 }
4479
4480 public char * OffsetEscapedString(char * s, int len, int offset)
4481 {
4482    char ch;
4483    int j = 0, k = 0;
4484    while(j < len && k < offset && (ch = s[j]))
4485    {
4486       if(ch == '\\') ++j;
4487       j++, k++;
4488    }
4489    return (k == offset) ? s + j : null;
4490 }
4491
4492 public Operand GetOperand(Expression exp)
4493 {
4494    Operand op { };
4495    Type type = exp.expType;
4496    if(type)
4497    {
4498       while(type.kind == classType &&
4499          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4500       {
4501          if(!type._class.registered.dataType)
4502             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4503          type = type._class.registered.dataType;
4504
4505       }
4506       if(exp.type == stringExp && op.kind == pointerType)
4507       {
4508          op.ui64 = (uint64)exp.string;
4509          op.kind = pointerType;
4510          op.ops = uint64Ops;
4511       }
4512       else if(exp.isConstant && exp.type == constantExp)
4513       {
4514          op.kind = type.kind;
4515          op.type = type;
4516
4517          switch(op.kind)
4518          {
4519             case _BoolType:
4520             case charType:
4521             {
4522                if(exp.constant[0] == '\'')
4523                {
4524                   op.c = exp.constant[1];
4525                   op.ops = charOps;
4526                }
4527                else if(type.isSigned)
4528                {
4529                   op.c = (char)strtol(exp.constant, null, 0);
4530                   op.ops = charOps;
4531                }
4532                else
4533                {
4534                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4535                   op.ops = ucharOps;
4536                }
4537                break;
4538             }
4539             case shortType:
4540                if(type.isSigned)
4541                {
4542                   op.s = (short)strtol(exp.constant, null, 0);
4543                   op.ops = shortOps;
4544                }
4545                else
4546                {
4547                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4548                   op.ops = ushortOps;
4549                }
4550                break;
4551             case intType:
4552             case longType:
4553                if(type.isSigned)
4554                {
4555                   op.i = (int)strtol(exp.constant, null, 0);
4556                   op.ops = intOps;
4557                }
4558                else
4559                {
4560                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4561                   op.ops = uintOps;
4562                }
4563                op.kind = intType;
4564                break;
4565             case int64Type:
4566                if(type.isSigned)
4567                {
4568                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4569                   op.ops = int64Ops;
4570                }
4571                else
4572                {
4573                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4574                   op.ops = uint64Ops;
4575                }
4576                op.kind = int64Type;
4577                break;
4578             case intPtrType:
4579                if(type.isSigned)
4580                {
4581                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4582                   op.ops = int64Ops;
4583                }
4584                else
4585                {
4586                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4587                   op.ops = uint64Ops;
4588                }
4589                op.kind = int64Type;
4590                break;
4591             case intSizeType:
4592                if(type.isSigned)
4593                {
4594                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4595                   op.ops = int64Ops;
4596                }
4597                else
4598                {
4599                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4600                   op.ops = uint64Ops;
4601                }
4602                op.kind = int64Type;
4603                break;
4604             case floatType:
4605                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4606                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4607                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4608                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4609                else
4610                   op.f = (float)strtod(exp.constant, null);
4611                op.ops = floatOps;
4612                break;
4613             case doubleType:
4614                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4615                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4616                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4617                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4618                else
4619                   op.d = (double)strtod(exp.constant, null);
4620                op.ops = doubleOps;
4621                break;
4622             //case classType:    For when we have operator overloading...
4623             // Pointer additions
4624             //case functionType:
4625             case arrayType:
4626             case pointerType:
4627             case classType:
4628                op.ui64 = _strtoui64(exp.constant, null, 0);
4629                op.kind = pointerType;
4630                op.ops = uint64Ops;
4631                // op.ptrSize =
4632                break;
4633          }
4634       }
4635    }
4636    return op;
4637 }
4638
4639 static int64 GetEnumValue(Class _class, void * ptr)
4640 {
4641    int64 v = 0;
4642    switch(_class.typeSize)
4643    {
4644       case 8:
4645          if(!strcmp(_class.dataTypeString, "uint64"))
4646             v = (int64)*(uint64 *)ptr;
4647          else
4648             v = (int64)*(int64 *)ptr;
4649          break;
4650       case 4:
4651          if(!strcmp(_class.dataTypeString, "uint"))
4652             v = (int64)*(uint *)ptr;
4653          else
4654             v = (int64)*(int *)ptr;
4655          break;
4656       case 2:
4657          if(!strcmp(_class.dataTypeString, "uint16"))
4658             v = (int64)*(uint16 *)ptr;
4659          else
4660             v = (int64)*(short *)ptr;
4661          break;
4662       case 1:
4663          if(!strcmp(_class.dataTypeString, "byte"))
4664             v = (int64)*(byte *)ptr;
4665          else
4666             v = (int64)*(char *)ptr;
4667          break;
4668    }
4669    return v;
4670 }
4671
4672 static __attribute__((unused)) void UnusedFunction()
4673 {
4674    int a;
4675    a.OnGetString(0,0,0);
4676 }
4677 default:
4678 extern int __ecereVMethodID_class_OnGetString;
4679 public:
4680
4681 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4682 {
4683    DataMember dataMember;
4684    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4685    {
4686       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4687          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4688       else
4689       {
4690          Expression exp { };
4691          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4692          Type type;
4693          void * ptr = inst.data + dataMember.offset + offset;
4694          char * result = null;
4695          exp.loc = member.loc = inst.loc;
4696          ((Identifier)member.identifiers->first).loc = inst.loc;
4697
4698          if(!dataMember.dataType)
4699             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4700          type = dataMember.dataType;
4701          if(type.kind == classType)
4702          {
4703             Class _class = type._class.registered;
4704             if(_class.type == enumClass)
4705             {
4706                Class enumClass = eSystem_FindClass(privateModule, "enum");
4707                if(enumClass)
4708                {
4709                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4710                   NamedLink64 item;
4711                   for(item = e.values.first; item; item = item.next)
4712                   {
4713                      if(item.data == GetEnumValue(_class, ptr))
4714                      {
4715                         result = item.name;
4716                         break;
4717                      }
4718                   }
4719                   if(result)
4720                   {
4721                      exp.identifier = MkIdentifier(result);
4722                      exp.type = identifierExp;
4723                      exp.destType = MkClassType(_class.fullName);
4724                      ProcessExpressionType(exp);
4725                   }
4726                }
4727             }
4728             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4729             {
4730                if(!_class.dataType)
4731                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4732                type = _class.dataType;
4733             }
4734          }
4735          if(!result)
4736          {
4737             switch(type.kind)
4738             {
4739                case floatType:
4740                {
4741                   FreeExpContents(exp);
4742
4743                   exp.constant = PrintFloat(*(float*)ptr);
4744                   exp.type = constantExp;
4745                   break;
4746                }
4747                case doubleType:
4748                {
4749                   FreeExpContents(exp);
4750
4751                   exp.constant = PrintDouble(*(double*)ptr);
4752                   exp.type = constantExp;
4753                   break;
4754                }
4755                case intType:
4756                {
4757                   FreeExpContents(exp);
4758
4759                   exp.constant = PrintInt(*(int*)ptr);
4760                   exp.type = constantExp;
4761                   break;
4762                }
4763                case int64Type:
4764                {
4765                   FreeExpContents(exp);
4766
4767                   exp.constant = PrintInt64(*(int64*)ptr);
4768                   exp.type = constantExp;
4769                   break;
4770                }
4771                case intPtrType:
4772                {
4773                   FreeExpContents(exp);
4774                   // TODO: This should probably use proper type
4775                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4776                   exp.type = constantExp;
4777                   break;
4778                }
4779                case intSizeType:
4780                {
4781                   FreeExpContents(exp);
4782                   // TODO: This should probably use proper type
4783                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4784                   exp.type = constantExp;
4785                   break;
4786                }
4787                default:
4788                   Compiler_Error($"Unhandled type populating instance\n");
4789             }
4790          }
4791          ListAdd(memberList, member);
4792       }
4793
4794       if(parentDataMember.type == unionMember)
4795          break;
4796    }
4797 }
4798
4799 void PopulateInstance(Instantiation inst)
4800 {
4801    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4802    Class _class = classSym.registered;
4803    DataMember dataMember;
4804    OldList * memberList = MkList();
4805    // Added this check and ->Add to prevent memory leaks on bad code
4806    if(!inst.members)
4807       inst.members = MkListOne(MkMembersInitList(memberList));
4808    else
4809       inst.members->Add(MkMembersInitList(memberList));
4810    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4811    {
4812       if(!dataMember.isProperty)
4813       {
4814          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4815             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4816          else
4817          {
4818             Expression exp { };
4819             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4820             Type type;
4821             void * ptr = inst.data + dataMember.offset;
4822             char * result = null;
4823
4824             exp.loc = member.loc = inst.loc;
4825             ((Identifier)member.identifiers->first).loc = inst.loc;
4826
4827             if(!dataMember.dataType)
4828                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4829             type = dataMember.dataType;
4830             if(type.kind == classType)
4831             {
4832                Class _class = type._class.registered;
4833                if(_class.type == enumClass)
4834                {
4835                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4836                   if(enumClass)
4837                   {
4838                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4839                      NamedLink64 item;
4840                      for(item = e.values.first; item; item = item.next)
4841                      {
4842                         if(item.data == GetEnumValue(_class, ptr))
4843                         {
4844                            result = item.name;
4845                            break;
4846                         }
4847                      }
4848                   }
4849                   if(result)
4850                   {
4851                      exp.identifier = MkIdentifier(result);
4852                      exp.type = identifierExp;
4853                      exp.destType = MkClassType(_class.fullName);
4854                      ProcessExpressionType(exp);
4855                   }
4856                }
4857                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4858                {
4859                   if(!_class.dataType)
4860                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4861                   type = _class.dataType;
4862                }
4863             }
4864             if(!result)
4865             {
4866                switch(type.kind)
4867                {
4868                   case floatType:
4869                   {
4870                      exp.constant = PrintFloat(*(float*)ptr);
4871                      exp.type = constantExp;
4872                      break;
4873                   }
4874                   case doubleType:
4875                   {
4876                      exp.constant = PrintDouble(*(double*)ptr);
4877                      exp.type = constantExp;
4878                      break;
4879                   }
4880                   case intType:
4881                   {
4882                      exp.constant = PrintInt(*(int*)ptr);
4883                      exp.type = constantExp;
4884                      break;
4885                   }
4886                   case int64Type:
4887                   {
4888                      exp.constant = PrintInt64(*(int64*)ptr);
4889                      exp.type = constantExp;
4890                      break;
4891                   }
4892                   case intPtrType:
4893                   {
4894                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4895                      exp.type = constantExp;
4896                      break;
4897                   }
4898                   default:
4899                      Compiler_Error($"Unhandled type populating instance\n");
4900                }
4901             }
4902             ListAdd(memberList, member);
4903          }
4904       }
4905    }
4906 }
4907
4908 void ComputeInstantiation(Expression exp)
4909 {
4910    Instantiation inst = exp.instance;
4911    MembersInit members;
4912    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4913    Class _class = classSym ? classSym.registered : null;
4914    DataMember curMember = null;
4915    Class curClass = null;
4916    DataMember subMemberStack[256];
4917    int subMemberStackPos = 0;
4918    uint64 bits = 0;
4919
4920    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4921    {
4922       // Don't recompute the instantiation...
4923       // Non Simple classes will have become constants by now
4924       if(inst.data)
4925          return;
4926
4927       if(_class.type == normalClass || _class.type == noHeadClass)
4928       {
4929          inst.data = (byte *)eInstance_New(_class);
4930          if(_class.type == normalClass)
4931             ((Instance)inst.data)._refCount++;
4932       }
4933       else
4934          inst.data = new0 byte[_class.structSize];
4935    }
4936
4937    if(inst.members)
4938    {
4939       for(members = inst.members->first; members; members = members.next)
4940       {
4941          switch(members.type)
4942          {
4943             case dataMembersInit:
4944             {
4945                if(members.dataMembers)
4946                {
4947                   MemberInit member;
4948                   for(member = members.dataMembers->first; member; member = member.next)
4949                   {
4950                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4951                      bool found = false;
4952
4953                      Property prop = null;
4954                      DataMember dataMember = null;
4955                      uint dataMemberOffset;
4956
4957                      if(!ident)
4958                      {
4959                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4960                         if(curMember)
4961                         {
4962                            if(curMember.isProperty)
4963                               prop = (Property)curMember;
4964                            else
4965                            {
4966                               dataMember = curMember;
4967
4968                               // CHANGED THIS HERE
4969                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4970
4971                               // 2013/17/29 -- It seems that this was missing here!
4972                               if(_class.type == normalClass)
4973                                  dataMemberOffset += _class.base.structSize;
4974                               // dataMemberOffset = dataMember.offset;
4975                            }
4976                            found = true;
4977                         }
4978                      }
4979                      else
4980                      {
4981                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4982                         if(prop)
4983                         {
4984                            found = true;
4985                            if(prop.memberAccess == publicAccess)
4986                            {
4987                               curMember = (DataMember)prop;
4988                               curClass = prop._class;
4989                            }
4990                         }
4991                         else
4992                         {
4993                            DataMember _subMemberStack[256];
4994                            int _subMemberStackPos = 0;
4995
4996                            // FILL MEMBER STACK
4997                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4998
4999                            if(dataMember)
5000                            {
5001                               found = true;
5002                               if(dataMember.memberAccess == publicAccess)
5003                               {
5004                                  curMember = dataMember;
5005                                  curClass = dataMember._class;
5006                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
5007                                  subMemberStackPos = _subMemberStackPos;
5008                               }
5009                            }
5010                         }
5011                      }
5012
5013                      if(found && member.initializer && member.initializer.type == expInitializer)
5014                      {
5015                         Expression value = member.initializer.exp;
5016                         Type type = null;
5017                         bool deepMember = false;
5018                         if(prop)
5019                         {
5020                            type = prop.dataType;
5021                         }
5022                         else if(dataMember)
5023                         {
5024                            if(!dataMember.dataType)
5025                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
5026
5027                            type = dataMember.dataType;
5028                         }
5029
5030                         if(ident && ident.next)
5031                         {
5032                            deepMember = true;
5033
5034                            // for(; ident && type; ident = ident.next)
5035                            for(ident = ident.next; ident && type; ident = ident.next)
5036                            {
5037                               if(type.kind == classType)
5038                               {
5039                                  prop = eClass_FindProperty(type._class.registered,
5040                                     ident.string, privateModule);
5041                                  if(prop)
5042                                     type = prop.dataType;
5043                                  else
5044                                  {
5045                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
5046                                        ident.string, &dataMemberOffset, privateModule, null, null);
5047                                     if(dataMember)
5048                                        type = dataMember.dataType;
5049                                  }
5050                               }
5051                               else if(type.kind == structType || type.kind == unionType)
5052                               {
5053                                  Type memberType;
5054                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
5055                                  {
5056                                     if(!strcmp(memberType.name, ident.string))
5057                                     {
5058                                        type = memberType;
5059                                        break;
5060                                     }
5061                                  }
5062                               }
5063                            }
5064                         }
5065                         if(value)
5066                         {
5067                            FreeType(value.destType);
5068                            value.destType = type;
5069                            if(type) type.refCount++;
5070                            ComputeExpression(value);
5071                         }
5072                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
5073                         {
5074                            if(type.kind == classType)
5075                            {
5076                               Class _class = type._class.registered;
5077                               if(_class.type == bitClass || _class.type == unitClass ||
5078                                  _class.type == enumClass)
5079                               {
5080                                  if(!_class.dataType)
5081                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5082                                  type = _class.dataType;
5083                               }
5084                            }
5085
5086                            if(dataMember)
5087                            {
5088                               void * ptr = inst.data + dataMemberOffset;
5089
5090                               if(value.type == constantExp)
5091                               {
5092                                  switch(type.kind)
5093                                  {
5094                                     case intType:
5095                                     {
5096                                        GetInt(value, (int*)ptr);
5097                                        break;
5098                                     }
5099                                     case int64Type:
5100                                     {
5101                                        GetInt64(value, (int64*)ptr);
5102                                        break;
5103                                     }
5104                                     case intPtrType:
5105                                     {
5106                                        GetIntPtr(value, (intptr*)ptr);
5107                                        break;
5108                                     }
5109                                     case intSizeType:
5110                                     {
5111                                        GetIntSize(value, (intsize*)ptr);
5112                                        break;
5113                                     }
5114                                     case floatType:
5115                                     {
5116                                        GetFloat(value, (float*)ptr);
5117                                        break;
5118                                     }
5119                                     case doubleType:
5120                                     {
5121                                        GetDouble(value, (double *)ptr);
5122                                        break;
5123                                     }
5124                                  }
5125                               }
5126                               else if(value.type == instanceExp)
5127                               {
5128                                  if(type.kind == classType)
5129                                  {
5130                                     Class _class = type._class.registered;
5131                                     if(_class.type == structClass)
5132                                     {
5133                                        ComputeTypeSize(type);
5134                                        if(value.instance.data)
5135                                           memcpy(ptr, value.instance.data, type.size);
5136                                     }
5137                                  }
5138                               }
5139                            }
5140                            else if(prop)
5141                            {
5142                               if(value.type == instanceExp && value.instance.data)
5143                               {
5144                                  if(type.kind == classType)
5145                                  {
5146                                     Class _class = type._class.registered;
5147                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5148                                     {
5149                                        void (*Set)(void *, void *) = (void *)prop.Set;
5150                                        Set(inst.data, value.instance.data);
5151                                        PopulateInstance(inst);
5152                                     }
5153                                  }
5154                               }
5155                               else if(value.type == constantExp)
5156                               {
5157                                  switch(type.kind)
5158                                  {
5159                                     case doubleType:
5160                                     {
5161                                        void (*Set)(void *, double) = (void *)prop.Set;
5162                                        Set(inst.data, strtod(value.constant, null) );
5163                                        break;
5164                                     }
5165                                     case floatType:
5166                                     {
5167                                        void (*Set)(void *, float) = (void *)prop.Set;
5168                                        Set(inst.data, (float)(strtod(value.constant, null)));
5169                                        break;
5170                                     }
5171                                     case intType:
5172                                     {
5173                                        void (*Set)(void *, int) = (void *)prop.Set;
5174                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5175                                        break;
5176                                     }
5177                                     case int64Type:
5178                                     {
5179                                        void (*Set)(void *, int64) = (void *)prop.Set;
5180                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5181                                        break;
5182                                     }
5183                                     case intPtrType:
5184                                     {
5185                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5186                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5187                                        break;
5188                                     }
5189                                     case intSizeType:
5190                                     {
5191                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5192                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5193                                        break;
5194                                     }
5195                                  }
5196                               }
5197                               else if(value.type == stringExp)
5198                               {
5199                                  char temp[1024];
5200                                  ReadString(temp, value.string);
5201                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5202                               }
5203                            }
5204                         }
5205                         else if(!deepMember && type && _class.type == unitClass)
5206                         {
5207                            if(prop)
5208                            {
5209                               // Only support converting units to units for now...
5210                               if(value.type == constantExp)
5211                               {
5212                                  if(type.kind == classType)
5213                                  {
5214                                     Class _class = type._class.registered;
5215                                     if(_class.type == unitClass)
5216                                     {
5217                                        if(!_class.dataType)
5218                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5219                                        type = _class.dataType;
5220                                     }
5221                                  }
5222                                  // TODO: Assuming same base type for units...
5223                                  switch(type.kind)
5224                                  {
5225                                     case floatType:
5226                                     {
5227                                        float fValue;
5228                                        float (*Set)(float) = (void *)prop.Set;
5229                                        GetFloat(member.initializer.exp, &fValue);
5230                                        exp.constant = PrintFloat(Set(fValue));
5231                                        exp.type = constantExp;
5232                                        break;
5233                                     }
5234                                     case doubleType:
5235                                     {
5236                                        double dValue;
5237                                        double (*Set)(double) = (void *)prop.Set;
5238                                        GetDouble(member.initializer.exp, &dValue);
5239                                        exp.constant = PrintDouble(Set(dValue));
5240                                        exp.type = constantExp;
5241                                        break;
5242                                     }
5243                                  }
5244                               }
5245                            }
5246                         }
5247                         else if(!deepMember && type && _class.type == bitClass)
5248                         {
5249                            if(prop)
5250                            {
5251                               if(value.type == instanceExp && value.instance.data)
5252                               {
5253                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5254                                  bits = Set(value.instance.data);
5255                               }
5256                               else if(value.type == constantExp)
5257                               {
5258                               }
5259                            }
5260                            else if(dataMember)
5261                            {
5262                               BitMember bitMember = (BitMember) dataMember;
5263                               Type type;
5264                               uint64 part = 0;
5265                               bits = (bits & ~bitMember.mask);
5266                               if(!bitMember.dataType)
5267                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5268                               type = bitMember.dataType;
5269                               if(type.kind == classType && type._class && type._class.registered)
5270                               {
5271                                  if(!type._class.registered.dataType)
5272                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5273                                  type = type._class.registered.dataType;
5274                               }
5275                               switch(type.kind)
5276                               {
5277                                  case _BoolType:
5278                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5279                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5280                                  case intType:
5281                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5282                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5283                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5284                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5285                               }
5286                               bits |= part << bitMember.pos;
5287                            }
5288                         }
5289                      }
5290                      else
5291                      {
5292                         if(_class && _class.type == unitClass)
5293                         {
5294                            ComputeExpression(member.initializer.exp);
5295                            exp.constant = member.initializer.exp.constant;
5296                            exp.type = constantExp;
5297
5298                            member.initializer.exp.constant = null;
5299                         }
5300                      }
5301                   }
5302                }
5303                break;
5304             }
5305          }
5306       }
5307    }
5308    if(_class && _class.type == bitClass)
5309    {
5310       exp.constant = PrintHexUInt(bits);
5311       exp.type = constantExp;
5312    }
5313    if(exp.type != instanceExp)
5314    {
5315       FreeInstance(inst);
5316    }
5317 }
5318
5319 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5320 {
5321    bool result = false;
5322    switch(kind)
5323    {
5324       case shortType:
5325          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5326             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5327          break;
5328       case intType:
5329       case longType:
5330          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5331             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5332          break;
5333       case int64Type:
5334          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5335             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5336             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5337          break;
5338       case floatType:
5339          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5340             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5341             result = GetOpFloat(op, &op.f);
5342          break;
5343       case doubleType:
5344          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5345             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5346             result = GetOpDouble(op, &op.d);
5347          break;
5348       case pointerType:
5349          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5350             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5351             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5352          break;
5353       case enumType:
5354          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5355             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5356             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5357          break;
5358       case intPtrType:
5359          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5360             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5361          break;
5362       case intSizeType:
5363          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5364             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5365          break;
5366    }
5367    return result;
5368 }
5369
5370 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5371 {
5372    if(exp.op.op == SIZEOF)
5373    {
5374       FreeExpContents(exp);
5375       exp.type = constantExp;
5376       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5377    }
5378    else
5379    {
5380       if(!exp.op.exp1)
5381       {
5382          switch(exp.op.op)
5383          {
5384             // unary arithmetic
5385             case '+':
5386             {
5387                // Provide default unary +
5388                Expression exp2 = exp.op.exp2;
5389                exp.op.exp2 = null;
5390                FreeExpContents(exp);
5391                FreeType(exp.expType);
5392                FreeType(exp.destType);
5393                *exp = *exp2;
5394                delete exp2;
5395                break;
5396             }
5397             case '-':
5398                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5399                break;
5400             // unary arithmetic increment and decrement
5401                   //OPERATOR_ALL(UNARY, ++, Inc)
5402                   //OPERATOR_ALL(UNARY, --, Dec)
5403             // unary bitwise
5404             case '~':
5405                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5406                break;
5407             // unary logical negation
5408             case '!':
5409                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5410                break;
5411          }
5412       }
5413       else
5414       {
5415          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5416          {
5417             if(Promote(op2, op1.kind, op1.type.isSigned))
5418                op2.kind = op1.kind, op2.ops = op1.ops;
5419             else if(Promote(op1, op2.kind, op2.type.isSigned))
5420                op1.kind = op2.kind, op1.ops = op2.ops;
5421          }
5422          switch(exp.op.op)
5423          {
5424             // binary arithmetic
5425             case '+':
5426                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5427                break;
5428             case '-':
5429                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5430                break;
5431             case '*':
5432                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5433                break;
5434             case '/':
5435                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5436                break;
5437             case '%':
5438                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5439                break;
5440             // binary arithmetic assignment
5441                   //OPERATOR_ALL(BINARY, =, Asign)
5442                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5443                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5444                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5445                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5446                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5447             // binary bitwise
5448             case '&':
5449                if(exp.op.exp2)
5450                {
5451                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5452                }
5453                break;
5454             case '|':
5455                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5456                break;
5457             case '^':
5458                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5459                break;
5460             case LEFT_OP:
5461                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5462                break;
5463             case RIGHT_OP:
5464                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5465                break;
5466             // binary bitwise assignment
5467                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5468                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5469                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5470                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5471                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5472             // binary logical equality
5473             case EQ_OP:
5474                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5475                break;
5476             case NE_OP:
5477                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5478                break;
5479             // binary logical
5480             case AND_OP:
5481                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5482                break;
5483             case OR_OP:
5484                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5485                break;
5486             // binary logical relational
5487             case '>':
5488                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5489                break;
5490             case '<':
5491                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5492                break;
5493             case GE_OP:
5494                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5495                break;
5496             case LE_OP:
5497                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5498                break;
5499          }
5500       }
5501    }
5502 }
5503
5504 void ComputeExpression(Expression exp)
5505 {
5506 #ifdef _DEBUG
5507    char expString[10240];
5508    expString[0] = '\0';
5509    PrintExpression(exp, expString);
5510 #endif
5511
5512    switch(exp.type)
5513    {
5514       case instanceExp:
5515       {
5516          ComputeInstantiation(exp);
5517          break;
5518       }
5519       /*
5520       case constantExp:
5521          break;
5522       */
5523       case opExp:
5524       {
5525          Expression exp1, exp2 = null;
5526          Operand op1 { };
5527          Operand op2 { };
5528
5529          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5530          if(exp.op.exp2)
5531          {
5532             Expression e = exp.op.exp2;
5533
5534             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5535             {
5536                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5537                {
5538                   if(e.type == extensionCompoundExp)
5539                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5540                   else
5541                      e = e.list->last;
5542                }
5543             }
5544             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5545             {
5546                if(e.type == stringExp && e.string)
5547                {
5548                   char * string = e.string;
5549                   int len = strlen(string);
5550                   char * tmp = new char[len-2+1];
5551                   len = UnescapeString(tmp, string + 1, len - 2);
5552                   delete tmp;
5553                   FreeExpContents(exp);
5554                   exp.type = constantExp;
5555                   exp.constant = PrintUInt(len + 1);
5556                }
5557                else
5558                {
5559                   Type type = e.expType;
5560                   type.refCount++;
5561                   FreeExpContents(exp);
5562                   exp.type = constantExp;
5563                   exp.constant = PrintUInt(ComputeTypeSize(type));
5564                   FreeType(type);
5565                }
5566                break;
5567             }
5568             else
5569                ComputeExpression(exp.op.exp2);
5570          }
5571          if(exp.op.exp1)
5572          {
5573             ComputeExpression(exp.op.exp1);
5574             exp1 = exp.op.exp1;
5575             exp2 = exp.op.exp2;
5576             op1 = GetOperand(exp1);
5577             if(op1.type) op1.type.refCount++;
5578             if(exp2)
5579             {
5580                op2 = GetOperand(exp2);
5581                if(op2.type) op2.type.refCount++;
5582             }
5583          }
5584          else
5585          {
5586             exp1 = exp.op.exp2;
5587             op1 = GetOperand(exp1);
5588             if(op1.type) op1.type.refCount++;
5589          }
5590
5591          CallOperator(exp, exp1, exp2, op1, op2);
5592          /*
5593          switch(exp.op.op)
5594          {
5595             // Unary operators
5596             case '&':
5597                // Also binary
5598                if(exp.op.exp1 && exp.op.exp2)
5599                {
5600                   // Binary And
5601                   if(op1.ops.BitAnd)
5602                   {
5603                      FreeExpContents(exp);
5604                      op1.ops.BitAnd(exp, op1, op2);
5605                   }
5606                }
5607                break;
5608             case '*':
5609                if(exp.op.exp1)
5610                {
5611                   if(op1.ops.Mul)
5612                   {
5613                      FreeExpContents(exp);
5614                      op1.ops.Mul(exp, op1, op2);
5615                   }
5616                }
5617                break;
5618             case '+':
5619                if(exp.op.exp1)
5620                {
5621                   if(op1.ops.Add)
5622                   {
5623                      FreeExpContents(exp);
5624                      op1.ops.Add(exp, op1, op2);
5625                   }
5626                }
5627                else
5628                {
5629                   // Provide default unary +
5630                   Expression exp2 = exp.op.exp2;
5631                   exp.op.exp2 = null;
5632                   FreeExpContents(exp);
5633                   FreeType(exp.expType);
5634                   FreeType(exp.destType);
5635
5636                   *exp = *exp2;
5637                   delete exp2;
5638                }
5639                break;
5640             case '-':
5641                if(exp.op.exp1)
5642                {
5643                   if(op1.ops.Sub)
5644                   {
5645                      FreeExpContents(exp);
5646                      op1.ops.Sub(exp, op1, op2);
5647                   }
5648                }
5649                else
5650                {
5651                   if(op1.ops.Neg)
5652                   {
5653                      FreeExpContents(exp);
5654                      op1.ops.Neg(exp, op1);
5655                   }
5656                }
5657                break;
5658             case '~':
5659                if(op1.ops.BitNot)
5660                {
5661                   FreeExpContents(exp);
5662                   op1.ops.BitNot(exp, op1);
5663                }
5664                break;
5665             case '!':
5666                if(op1.ops.Not)
5667                {
5668                   FreeExpContents(exp);
5669                   op1.ops.Not(exp, op1);
5670                }
5671                break;
5672             // Binary only operators
5673             case '/':
5674                if(op1.ops.Div)
5675                {
5676                   FreeExpContents(exp);
5677                   op1.ops.Div(exp, op1, op2);
5678                }
5679                break;
5680             case '%':
5681                if(op1.ops.Mod)
5682                {
5683                   FreeExpContents(exp);
5684                   op1.ops.Mod(exp, op1, op2);
5685                }
5686                break;
5687             case LEFT_OP:
5688                break;
5689             case RIGHT_OP:
5690                break;
5691             case '<':
5692                if(exp.op.exp1)
5693                {
5694                   if(op1.ops.Sma)
5695                   {
5696                      FreeExpContents(exp);
5697                      op1.ops.Sma(exp, op1, op2);
5698                   }
5699                }
5700                break;
5701             case '>':
5702                if(exp.op.exp1)
5703                {
5704                   if(op1.ops.Grt)
5705                   {
5706                      FreeExpContents(exp);
5707                      op1.ops.Grt(exp, op1, op2);
5708                   }
5709                }
5710                break;
5711             case LE_OP:
5712                if(exp.op.exp1)
5713                {
5714                   if(op1.ops.SmaEqu)
5715                   {
5716                      FreeExpContents(exp);
5717                      op1.ops.SmaEqu(exp, op1, op2);
5718                   }
5719                }
5720                break;
5721             case GE_OP:
5722                if(exp.op.exp1)
5723                {
5724                   if(op1.ops.GrtEqu)
5725                   {
5726                      FreeExpContents(exp);
5727                      op1.ops.GrtEqu(exp, op1, op2);
5728                   }
5729                }
5730                break;
5731             case EQ_OP:
5732                if(exp.op.exp1)
5733                {
5734                   if(op1.ops.Equ)
5735                   {
5736                      FreeExpContents(exp);
5737                      op1.ops.Equ(exp, op1, op2);
5738                   }
5739                }
5740                break;
5741             case NE_OP:
5742                if(exp.op.exp1)
5743                {
5744                   if(op1.ops.Nqu)
5745                   {
5746                      FreeExpContents(exp);
5747                      op1.ops.Nqu(exp, op1, op2);
5748                   }
5749                }
5750                break;
5751             case '|':
5752                if(op1.ops.BitOr)
5753                {
5754                   FreeExpContents(exp);
5755                   op1.ops.BitOr(exp, op1, op2);
5756                }
5757                break;
5758             case '^':
5759                if(op1.ops.BitXor)
5760                {
5761                   FreeExpContents(exp);
5762                   op1.ops.BitXor(exp, op1, op2);
5763                }
5764                break;
5765             case AND_OP:
5766                break;
5767             case OR_OP:
5768                break;
5769             case SIZEOF:
5770                FreeExpContents(exp);
5771                exp.type = constantExp;
5772                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5773                break;
5774          }
5775          */
5776          if(op1.type) FreeType(op1.type);
5777          if(op2.type) FreeType(op2.type);
5778          break;
5779       }
5780       case bracketsExp:
5781       case extensionExpressionExp:
5782       {
5783          Expression e, n;
5784          for(e = exp.list->first; e; e = n)
5785          {
5786             n = e.next;
5787             if(!n)
5788             {
5789                OldList * list = exp.list;
5790                Expression prev = exp.prev;
5791                Expression next = exp.next;
5792                ComputeExpression(e);
5793                //FreeExpContents(exp);
5794                FreeType(exp.expType);
5795                FreeType(exp.destType);
5796                *exp = *e;
5797                exp.prev = prev;
5798                exp.next = next;
5799                delete e;
5800                delete list;
5801             }
5802             else
5803             {
5804                FreeExpression(e);
5805             }
5806          }
5807          break;
5808       }
5809       /*
5810
5811       case ExpIndex:
5812       {
5813          Expression e;
5814          exp.isConstant = true;
5815
5816          ComputeExpression(exp.index.exp);
5817          if(!exp.index.exp.isConstant)
5818             exp.isConstant = false;
5819
5820          for(e = exp.index.index->first; e; e = e.next)
5821          {
5822             ComputeExpression(e);
5823             if(!e.next)
5824             {
5825                // Check if this type is int
5826             }
5827             if(!e.isConstant)
5828                exp.isConstant = false;
5829          }
5830          exp.expType = Dereference(exp.index.exp.expType);
5831          break;
5832       }
5833       */
5834       case memberExp:
5835       {
5836          Expression memberExp = exp.member.exp;
5837          Identifier memberID = exp.member.member;
5838
5839          Type type;
5840          ComputeExpression(exp.member.exp);
5841          type = exp.member.exp.expType;
5842          if(type)
5843          {
5844             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);
5845             Property prop = null;
5846             DataMember member = null;
5847             Class convertTo = null;
5848             if(type.kind == subClassType && exp.member.exp.type == classExp)
5849                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5850
5851             if(!_class)
5852             {
5853                char string[256];
5854                Symbol classSym;
5855                string[0] = '\0';
5856                PrintTypeNoConst(type, string, false, true);
5857                classSym = FindClass(string);
5858                _class = classSym ? classSym.registered : null;
5859             }
5860
5861             if(exp.member.member)
5862             {
5863                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5864                if(!prop)
5865                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5866             }
5867             if(!prop && !member && _class && exp.member.member)
5868             {
5869                Symbol classSym = FindClass(exp.member.member.string);
5870                convertTo = _class;
5871                _class = classSym ? classSym.registered : null;
5872                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5873             }
5874
5875             if(prop)
5876             {
5877                if(prop.compiled)
5878                {
5879                   Type type = prop.dataType;
5880                   // TODO: Assuming same base type for units...
5881                   if(_class.type == unitClass)
5882                   {
5883                      if(type.kind == classType)
5884                      {
5885                         Class _class = type._class.registered;
5886                         if(_class.type == unitClass)
5887                         {
5888                            if(!_class.dataType)
5889                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5890                            type = _class.dataType;
5891                         }
5892                      }
5893                      switch(type.kind)
5894                      {
5895                         case floatType:
5896                         {
5897                            float value;
5898                            float (*Get)(float) = (void *)prop.Get;
5899                            GetFloat(exp.member.exp, &value);
5900                            exp.constant = PrintFloat(Get ? Get(value) : value);
5901                            exp.type = constantExp;
5902                            break;
5903                         }
5904                         case doubleType:
5905                         {
5906                            double value;
5907                            double (*Get)(double);
5908                            GetDouble(exp.member.exp, &value);
5909
5910                            if(convertTo)
5911                               Get = (void *)prop.Set;
5912                            else
5913                               Get = (void *)prop.Get;
5914                            exp.constant = PrintDouble(Get ? Get(value) : value);
5915                            exp.type = constantExp;
5916                            break;
5917                         }
5918                      }
5919                   }
5920                   else
5921                   {
5922                      if(convertTo)
5923                      {
5924                         Expression value = exp.member.exp;
5925                         Type type;
5926                         if(!prop.dataType)
5927                            ProcessPropertyType(prop);
5928
5929                         type = prop.dataType;
5930                         if(!type)
5931                         {
5932                             // printf("Investigate this\n");
5933                         }
5934                         else if(_class.type == structClass)
5935                         {
5936                            switch(type.kind)
5937                            {
5938                               case classType:
5939                               {
5940                                  Class propertyClass = type._class.registered;
5941                                  if(propertyClass.type == structClass && value.type == instanceExp)
5942                                  {
5943                                     void (*Set)(void *, void *) = (void *)prop.Set;
5944                                     exp.instance = Instantiation { };
5945                                     exp.instance.data = new0 byte[_class.structSize];
5946                                     exp.instance._class = MkSpecifierName(_class.fullName);
5947                                     exp.instance.loc = exp.loc;
5948                                     exp.type = instanceExp;
5949                                     Set(exp.instance.data, value.instance.data);
5950                                     PopulateInstance(exp.instance);
5951                                  }
5952                                  break;
5953                               }
5954                               case intType:
5955                               {
5956                                  int intValue;
5957                                  void (*Set)(void *, int) = (void *)prop.Set;
5958
5959                                  exp.instance = Instantiation { };
5960                                  exp.instance.data = new0 byte[_class.structSize];
5961                                  exp.instance._class = MkSpecifierName(_class.fullName);
5962                                  exp.instance.loc = exp.loc;
5963                                  exp.type = instanceExp;
5964
5965                                  GetInt(value, &intValue);
5966
5967                                  Set(exp.instance.data, intValue);
5968                                  PopulateInstance(exp.instance);
5969                                  break;
5970                               }
5971                               case int64Type:
5972                               {
5973                                  int64 intValue;
5974                                  void (*Set)(void *, int64) = (void *)prop.Set;
5975
5976                                  exp.instance = Instantiation { };
5977                                  exp.instance.data = new0 byte[_class.structSize];
5978                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5979                                  exp.instance.loc = exp.loc;
5980                                  exp.type = instanceExp;
5981
5982                                  GetInt64(value, &intValue);
5983
5984                                  Set(exp.instance.data, intValue);
5985                                  PopulateInstance(exp.instance);
5986                                  break;
5987                               }
5988                               case intPtrType:
5989                               {
5990                                  // TOFIX:
5991                                  intptr intValue;
5992                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5993
5994                                  exp.instance = Instantiation { };
5995                                  exp.instance.data = new0 byte[_class.structSize];
5996                                  exp.instance._class = MkSpecifierName(_class.fullName);
5997                                  exp.instance.loc = exp.loc;
5998                                  exp.type = instanceExp;
5999
6000                                  GetIntPtr(value, &intValue);
6001
6002                                  Set(exp.instance.data, intValue);
6003                                  PopulateInstance(exp.instance);
6004                                  break;
6005                               }
6006                               case intSizeType:
6007                               {
6008                                  // TOFIX:
6009                                  intsize intValue;
6010                                  void (*Set)(void *, intsize) = (void *)prop.Set;
6011
6012                                  exp.instance = Instantiation { };
6013                                  exp.instance.data = new0 byte[_class.structSize];
6014                                  exp.instance._class = MkSpecifierName(_class.fullName);
6015                                  exp.instance.loc = exp.loc;
6016                                  exp.type = instanceExp;
6017
6018                                  GetIntSize(value, &intValue);
6019
6020                                  Set(exp.instance.data, intValue);
6021                                  PopulateInstance(exp.instance);
6022                                  break;
6023                               }
6024                               case floatType:
6025                               {
6026                                  float floatValue;
6027                                  void (*Set)(void *, float) = (void *)prop.Set;
6028
6029                                  exp.instance = Instantiation { };
6030                                  exp.instance.data = new0 byte[_class.structSize];
6031                                  exp.instance._class = MkSpecifierName(_class.fullName);
6032                                  exp.instance.loc = exp.loc;
6033                                  exp.type = instanceExp;
6034
6035                                  GetFloat(value, &floatValue);
6036
6037                                  Set(exp.instance.data, floatValue);
6038                                  PopulateInstance(exp.instance);
6039                                  break;
6040                               }
6041                               case doubleType:
6042                               {
6043                                  double doubleValue;
6044                                  void (*Set)(void *, double) = (void *)prop.Set;
6045
6046                                  exp.instance = Instantiation { };
6047                                  exp.instance.data = new0 byte[_class.structSize];
6048                                  exp.instance._class = MkSpecifierName(_class.fullName);
6049                                  exp.instance.loc = exp.loc;
6050                                  exp.type = instanceExp;
6051
6052                                  GetDouble(value, &doubleValue);
6053
6054                                  Set(exp.instance.data, doubleValue);
6055                                  PopulateInstance(exp.instance);
6056                                  break;
6057                               }
6058                            }
6059                         }
6060                         else if(_class.type == bitClass)
6061                         {
6062                            switch(type.kind)
6063                            {
6064                               case classType:
6065                               {
6066                                  Class propertyClass = type._class.registered;
6067                                  if(propertyClass.type == structClass && value.instance.data)
6068                                  {
6069                                     unsigned int (*Set)(void *) = (void *)prop.Set;
6070                                     unsigned int bits = Set(value.instance.data);
6071                                     exp.constant = PrintHexUInt(bits);
6072                                     exp.type = constantExp;
6073                                     break;
6074                                  }
6075                                  else if(_class.type == bitClass)
6076                                  {
6077                                     unsigned int value;
6078                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
6079                                     unsigned int bits;
6080
6081                                     GetUInt(exp.member.exp, &value);
6082                                     bits = Set(value);
6083                                     exp.constant = PrintHexUInt(bits);
6084                                     exp.type = constantExp;
6085                                  }
6086                               }
6087                            }
6088                         }
6089                      }
6090                      else
6091                      {
6092                         if(_class.type == bitClass)
6093                         {
6094                            unsigned int value;
6095                            GetUInt(exp.member.exp, &value);
6096
6097                            switch(type.kind)
6098                            {
6099                               case classType:
6100                               {
6101                                  Class _class = type._class.registered;
6102                                  if(_class.type == structClass)
6103                                  {
6104                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6105
6106                                     exp.instance = Instantiation { };
6107                                     exp.instance.data = new0 byte[_class.structSize];
6108                                     exp.instance._class = MkSpecifierName(_class.fullName);
6109                                     exp.instance.loc = exp.loc;
6110                                     //exp.instance.fullSet = true;
6111                                     exp.type = instanceExp;
6112                                     Get(value, exp.instance.data);
6113                                     PopulateInstance(exp.instance);
6114                                  }
6115                                  else if(_class.type == bitClass)
6116                                  {
6117                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6118                                     uint64 bits = Get(value);
6119                                     exp.constant = PrintHexUInt64(bits);
6120                                     exp.type = constantExp;
6121                                  }
6122                                  break;
6123                               }
6124                            }
6125                         }
6126                         else if(_class.type == structClass)
6127                         {
6128                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6129                            switch(type.kind)
6130                            {
6131                               case classType:
6132                               {
6133                                  Class _class = type._class.registered;
6134                                  if(_class.type == structClass && value)
6135                                  {
6136                                     void (*Get)(void *, void *) = (void *)prop.Get;
6137
6138                                     exp.instance = Instantiation { };
6139                                     exp.instance.data = new0 byte[_class.structSize];
6140                                     exp.instance._class = MkSpecifierName(_class.fullName);
6141                                     exp.instance.loc = exp.loc;
6142                                     //exp.instance.fullSet = true;
6143                                     exp.type = instanceExp;
6144                                     Get(value, exp.instance.data);
6145                                     PopulateInstance(exp.instance);
6146                                  }
6147                                  break;
6148                               }
6149                            }
6150                         }
6151                         /*else
6152                         {
6153                            char * value = exp.member.exp.instance.data;
6154                            switch(type.kind)
6155                            {
6156                               case classType:
6157                               {
6158                                  Class _class = type._class.registered;
6159                                  if(_class.type == normalClass)
6160                                  {
6161                                     void *(*Get)(void *) = (void *)prop.Get;
6162
6163                                     exp.instance = Instantiation { };
6164                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6165                                     exp.type = instanceExp;
6166                                     exp.instance.data = Get(value, exp.instance.data);
6167                                  }
6168                                  break;
6169                               }
6170                            }
6171                         }
6172                         */
6173                      }
6174                   }
6175                }
6176                else
6177                {
6178                   exp.isConstant = false;
6179                }
6180             }
6181             else if(member)
6182             {
6183             }
6184          }
6185
6186          if(exp.type != ExpressionType::memberExp)
6187          {
6188             FreeExpression(memberExp);
6189             FreeIdentifier(memberID);
6190          }
6191          break;
6192       }
6193       case typeSizeExp:
6194       {
6195          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6196          FreeExpContents(exp);
6197          exp.constant = PrintUInt(ComputeTypeSize(type));
6198          exp.type = constantExp;
6199          FreeType(type);
6200          break;
6201       }
6202       case classSizeExp:
6203       {
6204          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6205          if(classSym && classSym.registered)
6206          {
6207             if(classSym.registered.fixed)
6208             {
6209                FreeSpecifier(exp._class);
6210                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6211                exp.type = constantExp;
6212             }
6213             else
6214             {
6215                char className[1024];
6216                strcpy(className, "__ecereClass_");
6217                FullClassNameCat(className, classSym.string, true);
6218                //MangleClassName(className);
6219
6220                DeclareClass(classSym, className);
6221
6222                FreeExpContents(exp);
6223                exp.type = pointerExp;
6224                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6225                exp.member.member = MkIdentifier("structSize");
6226             }
6227          }
6228          break;
6229       }
6230       case castExp:
6231       //case constantExp:
6232       {
6233          Type type;
6234          Expression e = exp;
6235          if(exp.type == castExp)
6236          {
6237             if(exp.cast.exp)
6238                ComputeExpression(exp.cast.exp);
6239             e = exp.cast.exp;
6240          }
6241          if(e && exp.expType)
6242          {
6243             /*if(exp.destType)
6244                type = exp.destType;
6245             else*/
6246                type = exp.expType;
6247             if(type.kind == classType)
6248             {
6249                Class _class = type._class.registered;
6250                if(_class && (_class.type == unitClass || _class.type == bitClass))
6251                {
6252                   if(!_class.dataType)
6253                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6254                   type = _class.dataType;
6255                }
6256             }
6257
6258             switch(type.kind)
6259             {
6260                case _BoolType:
6261                case charType:
6262                   if(type.isSigned)
6263                   {
6264                      char value = 0;
6265                      if(GetChar(e, &value))
6266                      {
6267                         FreeExpContents(exp);
6268                         exp.constant = PrintChar(value);
6269                         exp.type = constantExp;
6270                      }
6271                   }
6272                   else
6273                   {
6274                      unsigned char value = 0;
6275                      if(GetUChar(e, &value))
6276                      {
6277                         FreeExpContents(exp);
6278                         exp.constant = PrintUChar(value);
6279                         exp.type = constantExp;
6280                      }
6281                   }
6282                   break;
6283                case shortType:
6284                   if(type.isSigned)
6285                   {
6286                      short value = 0;
6287                      if(GetShort(e, &value))
6288                      {
6289                         FreeExpContents(exp);
6290                         exp.constant = PrintShort(value);
6291                         exp.type = constantExp;
6292                      }
6293                   }
6294                   else
6295                   {
6296                      unsigned short value = 0;
6297                      if(GetUShort(e, &value))
6298                      {
6299                         FreeExpContents(exp);
6300                         exp.constant = PrintUShort(value);
6301                         exp.type = constantExp;
6302                      }
6303                   }
6304                   break;
6305                case intType:
6306                   if(type.isSigned)
6307                   {
6308                      int value = 0;
6309                      if(GetInt(e, &value))
6310                      {
6311                         FreeExpContents(exp);
6312                         exp.constant = PrintInt(value);
6313                         exp.type = constantExp;
6314                      }
6315                   }
6316                   else
6317                   {
6318                      unsigned int value = 0;
6319                      if(GetUInt(e, &value))
6320                      {
6321                         FreeExpContents(exp);
6322                         exp.constant = PrintUInt(value);
6323                         exp.type = constantExp;
6324                      }
6325                   }
6326                   break;
6327                case int64Type:
6328                   if(type.isSigned)
6329                   {
6330                      int64 value = 0;
6331                      if(GetInt64(e, &value))
6332                      {
6333                         FreeExpContents(exp);
6334                         exp.constant = PrintInt64(value);
6335                         exp.type = constantExp;
6336                      }
6337                   }
6338                   else
6339                   {
6340                      uint64 value = 0;
6341                      if(GetUInt64(e, &value))
6342                      {
6343                         FreeExpContents(exp);
6344                         exp.constant = PrintUInt64(value);
6345                         exp.type = constantExp;
6346                      }
6347                   }
6348                   break;
6349                case intPtrType:
6350                   if(type.isSigned)
6351                   {
6352                      intptr value = 0;
6353                      if(GetIntPtr(e, &value))
6354                      {
6355                         FreeExpContents(exp);
6356                         exp.constant = PrintInt64((int64)value);
6357                         exp.type = constantExp;
6358                      }
6359                   }
6360                   else
6361                   {
6362                      uintptr value = 0;
6363                      if(GetUIntPtr(e, &value))
6364                      {
6365                         FreeExpContents(exp);
6366                         exp.constant = PrintUInt64((uint64)value);
6367                         exp.type = constantExp;
6368                      }
6369                   }
6370                   break;
6371                case intSizeType:
6372                   if(type.isSigned)
6373                   {
6374                      intsize value = 0;
6375                      if(GetIntSize(e, &value))
6376                      {
6377                         FreeExpContents(exp);
6378                         exp.constant = PrintInt64((int64)value);
6379                         exp.type = constantExp;
6380                      }
6381                   }
6382                   else
6383                   {
6384                      uintsize value = 0;
6385                      if(GetUIntSize(e, &value))
6386                      {
6387                         FreeExpContents(exp);
6388                         exp.constant = PrintUInt64((uint64)value);
6389                         exp.type = constantExp;
6390                      }
6391                   }
6392                   break;
6393                case floatType:
6394                {
6395                   float value = 0;
6396                   if(GetFloat(e, &value))
6397                   {
6398                      FreeExpContents(exp);
6399                      exp.constant = PrintFloat(value);
6400                      exp.type = constantExp;
6401                   }
6402                   break;
6403                }
6404                case doubleType:
6405                {
6406                   double value = 0;
6407                   if(GetDouble(e, &value))
6408                   {
6409                      FreeExpContents(exp);
6410                      exp.constant = PrintDouble(value);
6411                      exp.type = constantExp;
6412                   }
6413                   break;
6414                }
6415             }
6416          }
6417          break;
6418       }
6419       case conditionExp:
6420       {
6421          Operand op1 { };
6422          Operand op2 { };
6423          Operand op3 { };
6424
6425          if(exp.cond.exp)
6426             // Caring only about last expression for now...
6427             ComputeExpression(exp.cond.exp->last);
6428          if(exp.cond.elseExp)
6429             ComputeExpression(exp.cond.elseExp);
6430          if(exp.cond.cond)
6431             ComputeExpression(exp.cond.cond);
6432
6433          op1 = GetOperand(exp.cond.cond);
6434          if(op1.type) op1.type.refCount++;
6435          op2 = GetOperand(exp.cond.exp->last);
6436          if(op2.type) op2.type.refCount++;
6437          op3 = GetOperand(exp.cond.elseExp);
6438          if(op3.type) op3.type.refCount++;
6439
6440          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6441          if(op1.type) FreeType(op1.type);
6442          if(op2.type) FreeType(op2.type);
6443          if(op3.type) FreeType(op3.type);
6444          break;
6445       }
6446    }
6447 }
6448
6449 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6450 {
6451    bool result = true;
6452    if(destType)
6453    {
6454       OldList converts { };
6455       Conversion convert;
6456
6457       if(destType.kind == voidType)
6458          return false;
6459
6460       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6461          result = false;
6462       if(converts.count)
6463       {
6464          // for(convert = converts.last; convert; convert = convert.prev)
6465          for(convert = converts.first; convert; convert = convert.next)
6466          {
6467             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6468             if(!empty)
6469             {
6470                Expression newExp { };
6471                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6472
6473                // TODO: Check this...
6474                *newExp = *exp;
6475                newExp.prev = null;
6476                newExp.next = null;
6477                newExp.destType = null;
6478
6479                if(convert.isGet)
6480                {
6481                   // [exp].ColorRGB
6482                   exp.type = memberExp;
6483                   exp.addedThis = true;
6484                   exp.member.exp = newExp;
6485                   FreeType(exp.member.exp.expType);
6486
6487                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6488                   exp.member.exp.expType.classObjectType = objectType;
6489                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6490                   exp.member.memberType = propertyMember;
6491                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6492                   // TESTING THIS... for (int)degrees
6493                   exp.needCast = true;
6494                   if(exp.expType) exp.expType.refCount++;
6495                   ApplyAnyObjectLogic(exp.member.exp);
6496                }
6497                else
6498                {
6499
6500                   /*if(exp.isConstant)
6501                   {
6502                      // Color { ColorRGB = [exp] };
6503                      exp.type = instanceExp;
6504                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6505                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6506                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6507                   }
6508                   else*/
6509                   {
6510                      // If not constant, don't turn it yet into an instantiation
6511                      // (Go through the deep members system first)
6512                      exp.type = memberExp;
6513                      exp.addedThis = true;
6514                      exp.member.exp = newExp;
6515
6516                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6517                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6518                         newExp.expType._class.registered.type == noHeadClass)
6519                      {
6520                         newExp.byReference = true;
6521                      }
6522
6523                      FreeType(exp.member.exp.expType);
6524                      /*exp.member.exp.expType = convert.convert.dataType;
6525                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6526                      exp.member.exp.expType = null;
6527                      if(convert.convert.dataType)
6528                      {
6529                         exp.member.exp.expType = { };
6530                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6531                         exp.member.exp.expType.refCount = 1;
6532                         exp.member.exp.expType.classObjectType = objectType;
6533                         ApplyAnyObjectLogic(exp.member.exp);
6534                      }
6535
6536                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6537                      exp.member.memberType = reverseConversionMember;
6538                      exp.expType = convert.resultType ? convert.resultType :
6539                         MkClassType(convert.convert._class.fullName);
6540                      exp.needCast = true;
6541                      if(convert.resultType) convert.resultType.refCount++;
6542                   }
6543                }
6544             }
6545             else
6546             {
6547                FreeType(exp.expType);
6548                if(convert.isGet)
6549                {
6550                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6551                   if(exp.destType.casted)
6552                      exp.needCast = true;
6553                   if(exp.expType) exp.expType.refCount++;
6554                }
6555                else
6556                {
6557                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6558                   if(exp.destType.casted)
6559                      exp.needCast = true;
6560                   if(convert.resultType)
6561                      convert.resultType.refCount++;
6562                }
6563             }
6564          }
6565          if(exp.isConstant && inCompiler)
6566             ComputeExpression(exp);
6567
6568          converts.Free(FreeConvert);
6569       }
6570
6571       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6572       {
6573          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6574       }
6575       if(!result && exp.expType && exp.destType)
6576       {
6577          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6578              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6579             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6580             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6581             result = true;
6582       }
6583    }
6584    // if(result) CheckTemplateTypes(exp);
6585    return result;
6586 }
6587
6588 void CheckTemplateTypes(Expression exp)
6589 {
6590    Expression nbExp = GetNonBracketsExp(exp);
6591    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6592       (nbExp == exp || nbExp.type != castExp))
6593    {
6594       Expression newExp { };
6595       Context context;
6596       *newExp = *exp;
6597       if(exp.destType) exp.destType.refCount++;
6598       if(exp.expType)  exp.expType.refCount++;
6599       newExp.prev = null;
6600       newExp.next = null;
6601
6602       switch(exp.expType.kind)
6603       {
6604          case doubleType:
6605             if(exp.destType.classObjectType)
6606             {
6607                // We need to pass the address, just pass it along (Undo what was done above)
6608                if(exp.destType) exp.destType.refCount--;
6609                if(exp.expType)  exp.expType.refCount--;
6610                delete newExp;
6611             }
6612             else
6613             {
6614                // If we're looking for value:
6615                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6616                OldList * specs;
6617                OldList * unionDefs = MkList();
6618                OldList * statements = MkList();
6619                context = PushContext();
6620                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6621                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6622                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6623                exp.type = extensionCompoundExp;
6624                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6625                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6626                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6627                exp.compound.compound.context = context;
6628                PopContext(context);
6629             }
6630             break;
6631          default:
6632             exp.type = castExp;
6633             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6634             exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6635             exp.needCast = true;
6636             break;
6637       }
6638    }
6639    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6640    {
6641       Expression newExp { };
6642       Context context;
6643       *newExp = *exp;
6644       if(exp.destType) exp.destType.refCount++;
6645       if(exp.expType)  exp.expType.refCount++;
6646       newExp.prev = null;
6647       newExp.next = null;
6648
6649       switch(exp.expType.kind)
6650       {
6651          case doubleType:
6652             if(exp.destType.classObjectType)
6653             {
6654                // We need to pass the address, just pass it along (Undo what was done above)
6655                if(exp.destType) exp.destType.refCount--;
6656                if(exp.expType)  exp.expType.refCount--;
6657                delete newExp;
6658             }
6659             else
6660             {
6661                // If we're looking for value:
6662                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6663                OldList * specs;
6664                OldList * unionDefs = MkList();
6665                OldList * statements = MkList();
6666                context = PushContext();
6667                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6668                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6669                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6670                exp.type = extensionCompoundExp;
6671                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6672                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6673                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6674                exp.compound.compound.context = context;
6675                PopContext(context);
6676             }
6677             break;
6678          case classType:
6679          {
6680             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6681             {
6682                exp.type = bracketsExp;
6683                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6684                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6685                ProcessExpressionType(exp.list->first);
6686                break;
6687             }
6688             else
6689             {
6690                exp.type = bracketsExp;
6691                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6692                exp.needTemplateCast = 2;
6693                newExp.needCast = true;
6694                newExp.needTemplateCast = 2;
6695                ProcessExpressionType(exp.list->first);
6696                break;
6697             }
6698          }
6699          default:
6700          {
6701             if(exp.expType.kind == templateType)
6702             {
6703                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6704                if(type)
6705                {
6706                   FreeType(exp.destType);
6707                   FreeType(exp.expType);
6708                   delete newExp;
6709                   break;
6710                }
6711             }
6712             if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6713             {
6714                exp.type = opExp;
6715                exp.op.op = '*';
6716                exp.op.exp1 = null;
6717                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6718                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6719             }
6720             else
6721             {
6722                char typeString[1024];
6723                Declarator decl;
6724                OldList * specs = MkList();
6725                typeString[0] = '\0';
6726                PrintType(exp.expType, typeString, false, false);
6727                decl = SpecDeclFromString(typeString, specs, null);
6728
6729                exp.type = castExp;
6730                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6731                exp.cast.typeName = MkTypeName(specs, decl);
6732                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6733                exp.cast.exp.needCast = true;
6734             }
6735             break;
6736          }
6737       }
6738    }
6739 }
6740 // TODO: The Symbol tree should be reorganized by namespaces
6741 // Name Space:
6742 //    - Tree of all symbols within (stored without namespace)
6743 //    - Tree of sub-namespaces
6744
6745 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6746 {
6747    int nsLen = strlen(nameSpace);
6748    Symbol symbol;
6749    // Start at the name space prefix
6750    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6751    {
6752       char * s = symbol.string;
6753       if(!strncmp(s, nameSpace, nsLen))
6754       {
6755          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6756          int c;
6757          char * namePart;
6758          for(c = strlen(s)-1; c >= 0; c--)
6759             if(s[c] == ':')
6760                break;
6761
6762          namePart = s+c+1;
6763          if(!strcmp(namePart, name))
6764          {
6765             // TODO: Error on ambiguity
6766             return symbol;
6767          }
6768       }
6769       else
6770          break;
6771    }
6772    return null;
6773 }
6774
6775 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6776 {
6777    int c;
6778    char nameSpace[1024];
6779    const char * namePart;
6780    bool gotColon = false;
6781
6782    nameSpace[0] = '\0';
6783    for(c = strlen(name)-1; c >= 0; c--)
6784       if(name[c] == ':')
6785       {
6786          gotColon = true;
6787          break;
6788       }
6789
6790    namePart = name+c+1;
6791    while(c >= 0 && name[c] == ':') c--;
6792    if(c >= 0)
6793    {
6794       // Try an exact match first
6795       Symbol symbol = (Symbol)tree.FindString(name);
6796       if(symbol)
6797          return symbol;
6798
6799       // Namespace specified
6800       memcpy(nameSpace, name, c + 1);
6801       nameSpace[c+1] = 0;
6802
6803       return ScanWithNameSpace(tree, nameSpace, namePart);
6804    }
6805    else if(gotColon)
6806    {
6807       // Looking for a global symbol, e.g. ::Sleep()
6808       Symbol symbol = (Symbol)tree.FindString(namePart);
6809       return symbol;
6810    }
6811    else
6812    {
6813       // Name only (no namespace specified)
6814       Symbol symbol = (Symbol)tree.FindString(namePart);
6815       if(symbol)
6816          return symbol;
6817       return ScanWithNameSpace(tree, "", namePart);
6818    }
6819    return null;
6820 }
6821
6822 static void ProcessDeclaration(Declaration decl);
6823
6824 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6825 {
6826 #ifdef _DEBUG
6827    //Time startTime = GetTime();
6828 #endif
6829    // Optimize this later? Do this before/less?
6830    Context ctx;
6831    Symbol symbol = null;
6832    // First, check if the identifier is declared inside the function
6833    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6834
6835    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6836    {
6837       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6838       {
6839          symbol = null;
6840          if(thisNameSpace)
6841          {
6842             char curName[1024];
6843             strcpy(curName, thisNameSpace);
6844             strcat(curName, "::");
6845             strcat(curName, name);
6846             // Try to resolve in current namespace first
6847             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6848          }
6849          if(!symbol)
6850             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6851       }
6852       else
6853          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6854
6855       if(symbol || ctx == endContext) break;
6856    }
6857    if(inCompiler && curExternal && symbol && ctx == globalContext && curExternal.symbol && symbol.id > curExternal.symbol.idCode && symbol.pointerExternal)
6858    {
6859       if(symbol.pointerExternal.type == functionExternal)
6860       {
6861          FunctionDefinition function = symbol.pointerExternal.function;
6862
6863          // Modified this recently...
6864          Context tmpContext = curContext;
6865          curContext = null;
6866          symbol.pointerExternal = MkExternalDeclaration(MkDeclaration(CopyList(function.specifiers, CopySpecifier), MkListOne(MkInitDeclarator(CopyDeclarator(function.declarator), null))));
6867          curContext = tmpContext;
6868
6869          symbol.pointerExternal.symbol = symbol;
6870
6871          // TESTING THIS:
6872          DeclareType(symbol.type, true, true);
6873
6874          ast->Insert(curExternal.prev, symbol.pointerExternal);
6875
6876          symbol.id = curExternal.symbol.idCode;
6877
6878       }
6879       else if(symbol.pointerExternal.type == declarationExternal && curExternal.symbol.idCode < symbol.pointerExternal.symbol.id) // Added id comparison because Global Function prototypes were broken
6880       {
6881          ast->Move(symbol.pointerExternal, curExternal.prev);
6882          symbol.id = curExternal.symbol.idCode;
6883       }
6884    }
6885 #ifdef _DEBUG
6886    //findSymbolTotalTime += GetTime() - startTime;
6887 #endif
6888    return symbol;
6889 }
6890
6891 static void GetTypeSpecs(Type type, OldList * specs)
6892 {
6893    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6894    switch(type.kind)
6895    {
6896       case classType:
6897       {
6898          if(type._class.registered)
6899          {
6900             if(!type._class.registered.dataType)
6901                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6902             GetTypeSpecs(type._class.registered.dataType, specs);
6903          }
6904          break;
6905       }
6906       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6907       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6908       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6909       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6910       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6911       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6912       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6913       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6914       case intType:
6915       default:
6916          ListAdd(specs, MkSpecifier(INT)); break;
6917    }
6918 }
6919
6920 static void PrintArraySize(Type arrayType, char * string)
6921 {
6922    char size[256];
6923    size[0] = '\0';
6924    strcat(size, "[");
6925    if(arrayType.enumClass)
6926       strcat(size, arrayType.enumClass.string);
6927    else if(arrayType.arraySizeExp)
6928       PrintExpression(arrayType.arraySizeExp, size);
6929    strcat(size, "]");
6930    strcat(string, size);
6931 }
6932
6933 // WARNING : This function expects a null terminated string since it recursively concatenate...
6934 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6935 {
6936    if(type)
6937    {
6938       if(printConst && type.constant)
6939          strcat(string, "const ");
6940       switch(type.kind)
6941       {
6942          case classType:
6943          {
6944             Symbol c = type._class;
6945             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6946             //       look into merging with thisclass ?
6947             if(type.classObjectType == typedObject)
6948                strcat(string, "typed_object");
6949             else if(type.classObjectType == anyObject)
6950                strcat(string, "any_object");
6951             else
6952             {
6953                if(c && c.string)
6954                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6955             }
6956             if(type.byReference)
6957                strcat(string, " &");
6958             break;
6959          }
6960          case voidType: strcat(string, "void"); break;
6961          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6962          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6963          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6964          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6965          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6966          case _BoolType: strcat(string, "_Bool"); break;
6967          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6968          case floatType: strcat(string, "float"); break;
6969          case doubleType: strcat(string, "double"); break;
6970          case structType:
6971             if(type.enumName)
6972             {
6973                strcat(string, "struct ");
6974                strcat(string, type.enumName);
6975             }
6976             else if(type.typeName)
6977                strcat(string, type.typeName);
6978             else
6979             {
6980                Type member;
6981                strcat(string, "struct { ");
6982                for(member = type.members.first; member; member = member.next)
6983                {
6984                   PrintType(member, string, true, fullName);
6985                   strcat(string,"; ");
6986                }
6987                strcat(string,"}");
6988             }
6989             break;
6990          case unionType:
6991             if(type.enumName)
6992             {
6993                strcat(string, "union ");
6994                strcat(string, type.enumName);
6995             }
6996             else if(type.typeName)
6997                strcat(string, type.typeName);
6998             else
6999             {
7000                strcat(string, "union ");
7001                strcat(string,"(unnamed)");
7002             }
7003             break;
7004          case enumType:
7005             if(type.enumName)
7006             {
7007                strcat(string, "enum ");
7008                strcat(string, type.enumName);
7009             }
7010             else if(type.typeName)
7011                strcat(string, type.typeName);
7012             else
7013                strcat(string, "int"); // "enum");
7014             break;
7015          case ellipsisType:
7016             strcat(string, "...");
7017             break;
7018          case subClassType:
7019             strcat(string, "subclass(");
7020             strcat(string, type._class ? type._class.string : "int");
7021             strcat(string, ")");
7022             break;
7023          case templateType:
7024             strcat(string, type.templateParameter.identifier.string);
7025             break;
7026          case thisClassType:
7027             strcat(string, "thisclass");
7028             break;
7029          case vaListType:
7030             strcat(string, "__builtin_va_list");
7031             break;
7032       }
7033    }
7034 }
7035
7036 static void PrintName(Type type, char * string, bool fullName)
7037 {
7038    if(type.name && type.name[0])
7039    {
7040       if(fullName)
7041          strcat(string, type.name);
7042       else
7043       {
7044          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
7045          if(name) name += 2; else name = type.name;
7046          strcat(string, name);
7047       }
7048    }
7049 }
7050
7051 static void PrintAttribs(Type type, char * string)
7052 {
7053    if(type)
7054    {
7055       if(type.dllExport)   strcat(string, "dllexport ");
7056       if(type.attrStdcall) strcat(string, "stdcall ");
7057    }
7058 }
7059
7060 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
7061 {
7062    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7063    {
7064       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
7065          PrintAttribs(type, string);
7066       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
7067          strcat(string, " const");
7068       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
7069       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7070          strcat(string, " (");
7071       if(type.kind == pointerType)
7072       {
7073          if(type.type.kind == functionType || type.type.kind == methodType)
7074             PrintAttribs(type.type, string);
7075       }
7076       if(type.kind == pointerType)
7077       {
7078          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7079             strcat(string, "*");
7080          else
7081             strcat(string, " *");
7082       }
7083       if(printConst && type.constant && type.kind == pointerType)
7084          strcat(string, " const");
7085    }
7086    else
7087       PrintTypeSpecs(type, string, fullName, printConst);
7088 }
7089
7090 static void PostPrintType(Type type, char * string, bool fullName)
7091 {
7092    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7093       strcat(string, ")");
7094    if(type.kind == arrayType)
7095       PrintArraySize(type, string);
7096    else if(type.kind == functionType)
7097    {
7098       Type param;
7099       strcat(string, "(");
7100       for(param = type.params.first; param; param = param.next)
7101       {
7102          PrintType(param, string, true, fullName);
7103          if(param.next) strcat(string, ", ");
7104       }
7105       strcat(string, ")");
7106    }
7107    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7108       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7109 }
7110
7111 // *****
7112 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7113 // *****
7114 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7115 {
7116    PrePrintType(type, string, fullName, null, printConst);
7117
7118    if(type.thisClass || (printName && type.name && type.name[0]))
7119       strcat(string, " ");
7120    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7121    {
7122       Symbol _class = type.thisClass;
7123       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7124       {
7125          if(type.classObjectType == classPointer)
7126             strcat(string, "class");
7127          else
7128             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7129       }
7130       else if(_class && _class.string)
7131       {
7132          String s = _class.string;
7133          if(fullName)
7134             strcat(string, s);
7135          else
7136          {
7137             char * name = RSearchString(s, "::", strlen(s), true, false);
7138             if(name) name += 2; else name = s;
7139             strcat(string, name);
7140          }
7141       }
7142       strcat(string, "::");
7143    }
7144
7145    if(printName && type.name)
7146       PrintName(type, string, fullName);
7147    PostPrintType(type, string, fullName);
7148    if(type.bitFieldCount)
7149    {
7150       char count[100];
7151       sprintf(count, ":%d", type.bitFieldCount);
7152       strcat(string, count);
7153    }
7154 }
7155
7156 void PrintType(Type type, char * string, bool printName, bool fullName)
7157 {
7158    _PrintType(type, string, printName, fullName, true);
7159 }
7160
7161 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7162 {
7163    _PrintType(type, string, printName, fullName, false);
7164 }
7165
7166 static Type FindMember(Type type, char * string)
7167 {
7168    Type memberType;
7169    for(memberType = type.members.first; memberType; memberType = memberType.next)
7170    {
7171       if(!memberType.name)
7172       {
7173          Type subType = FindMember(memberType, string);
7174          if(subType)
7175             return subType;
7176       }
7177       else if(!strcmp(memberType.name, string))
7178          return memberType;
7179    }
7180    return null;
7181 }
7182
7183 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7184 {
7185    Type memberType;
7186    for(memberType = type.members.first; memberType; memberType = memberType.next)
7187    {
7188       if(!memberType.name)
7189       {
7190          Type subType = FindMember(memberType, string);
7191          if(subType)
7192          {
7193             *offset += memberType.offset;
7194             return subType;
7195          }
7196       }
7197       else if(!strcmp(memberType.name, string))
7198       {
7199          *offset += memberType.offset;
7200          return memberType;
7201       }
7202    }
7203    return null;
7204 }
7205
7206 public bool GetParseError() { return parseError; }
7207
7208 Expression ParseExpressionString(char * expression)
7209 {
7210    parseError = false;
7211
7212    fileInput = TempFile { };
7213    fileInput.Write(expression, 1, strlen(expression));
7214    fileInput.Seek(0, start);
7215
7216    echoOn = false;
7217    parsedExpression = null;
7218    resetScanner();
7219    expression_yyparse();
7220    delete fileInput;
7221
7222    return parsedExpression;
7223 }
7224
7225 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7226 {
7227    Identifier id = exp.identifier;
7228    Method method = null;
7229    Property prop = null;
7230    DataMember member = null;
7231    ClassProperty classProp = null;
7232
7233    if(_class && _class.type == enumClass)
7234    {
7235       NamedLink64 value = null;
7236       Class enumClass = eSystem_FindClass(privateModule, "enum");
7237       if(enumClass)
7238       {
7239          Class baseClass;
7240          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7241          {
7242             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7243             for(value = e.values.first; value; value = value.next)
7244             {
7245                if(!strcmp(value.name, id.string))
7246                   break;
7247             }
7248             if(value)
7249             {
7250                char constant[256];
7251
7252                FreeExpContents(exp);
7253
7254                exp.type = constantExp;
7255                exp.isConstant = true;
7256                if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7257                   sprintf(constant, FORMAT64D, value.data);
7258                else
7259                   sprintf(constant, FORMAT64HEX, value.data);
7260                exp.constant = CopyString(constant);
7261                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7262                exp.expType = MkClassType(baseClass.fullName);
7263                break;
7264             }
7265          }
7266       }
7267       if(value)
7268          return true;
7269    }
7270    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7271    {
7272       ProcessMethodType(method);
7273       exp.expType = Type
7274       {
7275          refCount = 1;
7276          kind = methodType;
7277          method = method;
7278          // Crash here?
7279          // TOCHECK: Put it back to what it was...
7280          // methodClass = _class;
7281          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7282       };
7283       //id._class = null;
7284       return true;
7285    }
7286    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7287    {
7288       if(!prop.dataType)
7289          ProcessPropertyType(prop);
7290       exp.expType = prop.dataType;
7291       if(prop.dataType) prop.dataType.refCount++;
7292       return true;
7293    }
7294    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7295    {
7296       if(!member.dataType)
7297          member.dataType = ProcessTypeString(member.dataTypeString, false);
7298       exp.expType = member.dataType;
7299       if(member.dataType) member.dataType.refCount++;
7300       return true;
7301    }
7302    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7303    {
7304       if(!classProp.dataType)
7305          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7306
7307       if(classProp.constant)
7308       {
7309          FreeExpContents(exp);
7310
7311          exp.isConstant = true;
7312          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7313          {
7314             //char constant[256];
7315             exp.type = stringExp;
7316             exp.constant = QMkString((char *)classProp.Get(_class));
7317          }
7318          else
7319          {
7320             char constant[256];
7321             exp.type = constantExp;
7322             sprintf(constant, "%d", (int)classProp.Get(_class));
7323             exp.constant = CopyString(constant);
7324          }
7325       }
7326       else
7327       {
7328          // TO IMPLEMENT...
7329       }
7330
7331       exp.expType = classProp.dataType;
7332       if(classProp.dataType) classProp.dataType.refCount++;
7333       return true;
7334    }
7335    return false;
7336 }
7337
7338 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7339 {
7340    BinaryTree * tree = &nameSpace.functions;
7341    GlobalData data = (GlobalData)tree->FindString(name);
7342    NameSpace * child;
7343    if(!data)
7344    {
7345       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7346       {
7347          data = ScanGlobalData(child, name);
7348          if(data)
7349             break;
7350       }
7351    }
7352    return data;
7353 }
7354
7355 static GlobalData FindGlobalData(char * name)
7356 {
7357    int start = 0, c;
7358    NameSpace * nameSpace;
7359    nameSpace = globalData;
7360    for(c = 0; name[c]; c++)
7361    {
7362       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7363       {
7364          NameSpace * newSpace;
7365          char * spaceName = new char[c - start + 1];
7366          strncpy(spaceName, name + start, c - start);
7367          spaceName[c-start] = '\0';
7368          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7369          delete spaceName;
7370          if(!newSpace)
7371             return null;
7372          nameSpace = newSpace;
7373          if(name[c] == ':') c++;
7374          start = c+1;
7375       }
7376    }
7377    if(c - start)
7378    {
7379       return ScanGlobalData(nameSpace, name + start);
7380    }
7381    return null;
7382 }
7383
7384 static int definedExpStackPos;
7385 static void * definedExpStack[512];
7386
7387 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7388 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7389 {
7390    Expression prev = checkedExp.prev, next = checkedExp.next;
7391
7392    FreeExpContents(checkedExp);
7393    FreeType(checkedExp.expType);
7394    FreeType(checkedExp.destType);
7395
7396    *checkedExp = *newExp;
7397
7398    delete newExp;
7399
7400    checkedExp.prev = prev;
7401    checkedExp.next = next;
7402 }
7403
7404 void ApplyAnyObjectLogic(Expression e)
7405 {
7406    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7407 #ifdef _DEBUG
7408    char debugExpString[4096];
7409    debugExpString[0] = '\0';
7410    PrintExpression(e, debugExpString);
7411 #endif
7412
7413    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7414    {
7415       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7416       //ellipsisDestType = destType;
7417       if(e && e.expType)
7418       {
7419          Type type = e.expType;
7420          Class _class = null;
7421          //Type destType = e.destType;
7422
7423          if(type.kind == classType && type._class && type._class.registered)
7424          {
7425             _class = type._class.registered;
7426          }
7427          else if(type.kind == subClassType)
7428          {
7429             _class = FindClass("ecere::com::Class").registered;
7430          }
7431          else
7432          {
7433             char string[1024] = "";
7434             Symbol classSym;
7435
7436             PrintTypeNoConst(type, string, false, true);
7437             classSym = FindClass(string);
7438             if(classSym) _class = classSym.registered;
7439          }
7440
7441          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...
7442             (!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))) ||
7443             destType.byReference)))
7444          {
7445             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7446             {
7447                Expression checkedExp = e, newExp;
7448
7449                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7450                {
7451                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7452                   {
7453                      if(checkedExp.type == extensionCompoundExp)
7454                      {
7455                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7456                      }
7457                      else
7458                         checkedExp = checkedExp.list->last;
7459                   }
7460                   else if(checkedExp.type == castExp)
7461                      checkedExp = checkedExp.cast.exp;
7462                }
7463
7464                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7465                {
7466                   newExp = checkedExp.op.exp2;
7467                   checkedExp.op.exp2 = null;
7468                   FreeExpContents(checkedExp);
7469
7470                   if(e.expType && e.expType.passAsTemplate)
7471                   {
7472                      char size[100];
7473                      ComputeTypeSize(e.expType);
7474                      sprintf(size, "%d", e.expType.size);
7475                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7476                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7477                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7478                   }
7479
7480                   ReplaceExpContents(checkedExp, newExp);
7481                   e.byReference = true;
7482                }
7483                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7484                {
7485                   Expression checkedExp; //, newExp;
7486
7487                   {
7488                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7489                      bool hasAddress =
7490                         e.type == identifierExp ||
7491                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7492                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7493                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7494                         e.type == indexExp;
7495
7496                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7497                      {
7498                         Context context = PushContext();
7499                         Declarator decl;
7500                         OldList * specs = MkList();
7501                         char typeString[1024];
7502                         Expression newExp { };
7503
7504                         typeString[0] = '\0';
7505                         *newExp = *e;
7506
7507                         //if(e.destType) e.destType.refCount++;
7508                         // if(exp.expType) exp.expType.refCount++;
7509                         newExp.prev = null;
7510                         newExp.next = null;
7511                         newExp.expType = null;
7512
7513                         PrintTypeNoConst(e.expType, typeString, false, true);
7514                         decl = SpecDeclFromString(typeString, specs, null);
7515                         newExp.destType = ProcessType(specs, decl);
7516
7517                         curContext = context;
7518
7519                         // We need a current compound for this
7520                         if(curCompound)
7521                         {
7522                            char name[100];
7523                            OldList * stmts = MkList();
7524                            e.type = extensionCompoundExp;
7525                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7526                            if(!curCompound.compound.declarations)
7527                               curCompound.compound.declarations = MkList();
7528                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7529                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7530                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7531                            e.compound = MkCompoundStmt(null, stmts);
7532                         }
7533                         else
7534                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7535
7536                         /*
7537                         e.compound = MkCompoundStmt(
7538                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7539                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7540
7541                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7542                         */
7543
7544                         {
7545                            Type type = e.destType;
7546                            e.destType = { };
7547                            CopyTypeInto(e.destType, type);
7548                            e.destType.refCount = 1;
7549                            e.destType.classObjectType = none;
7550                            FreeType(type);
7551                         }
7552
7553                         e.compound.compound.context = context;
7554                         PopContext(context);
7555                         curContext = context.parent;
7556                      }
7557                   }
7558
7559                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7560                   checkedExp = e;
7561                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7562                   {
7563                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7564                      {
7565                         if(checkedExp.type == extensionCompoundExp)
7566                         {
7567                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7568                         }
7569                         else
7570                            checkedExp = checkedExp.list->last;
7571                      }
7572                      else if(checkedExp.type == castExp)
7573                         checkedExp = checkedExp.cast.exp;
7574                   }
7575                   {
7576                      Expression operand { };
7577                      operand = *checkedExp;
7578                      checkedExp.Clear();
7579                      checkedExp.destType = ProcessTypeString("void *", false);
7580                      checkedExp.expType = checkedExp.destType;
7581                      checkedExp.destType.refCount++;
7582
7583                      checkedExp.type = opExp;
7584                      checkedExp.op.op = '&';
7585                      checkedExp.op.exp1 = null;
7586                      checkedExp.op.exp2 = operand;
7587
7588                      //newExp = MkExpOp(null, '&', checkedExp);
7589                   }
7590                   //ReplaceExpContents(checkedExp, newExp);
7591                }
7592             }
7593          }
7594       }
7595    }
7596    {
7597       // If expression type is a simple class, make it an address
7598       // FixReference(e, true);
7599    }
7600 //#if 0
7601    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7602       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7603          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7604    {
7605       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"))
7606       {
7607          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7608       }
7609       else
7610       {
7611          Expression thisExp { };
7612
7613          *thisExp = *e;
7614          thisExp.prev = null;
7615          thisExp.next = null;
7616          e.Clear();
7617
7618          e.type = bracketsExp;
7619          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7620          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7621             ((Expression)e.list->first).byReference = true;
7622
7623          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7624          {
7625             e.expType = thisExp.expType;
7626             e.expType.refCount++;
7627          }
7628          else*/
7629          {
7630             e.expType = { };
7631             CopyTypeInto(e.expType, thisExp.expType);
7632             e.expType.byReference = false;
7633             e.expType.refCount = 1;
7634
7635             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7636                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7637             {
7638                e.expType.classObjectType = none;
7639             }
7640          }
7641       }
7642    }
7643 // TOFIX: Try this for a nice IDE crash!
7644 //#endif
7645    // The other way around
7646    else
7647 //#endif
7648    if(destType && e.expType &&
7649          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7650          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7651          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7652    {
7653       if(destType.kind == ellipsisType)
7654       {
7655          Compiler_Error($"Unspecified type\n");
7656       }
7657       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7658       {
7659          bool byReference = e.expType.byReference;
7660          Expression thisExp { };
7661          Declarator decl;
7662          OldList * specs = MkList();
7663          char typeString[1024]; // Watch buffer overruns
7664          Type type;
7665          ClassObjectType backupClassObjectType;
7666          bool backupByReference;
7667
7668          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7669             type = e.expType;
7670          else
7671             type = destType;
7672
7673          backupClassObjectType = type.classObjectType;
7674          backupByReference = type.byReference;
7675
7676          type.classObjectType = none;
7677          type.byReference = false;
7678
7679          typeString[0] = '\0';
7680          PrintType(type, typeString, false, true);
7681          decl = SpecDeclFromString(typeString, specs, null);
7682
7683          type.classObjectType = backupClassObjectType;
7684          type.byReference = backupByReference;
7685
7686          *thisExp = *e;
7687          thisExp.prev = null;
7688          thisExp.next = null;
7689          e.Clear();
7690
7691          if( ( type.kind == classType && type._class && type._class.registered &&
7692                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7693                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7694              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7695              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7696          {
7697             e.type = opExp;
7698             e.op.op = '*';
7699             e.op.exp1 = null;
7700             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7701
7702             e.expType = { };
7703             CopyTypeInto(e.expType, type);
7704             e.expType.byReference = false;
7705             e.expType.refCount = 1;
7706          }
7707          else
7708          {
7709             e.type = castExp;
7710             e.cast.typeName = MkTypeName(specs, decl);
7711             e.cast.exp = thisExp;
7712             e.byReference = true;
7713             e.expType = type;
7714             type.refCount++;
7715          }
7716          e.destType = destType;
7717          destType.refCount++;
7718       }
7719    }
7720 }
7721
7722 void ApplyLocation(Expression exp, Location loc)
7723 {
7724    exp.loc = loc;
7725    switch(exp.type)
7726    {
7727       case opExp:
7728          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7729          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7730          break;
7731       case bracketsExp:
7732          if(exp.list)
7733          {
7734             Expression e;
7735             for(e = exp.list->first; e; e = e.next)
7736                ApplyLocation(e, loc);
7737          }
7738          break;
7739       case indexExp:
7740          if(exp.index.index)
7741          {
7742             Expression e;
7743             for(e = exp.index.index->first; e; e = e.next)
7744                ApplyLocation(e, loc);
7745          }
7746          if(exp.index.exp)
7747             ApplyLocation(exp.index.exp, loc);
7748          break;
7749       case callExp:
7750          if(exp.call.arguments)
7751          {
7752             Expression arg;
7753             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7754                ApplyLocation(arg, loc);
7755          }
7756          if(exp.call.exp)
7757             ApplyLocation(exp.call.exp, loc);
7758          break;
7759       case memberExp:
7760       case pointerExp:
7761          if(exp.member.exp)
7762             ApplyLocation(exp.member.exp, loc);
7763          break;
7764       case castExp:
7765          if(exp.cast.exp)
7766             ApplyLocation(exp.cast.exp, loc);
7767          break;
7768       case conditionExp:
7769          if(exp.cond.exp)
7770          {
7771             Expression e;
7772             for(e = exp.cond.exp->first; e; e = e.next)
7773                ApplyLocation(e, loc);
7774          }
7775          if(exp.cond.cond)
7776             ApplyLocation(exp.cond.cond, loc);
7777          if(exp.cond.elseExp)
7778             ApplyLocation(exp.cond.elseExp, loc);
7779          break;
7780       case vaArgExp:
7781          if(exp.vaArg.exp)
7782             ApplyLocation(exp.vaArg.exp, loc);
7783          break;
7784       default:
7785          break;
7786    }
7787 }
7788
7789 void ProcessExpressionType(Expression exp)
7790 {
7791    bool unresolved = false;
7792    Location oldyylloc = yylloc;
7793    bool notByReference = false;
7794 #ifdef _DEBUG
7795    char debugExpString[4096];
7796    debugExpString[0] = '\0';
7797    PrintExpression(exp, debugExpString);
7798 #endif
7799    if(!exp || exp.expType)
7800       return;
7801
7802    //eSystem_Logf("%s\n", expString);
7803
7804    // Testing this here
7805    yylloc = exp.loc;
7806    switch(exp.type)
7807    {
7808       case identifierExp:
7809       {
7810          Identifier id = exp.identifier;
7811          if(!id || !topContext) return;
7812
7813          // DOING THIS LATER NOW...
7814          if(id._class && id._class.name)
7815          {
7816             id.classSym = id._class.symbol; // FindClass(id._class.name);
7817             /* TODO: Name Space Fix ups
7818             if(!id.classSym)
7819                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7820             */
7821          }
7822
7823          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7824          {
7825             exp.expType = ProcessTypeString("Module", true);
7826             break;
7827          }
7828          else */
7829          if(!strcmp(id.string, "__runtimePlatform"))
7830          {
7831             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7832             break;
7833          }
7834          else if(strstr(id.string, "__ecereClass") == id.string)
7835          {
7836             exp.expType = ProcessTypeString("ecere::com::Class", true);
7837             break;
7838          }
7839          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7840          {
7841             // Added this here as well
7842             ReplaceClassMembers(exp, thisClass);
7843             if(exp.type != identifierExp)
7844             {
7845                ProcessExpressionType(exp);
7846                break;
7847             }
7848
7849             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7850                break;
7851          }
7852          else
7853          {
7854             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7855             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7856             if(!symbol/* && exp.destType*/)
7857             {
7858                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7859                   break;
7860                else
7861                {
7862                   if(thisClass)
7863                   {
7864                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7865                      if(exp.type != identifierExp)
7866                      {
7867                         ProcessExpressionType(exp);
7868                         break;
7869                      }
7870                   }
7871                   // Static methods called from inside the _class
7872                   else if(currentClass && !id._class)
7873                   {
7874                      if(ResolveIdWithClass(exp, currentClass, true))
7875                         break;
7876                   }
7877                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7878                }
7879             }
7880
7881             // If we manage to resolve this symbol
7882             if(symbol)
7883             {
7884                Type type = symbol.type;
7885                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7886
7887                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7888                {
7889                   Context context = SetupTemplatesContext(_class);
7890                   type = ReplaceThisClassType(_class);
7891                   FinishTemplatesContext(context);
7892                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7893                }
7894
7895                FreeSpecifier(id._class);
7896                id._class = null;
7897                delete id.string;
7898                id.string = CopyString(symbol.string);
7899
7900                id.classSym = null;
7901                exp.expType = type;
7902                if(type)
7903                   type.refCount++;
7904
7905                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7906                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7907                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7908                   // Add missing cases here... enum Classes...
7909                   exp.isConstant = true;
7910
7911                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7912                if(symbol.isParam || !strcmp(id.string, "this"))
7913                {
7914                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7915                      exp.byReference = true;
7916
7917                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7918                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7919                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7920                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7921                   {
7922                      Identifier id = exp.identifier;
7923                      exp.type = bracketsExp;
7924                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7925                   }*/
7926                }
7927
7928                if(symbol.isIterator)
7929                {
7930                   if(symbol.isIterator == 3)
7931                   {
7932                      exp.type = bracketsExp;
7933                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7934                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7935                      exp.expType = null;
7936                      ProcessExpressionType(exp);
7937                   }
7938                   else if(symbol.isIterator != 4)
7939                   {
7940                      exp.type = memberExp;
7941                      exp.member.exp = MkExpIdentifier(exp.identifier);
7942                      exp.member.exp.expType = exp.expType;
7943                      /*if(symbol.isIterator == 6)
7944                         exp.member.member = MkIdentifier("key");
7945                      else*/
7946                         exp.member.member = MkIdentifier("data");
7947                      exp.expType = null;
7948                      ProcessExpressionType(exp);
7949                   }
7950                }
7951                break;
7952             }
7953             else
7954             {
7955                DefinedExpression definedExp = null;
7956                if(thisNameSpace && !(id._class && !id._class.name))
7957                {
7958                   char name[1024];
7959                   strcpy(name, thisNameSpace);
7960                   strcat(name, "::");
7961                   strcat(name, id.string);
7962                   definedExp = eSystem_FindDefine(privateModule, name);
7963                }
7964                if(!definedExp)
7965                   definedExp = eSystem_FindDefine(privateModule, id.string);
7966                if(definedExp)
7967                {
7968                   int c;
7969                   for(c = 0; c<definedExpStackPos; c++)
7970                      if(definedExpStack[c] == definedExp)
7971                         break;
7972                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7973                   {
7974                      Location backupYylloc = yylloc;
7975                      File backInput = fileInput;
7976                      definedExpStack[definedExpStackPos++] = definedExp;
7977
7978                      fileInput = TempFile { };
7979                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7980                      fileInput.Seek(0, start);
7981
7982                      echoOn = false;
7983                      parsedExpression = null;
7984                      resetScanner();
7985                      expression_yyparse();
7986                      delete fileInput;
7987                      if(backInput)
7988                         fileInput = backInput;
7989
7990                      yylloc = backupYylloc;
7991
7992                      if(parsedExpression)
7993                      {
7994                         FreeIdentifier(id);
7995                         exp.type = bracketsExp;
7996                         exp.list = MkListOne(parsedExpression);
7997                         ApplyLocation(parsedExpression, yylloc);
7998                         ProcessExpressionType(exp);
7999                         definedExpStackPos--;
8000                         return;
8001                      }
8002                      definedExpStackPos--;
8003                   }
8004                   else
8005                   {
8006                      if(inCompiler)
8007                      {
8008                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
8009                      }
8010                   }
8011                }
8012                else
8013                {
8014                   GlobalData data = null;
8015                   if(thisNameSpace && !(id._class && !id._class.name))
8016                   {
8017                      char name[1024];
8018                      strcpy(name, thisNameSpace);
8019                      strcat(name, "::");
8020                      strcat(name, id.string);
8021                      data = FindGlobalData(name);
8022                   }
8023                   if(!data)
8024                      data = FindGlobalData(id.string);
8025                   if(data)
8026                   {
8027                      DeclareGlobalData(data);
8028                      exp.expType = data.dataType;
8029                      if(data.dataType) data.dataType.refCount++;
8030
8031                      delete id.string;
8032                      id.string = CopyString(data.fullName);
8033                      FreeSpecifier(id._class);
8034                      id._class = null;
8035
8036                      break;
8037                   }
8038                   else
8039                   {
8040                      GlobalFunction function = null;
8041                      if(thisNameSpace && !(id._class && !id._class.name))
8042                      {
8043                         char name[1024];
8044                         strcpy(name, thisNameSpace);
8045                         strcat(name, "::");
8046                         strcat(name, id.string);
8047                         function = eSystem_FindFunction(privateModule, name);
8048                      }
8049                      if(!function)
8050                         function = eSystem_FindFunction(privateModule, id.string);
8051                      if(function)
8052                      {
8053                         char name[1024];
8054                         delete id.string;
8055                         id.string = CopyString(function.name);
8056                         name[0] = 0;
8057
8058                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8059                            strcpy(name, "__ecereFunction_");
8060                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8061                         if(DeclareFunction(function, name))
8062                         {
8063                            delete id.string;
8064                            id.string = CopyString(name);
8065                         }
8066                         exp.expType = function.dataType;
8067                         if(function.dataType) function.dataType.refCount++;
8068
8069                         FreeSpecifier(id._class);
8070                         id._class = null;
8071
8072                         break;
8073                      }
8074                   }
8075                }
8076             }
8077          }
8078          unresolved = true;
8079          break;
8080       }
8081       case instanceExp:
8082       {
8083          // Class _class;
8084          // Symbol classSym;
8085
8086          if(!exp.instance._class)
8087          {
8088             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8089             {
8090                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8091             }
8092          }
8093
8094          //classSym = FindClass(exp.instance._class.fullName);
8095          //_class = classSym ? classSym.registered : null;
8096
8097          ProcessInstantiationType(exp.instance);
8098
8099          exp.isConstant = exp.instance.isConstant;
8100
8101          /*
8102          if(_class.type == unitClass && _class.base.type != systemClass)
8103          {
8104             {
8105                Type destType = exp.destType;
8106
8107                exp.destType = MkClassType(_class.base.fullName);
8108                exp.expType = MkClassType(_class.fullName);
8109                CheckExpressionType(exp, exp.destType, true);
8110
8111                exp.destType = destType;
8112             }
8113             exp.expType = MkClassType(_class.fullName);
8114          }
8115          else*/
8116          if(exp.instance._class)
8117          {
8118             exp.expType = MkClassType(exp.instance._class.name);
8119             /*if(exp.expType._class && exp.expType._class.registered &&
8120                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8121                exp.expType.byReference = true;*/
8122          }
8123          break;
8124       }
8125       case constantExp:
8126       {
8127          if(!exp.expType)
8128          {
8129             char * constant = exp.constant;
8130             Type type
8131             {
8132                refCount = 1;
8133                constant = true;
8134             };
8135             exp.expType = type;
8136
8137             if(constant[0] == '\'')
8138             {
8139                if((int)((byte *)constant)[1] > 127)
8140                {
8141                   int nb;
8142                   unichar ch = UTF8GetChar(constant + 1, &nb);
8143                   if(nb < 2) ch = constant[1];
8144                   delete constant;
8145                   exp.constant = PrintUInt(ch);
8146                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8147                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8148                   type._class = FindClass("unichar");
8149
8150                   type.isSigned = false;
8151                }
8152                else
8153                {
8154                   type.kind = charType;
8155                   type.isSigned = true;
8156                }
8157             }
8158             else
8159             {
8160                char * dot = strchr(constant, '.');
8161                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8162                char * exponent;
8163                if(isHex)
8164                {
8165                   exponent = strchr(constant, 'p');
8166                   if(!exponent) exponent = strchr(constant, 'P');
8167                }
8168                else
8169                {
8170                   exponent = strchr(constant, 'e');
8171                   if(!exponent) exponent = strchr(constant, 'E');
8172                }
8173
8174                if(dot || exponent)
8175                {
8176                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8177                      type.kind = floatType;
8178                   else
8179                      type.kind = doubleType;
8180                   type.isSigned = true;
8181                }
8182                else
8183                {
8184                   bool isSigned = constant[0] == '-';
8185                   char * endP = null;
8186                   int64 i64 = strtoll(constant, &endP, 0);
8187                   uint64 ui64 = strtoull(constant, &endP, 0);
8188                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll"));
8189                   if(isSigned)
8190                   {
8191                      if(i64 < MININT)
8192                         is64Bit = true;
8193                   }
8194                   else
8195                   {
8196                      if(ui64 > MAXINT)
8197                      {
8198                         if(ui64 > MAXDWORD)
8199                         {
8200                            is64Bit = true;
8201                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8202                               isSigned = true;
8203                         }
8204                      }
8205                      else if(constant[0] != '0' || !constant[1])
8206                         isSigned = true;
8207                   }
8208                   type.kind = is64Bit ? int64Type : intType;
8209                   type.isSigned = isSigned;
8210                }
8211             }
8212             exp.isConstant = true;
8213             if(exp.destType && exp.destType.kind == doubleType)
8214                type.kind = doubleType;
8215             else if(exp.destType && exp.destType.kind == floatType)
8216                type.kind = floatType;
8217             else if(exp.destType && exp.destType.kind == int64Type)
8218                type.kind = int64Type;
8219          }
8220          break;
8221       }
8222       case stringExp:
8223       {
8224          exp.isConstant = true;      // Why wasn't this constant?
8225          exp.expType = Type
8226          {
8227             refCount = 1;
8228             kind = pointerType;
8229             type = Type
8230             {
8231                refCount = 1;
8232                kind = charType;
8233                constant = true;
8234                isSigned = true;
8235             }
8236          };
8237          break;
8238       }
8239       case newExp:
8240       case new0Exp:
8241          ProcessExpressionType(exp._new.size);
8242          exp.expType = Type
8243          {
8244             refCount = 1;
8245             kind = pointerType;
8246             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8247          };
8248          DeclareType(exp.expType.type, false, false);
8249          break;
8250       case renewExp:
8251       case renew0Exp:
8252          ProcessExpressionType(exp._renew.size);
8253          ProcessExpressionType(exp._renew.exp);
8254          exp.expType = Type
8255          {
8256             refCount = 1;
8257             kind = pointerType;
8258             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8259          };
8260          DeclareType(exp.expType.type, false, false);
8261          break;
8262       case opExp:
8263       {
8264          bool assign = false, boolResult = false, boolOps = false;
8265          Type type1 = null, type2 = null;
8266          bool useDestType = false, useSideType = false;
8267          Location oldyylloc = yylloc;
8268          bool useSideUnit = false;
8269          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8270
8271          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8272          Type dummy
8273          {
8274             count = 1;
8275             refCount = 1;
8276          };
8277
8278          switch(exp.op.op)
8279          {
8280             // Assignment Operators
8281             case '=':
8282             case MUL_ASSIGN:
8283             case DIV_ASSIGN:
8284             case MOD_ASSIGN:
8285             case ADD_ASSIGN:
8286             case SUB_ASSIGN:
8287             case LEFT_ASSIGN:
8288             case RIGHT_ASSIGN:
8289             case AND_ASSIGN:
8290             case XOR_ASSIGN:
8291             case OR_ASSIGN:
8292                assign = true;
8293                break;
8294             // boolean Operators
8295             case '!':
8296                // Expect boolean operators
8297                //boolOps = true;
8298                //boolResult = true;
8299                break;
8300             case AND_OP:
8301             case OR_OP:
8302                // Expect boolean operands
8303                boolOps = true;
8304                boolResult = true;
8305                break;
8306             // Comparisons
8307             case EQ_OP:
8308             case '<':
8309             case '>':
8310             case LE_OP:
8311             case GE_OP:
8312             case NE_OP:
8313                // Gives boolean result
8314                boolResult = true;
8315                useSideType = true;
8316                break;
8317             case '+':
8318             case '-':
8319                useSideUnit = true;
8320                useSideType = true;
8321                useDestType = true;
8322                break;
8323
8324             case LEFT_OP:
8325             case RIGHT_OP:
8326                useSideType = true;
8327                useDestType = true;
8328                break;
8329
8330             case '|':
8331             case '^':
8332                useSideType = true;
8333                useDestType = true;
8334                break;
8335
8336             case '/':
8337             case '%':
8338                useSideType = true;
8339                useDestType = true;
8340                break;
8341             case '&':
8342             case '*':
8343                if(exp.op.exp1)
8344                {
8345                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8346                   useSideType = true;
8347                   useDestType = true;
8348                }
8349                break;
8350
8351             /*// Implement speed etc.
8352             case '*':
8353             case '/':
8354                break;
8355             */
8356          }
8357          if(exp.op.op == '&')
8358          {
8359             // Added this here earlier for Iterator address as key
8360             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8361             {
8362                Identifier id = exp.op.exp2.identifier;
8363                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8364                if(symbol && symbol.isIterator == 2)
8365                {
8366                   exp.type = memberExp;
8367                   exp.member.exp = exp.op.exp2;
8368                   exp.member.member = MkIdentifier("key");
8369                   exp.expType = null;
8370                   exp.op.exp2.expType = symbol.type;
8371                   symbol.type.refCount++;
8372                   ProcessExpressionType(exp);
8373                   FreeType(dummy);
8374                   break;
8375                }
8376                // exp.op.exp2.usage.usageRef = true;
8377             }
8378          }
8379
8380          //dummy.kind = TypeDummy;
8381          if(exp.op.exp1)
8382          {
8383             // Added this check here to use the dest type only for units derived from the base unit
8384             // So that untyped units will use the side unit as opposed to the untyped destination unit
8385             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8386             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8387                useDestType = false;
8388
8389             if(destClass && useDestType &&
8390               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8391
8392               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8393             {
8394                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8395                exp.op.exp1.destType = exp.destType;
8396                exp.op.exp1.opDestType = true;
8397                if(exp.destType)
8398                   exp.destType.refCount++;
8399             }
8400             else if(!assign)
8401             {
8402                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8403                exp.op.exp1.destType = dummy;
8404                dummy.refCount++;
8405             }
8406
8407             // TESTING THIS HERE...
8408             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8409                ProcessExpressionType(exp.op.exp1);
8410             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8411
8412             exp.op.exp1.opDestType = false;
8413
8414             // Fix for unit and ++ / --
8415             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8416                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8417             {
8418                exp.op.exp2 = MkExpConstant("1");
8419                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8420                assign = true;
8421             }
8422
8423             if(exp.op.exp1.destType == dummy)
8424             {
8425                FreeType(dummy);
8426                exp.op.exp1.destType = null;
8427             }
8428             type1 = exp.op.exp1.expType;
8429          }
8430
8431          if(exp.op.exp2)
8432          {
8433             char expString[10240];
8434             expString[0] = '\0';
8435             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8436             {
8437                if(exp.op.exp1)
8438                {
8439                   exp.op.exp2.destType = exp.op.exp1.expType;
8440                   if(exp.op.exp1.expType)
8441                      exp.op.exp1.expType.refCount++;
8442                }
8443                else
8444                {
8445                   exp.op.exp2.destType = exp.destType;
8446                   if(!exp.op.exp1 || exp.op.op != '&')
8447                      exp.op.exp2.opDestType = true;
8448                   if(exp.destType)
8449                      exp.destType.refCount++;
8450                }
8451
8452                if(type1) type1.refCount++;
8453                exp.expType = type1;
8454             }
8455             else if(assign)
8456             {
8457                if(inCompiler)
8458                   PrintExpression(exp.op.exp2, expString);
8459
8460                if(type1 && type1.kind == pointerType)
8461                {
8462                   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 ||
8463                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8464                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8465                   else if(exp.op.op == '=')
8466                   {
8467                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8468                      exp.op.exp2.destType = type1;
8469                      if(type1)
8470                         type1.refCount++;
8471                   }
8472                }
8473                else
8474                {
8475                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8476                   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/* ||
8477                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8478                   else
8479                   {
8480                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8481                      exp.op.exp2.destType = type1;
8482                      if(type1)
8483                         type1.refCount++;
8484                   }
8485                }
8486                if(type1) type1.refCount++;
8487                exp.expType = type1;
8488             }
8489             else if(destClass &&
8490                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8491                   (destClass.type == enumClass && useDestType)))
8492             {
8493                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8494                exp.op.exp2.destType = exp.destType;
8495                if(exp.op.op != '&')
8496                   exp.op.exp2.opDestType = true;
8497                if(exp.destType)
8498                   exp.destType.refCount++;
8499             }
8500             else
8501             {
8502                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8503                exp.op.exp2.destType = dummy;
8504                dummy.refCount++;
8505             }
8506
8507             // TESTING THIS HERE... (DANGEROUS)
8508             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8509                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8510             {
8511                FreeType(exp.op.exp2.destType);
8512                exp.op.exp2.destType = type1;
8513                type1.refCount++;
8514             }
8515             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8516             // Cannot lose the cast on a sizeof
8517             if(exp.op.op == SIZEOF)
8518             {
8519                Expression e = exp.op.exp2;
8520                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8521                {
8522                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8523                   {
8524                      if(e.type == extensionCompoundExp)
8525                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8526                      else
8527                         e = e.list->last;
8528                   }
8529                }
8530                if(e.type == castExp && e.cast.exp)
8531                   e.cast.exp.needCast = true;
8532             }
8533             ProcessExpressionType(exp.op.exp2);
8534             exp.op.exp2.opDestType = false;
8535             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8536
8537             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8538             {
8539                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)
8540                {
8541                   if(exp.op.op != '=' && type1.type.kind == voidType)
8542                      Compiler_Error($"void *: unknown size\n");
8543                }
8544                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||
8545                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8546                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8547                               exp.op.exp2.expType._class.registered.type == structClass ||
8548                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8549                {
8550                   if(exp.op.op == ADD_ASSIGN)
8551                      Compiler_Error($"cannot add two pointers\n");
8552                }
8553                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8554                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8555                {
8556                   if(exp.op.op == ADD_ASSIGN)
8557                      Compiler_Error($"cannot add two pointers\n");
8558                }
8559                else if(inCompiler)
8560                {
8561                   char type1String[1024];
8562                   char type2String[1024];
8563                   type1String[0] = '\0';
8564                   type2String[0] = '\0';
8565
8566                   PrintType(exp.op.exp2.expType, type1String, false, true);
8567                   PrintType(type1, type2String, false, true);
8568                   ChangeCh(expString, '\n', ' ');
8569                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8570                }
8571             }
8572
8573             if(exp.op.exp2.destType == dummy)
8574             {
8575                FreeType(dummy);
8576                exp.op.exp2.destType = null;
8577             }
8578
8579             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8580             {
8581                type2 = { };
8582                type2.refCount = 1;
8583                CopyTypeInto(type2, exp.op.exp2.expType);
8584                type2.isSigned = true;
8585             }
8586             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8587             {
8588                type2 = { kind = intType };
8589                type2.refCount = 1;
8590                type2.isSigned = true;
8591             }
8592             else
8593             {
8594                type2 = exp.op.exp2.expType;
8595                if(type2) type2.refCount++;
8596             }
8597          }
8598
8599          dummy.kind = voidType;
8600
8601          if(exp.op.op == SIZEOF)
8602          {
8603             exp.expType = Type
8604             {
8605                refCount = 1;
8606                kind = intSizeType;
8607             };
8608             exp.isConstant = true;
8609          }
8610          // Get type of dereferenced pointer
8611          else if(exp.op.op == '*' && !exp.op.exp1)
8612          {
8613             exp.expType = Dereference(type2);
8614             if(type2 && type2.kind == classType)
8615                notByReference = true;
8616          }
8617          else if(exp.op.op == '&' && !exp.op.exp1)
8618             exp.expType = Reference(type2);
8619          else if(!assign)
8620          {
8621             if(boolOps)
8622             {
8623                if(exp.op.exp1)
8624                {
8625                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8626                   exp.op.exp1.destType = MkClassType("bool");
8627                   exp.op.exp1.destType.truth = true;
8628                   if(!exp.op.exp1.expType)
8629                      ProcessExpressionType(exp.op.exp1);
8630                   else
8631                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8632                   FreeType(exp.op.exp1.expType);
8633                   exp.op.exp1.expType = MkClassType("bool");
8634                   exp.op.exp1.expType.truth = true;
8635                }
8636                if(exp.op.exp2)
8637                {
8638                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8639                   exp.op.exp2.destType = MkClassType("bool");
8640                   exp.op.exp2.destType.truth = true;
8641                   if(!exp.op.exp2.expType)
8642                      ProcessExpressionType(exp.op.exp2);
8643                   else
8644                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8645                   FreeType(exp.op.exp2.expType);
8646                   exp.op.exp2.expType = MkClassType("bool");
8647                   exp.op.exp2.expType.truth = true;
8648                }
8649             }
8650             else if(exp.op.exp1 && exp.op.exp2 &&
8651                ((useSideType /*&&
8652                      (useSideUnit ||
8653                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8654                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8655                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8656                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8657             {
8658                if(type1 && type2 &&
8659                   // If either both are class or both are not class
8660                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8661                {
8662                   // Added this check for enum subtraction to result in an int type:
8663                   if(exp.op.op == '-' &&
8664                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8665                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8666                   {
8667                      Type intType;
8668                      if(!type1._class.registered.dataType)
8669                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8670                      if(!type2._class.registered.dataType)
8671                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8672
8673                      intType = ProcessTypeString(
8674                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8675
8676                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8677                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8678                      exp.op.exp1.destType = intType;
8679                      exp.op.exp2.destType = intType;
8680                      intType.refCount++;
8681                   }
8682                   else
8683                   {
8684                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8685                      exp.op.exp2.destType = type1;
8686                      type1.refCount++;
8687                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8688                      exp.op.exp1.destType = type2;
8689                      type2.refCount++;
8690                   }
8691
8692                   // Warning here for adding Radians + Degrees with no destination type
8693                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8694                      type1._class.registered && type1._class.registered.type == unitClass &&
8695                      type2._class.registered && type2._class.registered.type == unitClass &&
8696                      type1._class.registered != type2._class.registered)
8697                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8698                         type1._class.string, type2._class.string, type1._class.string);
8699
8700                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8701                   {
8702                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8703                      if(argExp)
8704                      {
8705                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8706
8707                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8708                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8709                            exp.op.exp1)));
8710
8711                         ProcessExpressionType(exp.op.exp1);
8712
8713                         if(type2.kind != pointerType)
8714                         {
8715                            ProcessExpressionType(classExp);
8716
8717                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8718
8719                            if(!exp.op.exp2.expType)
8720                            {
8721                               if(type2)
8722                                  FreeType(type2);
8723                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8724                               type2.refCount++;
8725                            }
8726
8727                            ProcessExpressionType(exp.op.exp2);
8728                         }
8729                      }
8730                   }
8731
8732                   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)))
8733                   {
8734                      if(type1.kind != classType && type1.type.kind == voidType)
8735                         Compiler_Error($"void *: unknown size\n");
8736                      exp.expType = type1;
8737                      if(type1) type1.refCount++;
8738                   }
8739                   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)))
8740                   {
8741                      if(type2.kind != classType && type2.type.kind == voidType)
8742                         Compiler_Error($"void *: unknown size\n");
8743                      exp.expType = type2;
8744                      if(type2) type2.refCount++;
8745                   }
8746                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8747                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8748                   {
8749                      Compiler_Warning($"different levels of indirection\n");
8750                   }
8751                   else
8752                   {
8753                      bool success = false;
8754                      if(type1.kind == pointerType && type2.kind == pointerType)
8755                      {
8756                         if(exp.op.op == '+')
8757                            Compiler_Error($"cannot add two pointers\n");
8758                         else if(exp.op.op == '-')
8759                         {
8760                            // Pointer Subtraction gives integer
8761                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8762                            {
8763                               exp.expType = Type
8764                               {
8765                                  kind = intType;
8766                                  refCount = 1;
8767                               };
8768                               success = true;
8769
8770                               if(type1.type.kind == templateType)
8771                               {
8772                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8773                                  if(argExp)
8774                                  {
8775                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8776
8777                                     ProcessExpressionType(classExp);
8778
8779                                     exp.type = bracketsExp;
8780                                     exp.list = MkListOne(MkExpOp(
8781                                        MkExpBrackets(MkListOne(MkExpOp(
8782                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8783                                              , exp.op.op,
8784                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8785                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8786
8787                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8788                                     FreeType(dummy);
8789                                     return;
8790                                  }
8791                               }
8792                            }
8793                         }
8794                      }
8795
8796                      if(!success && exp.op.exp1.type == constantExp)
8797                      {
8798                         // If first expression is constant, try to match that first
8799                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8800                         {
8801                            if(exp.expType) FreeType(exp.expType);
8802                            exp.expType = exp.op.exp1.destType;
8803                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8804                            success = true;
8805                         }
8806                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8807                         {
8808                            if(exp.expType) FreeType(exp.expType);
8809                            exp.expType = exp.op.exp2.destType;
8810                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8811                            success = true;
8812                         }
8813                      }
8814                      else if(!success)
8815                      {
8816                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8817                         {
8818                            if(exp.expType) FreeType(exp.expType);
8819                            exp.expType = exp.op.exp2.destType;
8820                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8821                            success = true;
8822                         }
8823                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8824                         {
8825                            if(exp.expType) FreeType(exp.expType);
8826                            exp.expType = exp.op.exp1.destType;
8827                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8828                            success = true;
8829                         }
8830                      }
8831                      if(!success)
8832                      {
8833                         char expString1[10240];
8834                         char expString2[10240];
8835                         char type1[1024];
8836                         char type2[1024];
8837                         expString1[0] = '\0';
8838                         expString2[0] = '\0';
8839                         type1[0] = '\0';
8840                         type2[0] = '\0';
8841                         if(inCompiler)
8842                         {
8843                            PrintExpression(exp.op.exp1, expString1);
8844                            ChangeCh(expString1, '\n', ' ');
8845                            PrintExpression(exp.op.exp2, expString2);
8846                            ChangeCh(expString2, '\n', ' ');
8847                            PrintType(exp.op.exp1.expType, type1, false, true);
8848                            PrintType(exp.op.exp2.expType, type2, false, true);
8849                         }
8850
8851                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8852                      }
8853                   }
8854                }
8855                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8856                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8857                {
8858                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8859                   // Convert e.g. / 4 into / 4.0
8860                   exp.op.exp1.destType = type2._class.registered.dataType;
8861                   if(type2._class.registered.dataType)
8862                      type2._class.registered.dataType.refCount++;
8863                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8864                   exp.expType = type2;
8865                   if(type2) type2.refCount++;
8866                }
8867                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8868                {
8869                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8870                   // Convert e.g. / 4 into / 4.0
8871                   exp.op.exp2.destType = type1._class.registered.dataType;
8872                   if(type1._class.registered.dataType)
8873                      type1._class.registered.dataType.refCount++;
8874                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8875                   exp.expType = type1;
8876                   if(type1) type1.refCount++;
8877                }
8878                else if(type1)
8879                {
8880                   bool valid = false;
8881
8882                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8883                   {
8884                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8885
8886                      if(!type1._class.registered.dataType)
8887                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8888                      exp.op.exp2.destType = type1._class.registered.dataType;
8889                      exp.op.exp2.destType.refCount++;
8890
8891                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8892                      if(type2)
8893                         FreeType(type2);
8894                      type2 = exp.op.exp2.destType;
8895                      if(type2) type2.refCount++;
8896
8897                      exp.expType = type2;
8898                      type2.refCount++;
8899                   }
8900
8901                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8902                   {
8903                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8904
8905                      if(!type2._class.registered.dataType)
8906                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8907                      exp.op.exp1.destType = type2._class.registered.dataType;
8908                      exp.op.exp1.destType.refCount++;
8909
8910                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8911                      type1 = exp.op.exp1.destType;
8912                      exp.expType = type1;
8913                      type1.refCount++;
8914                   }
8915
8916                   // TESTING THIS NEW CODE
8917                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8918                   {
8919                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8920                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8921                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8922                      {
8923                         // Convert the enum to an int instead for these operators
8924                         if(op1IsEnum && exp.op.exp2.expType)
8925                         {
8926                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8927                            {
8928                               if(exp.expType) FreeType(exp.expType);
8929                               exp.expType = exp.op.exp2.expType;
8930                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8931                               valid = true;
8932                            }
8933                         }
8934                         else if(op2IsEnum && exp.op.exp1.expType)
8935                         {
8936                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8937                            {
8938                               if(exp.expType) FreeType(exp.expType);
8939                               exp.expType = exp.op.exp1.expType;
8940                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8941                               valid = true;
8942                            }
8943                         }
8944                      }
8945                      else
8946                      {
8947                         if(op1IsEnum && exp.op.exp2.expType)
8948                         {
8949                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8950                            {
8951                               if(exp.expType) FreeType(exp.expType);
8952                               exp.expType = exp.op.exp1.expType;
8953                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8954                               valid = true;
8955                            }
8956                         }
8957                         else if(op2IsEnum && exp.op.exp1.expType)
8958                         {
8959                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8960                            {
8961                               if(exp.expType) FreeType(exp.expType);
8962                               exp.expType = exp.op.exp2.expType;
8963                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8964                               valid = true;
8965                            }
8966                         }
8967                      }
8968                   }
8969
8970                   if(!valid)
8971                   {
8972                      // 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
8973                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8974                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8975                      {
8976                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8977                         exp.op.exp1.destType = type2;
8978                         type2.refCount++;
8979
8980                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8981                         {
8982                            if(exp.expType) FreeType(exp.expType);
8983                            exp.expType = exp.op.exp1.destType;
8984                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8985                         }
8986                      }
8987                      else
8988                      {
8989                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8990                         exp.op.exp2.destType = type1;
8991                         type1.refCount++;
8992
8993                      /*
8994                      // Maybe this was meant to be an enum...
8995                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8996                      {
8997                         Type oldType = exp.op.exp2.expType;
8998                         exp.op.exp2.expType = null;
8999                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
9000                            FreeType(oldType);
9001                         else
9002                            exp.op.exp2.expType = oldType;
9003                      }
9004                      */
9005
9006                      /*
9007                      // TESTING THIS HERE... LATEST ADDITION
9008                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9009                      {
9010                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9011                         exp.op.exp2.destType = type2._class.registered.dataType;
9012                         if(type2._class.registered.dataType)
9013                            type2._class.registered.dataType.refCount++;
9014                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9015
9016                         //exp.expType = type2._class.registered.dataType; //type2;
9017                         //if(type2) type2.refCount++;
9018                      }
9019
9020                      // TESTING THIS HERE... LATEST ADDITION
9021                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9022                      {
9023                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9024                         exp.op.exp1.destType = type1._class.registered.dataType;
9025                         if(type1._class.registered.dataType)
9026                            type1._class.registered.dataType.refCount++;
9027                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9028                         exp.expType = type1._class.registered.dataType; //type1;
9029                         if(type1) type1.refCount++;
9030                      }
9031                      */
9032
9033                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9034                         {
9035                            if(exp.expType) FreeType(exp.expType);
9036                            exp.expType = exp.op.exp2.destType;
9037                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9038                         }
9039                         else if(type1 && type2)
9040                         {
9041                            char expString1[10240];
9042                            char expString2[10240];
9043                            char type1String[1024];
9044                            char type2String[1024];
9045                            expString1[0] = '\0';
9046                            expString2[0] = '\0';
9047                            type1String[0] = '\0';
9048                            type2String[0] = '\0';
9049                            if(inCompiler)
9050                            {
9051                               PrintExpression(exp.op.exp1, expString1);
9052                               ChangeCh(expString1, '\n', ' ');
9053                               PrintExpression(exp.op.exp2, expString2);
9054                               ChangeCh(expString2, '\n', ' ');
9055                               PrintType(exp.op.exp1.expType, type1String, false, true);
9056                               PrintType(exp.op.exp2.expType, type2String, false, true);
9057                            }
9058
9059                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9060
9061                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9062                            {
9063                               exp.expType = exp.op.exp1.expType;
9064                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9065                            }
9066                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9067                            {
9068                               exp.expType = exp.op.exp2.expType;
9069                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9070                            }
9071                         }
9072                      }
9073                   }
9074                }
9075                else if(type2)
9076                {
9077                   // Maybe this was meant to be an enum...
9078                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9079                   {
9080                      Type oldType = exp.op.exp1.expType;
9081                      exp.op.exp1.expType = null;
9082                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9083                         FreeType(oldType);
9084                      else
9085                         exp.op.exp1.expType = oldType;
9086                   }
9087
9088                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9089                   exp.op.exp1.destType = type2;
9090                   type2.refCount++;
9091                   /*
9092                   // TESTING THIS HERE... LATEST ADDITION
9093                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9094                   {
9095                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9096                      exp.op.exp1.destType = type1._class.registered.dataType;
9097                      if(type1._class.registered.dataType)
9098                         type1._class.registered.dataType.refCount++;
9099                   }
9100
9101                   // TESTING THIS HERE... LATEST ADDITION
9102                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9103                   {
9104                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9105                      exp.op.exp2.destType = type2._class.registered.dataType;
9106                      if(type2._class.registered.dataType)
9107                         type2._class.registered.dataType.refCount++;
9108                   }
9109                   */
9110
9111                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9112                   {
9113                      if(exp.expType) FreeType(exp.expType);
9114                      exp.expType = exp.op.exp1.destType;
9115                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9116                   }
9117                }
9118             }
9119             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9120             {
9121                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9122                {
9123                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9124                   // Convert e.g. / 4 into / 4.0
9125                   exp.op.exp1.destType = type2._class.registered.dataType;
9126                   if(type2._class.registered.dataType)
9127                      type2._class.registered.dataType.refCount++;
9128                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9129                }
9130                if(exp.op.op == '!')
9131                {
9132                   exp.expType = MkClassType("bool");
9133                   exp.expType.truth = true;
9134                }
9135                else
9136                {
9137                   exp.expType = type2;
9138                   if(type2) type2.refCount++;
9139                }
9140             }
9141             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9142             {
9143                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9144                {
9145                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9146                   // Convert e.g. / 4 into / 4.0
9147                   exp.op.exp2.destType = type1._class.registered.dataType;
9148                   if(type1._class.registered.dataType)
9149                      type1._class.registered.dataType.refCount++;
9150                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9151                }
9152                exp.expType = type1;
9153                if(type1) type1.refCount++;
9154             }
9155          }
9156
9157          yylloc = exp.loc;
9158          if(exp.op.exp1 && !exp.op.exp1.expType)
9159          {
9160             char expString[10000];
9161             expString[0] = '\0';
9162             if(inCompiler)
9163             {
9164                PrintExpression(exp.op.exp1, expString);
9165                ChangeCh(expString, '\n', ' ');
9166             }
9167             if(expString[0])
9168                Compiler_Error($"couldn't determine type of %s\n", expString);
9169          }
9170          if(exp.op.exp2 && !exp.op.exp2.expType)
9171          {
9172             char expString[10240];
9173             expString[0] = '\0';
9174             if(inCompiler)
9175             {
9176                PrintExpression(exp.op.exp2, expString);
9177                ChangeCh(expString, '\n', ' ');
9178             }
9179             if(expString[0])
9180                Compiler_Error($"couldn't determine type of %s\n", expString);
9181          }
9182
9183          if(boolResult)
9184          {
9185             FreeType(exp.expType);
9186             exp.expType = MkClassType("bool");
9187             exp.expType.truth = true;
9188          }
9189
9190          if(exp.op.op != SIZEOF)
9191             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9192                (!exp.op.exp2 || exp.op.exp2.isConstant);
9193
9194          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9195          {
9196             DeclareType(exp.op.exp2.expType, false, false);
9197          }
9198
9199          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9200             Compiler_Warning($"deleting const qualified object\n");
9201
9202          yylloc = oldyylloc;
9203
9204          FreeType(dummy);
9205          if(type2)
9206             FreeType(type2);
9207          break;
9208       }
9209       case bracketsExp:
9210       case extensionExpressionExp:
9211       {
9212          Expression e;
9213          exp.isConstant = true;
9214          for(e = exp.list->first; e; e = e.next)
9215          {
9216             bool inced = false;
9217             if(!e.next)
9218             {
9219                FreeType(e.destType);
9220                e.opDestType = exp.opDestType;
9221                e.destType = exp.destType;
9222                if(e.destType) { exp.destType.refCount++; e.destType.count++; inced = true; }
9223             }
9224             ProcessExpressionType(e);
9225             if(inced)
9226                exp.destType.count--;
9227             if(!exp.expType && !e.next)
9228             {
9229                exp.expType = e.expType;
9230                if(e.expType) e.expType.refCount++;
9231             }
9232             if(!e.isConstant)
9233                exp.isConstant = false;
9234          }
9235
9236          // In case a cast became a member...
9237          e = exp.list->first;
9238          if(!e.next && e.type == memberExp)
9239          {
9240             // Preserve prev, next
9241             Expression next = exp.next, prev = exp.prev;
9242
9243
9244             FreeType(exp.expType);
9245             FreeType(exp.destType);
9246             delete exp.list;
9247
9248             *exp = *e;
9249
9250             exp.prev = prev;
9251             exp.next = next;
9252
9253             delete e;
9254
9255             ProcessExpressionType(exp);
9256          }
9257          break;
9258       }
9259       case indexExp:
9260       {
9261          Expression e;
9262          exp.isConstant = true;
9263
9264          ProcessExpressionType(exp.index.exp);
9265          if(!exp.index.exp.isConstant)
9266             exp.isConstant = false;
9267
9268          if(exp.index.exp.expType)
9269          {
9270             Type source = exp.index.exp.expType;
9271             if(source.kind == classType && source._class && source._class.registered)
9272             {
9273                Class _class = source._class.registered;
9274                Class c = _class.templateClass ? _class.templateClass : _class;
9275                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9276                {
9277                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9278
9279                   if(exp.index.index && exp.index.index->last)
9280                   {
9281                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9282
9283                      if(type.kind == classType) type.constant = true;
9284                      else if(type.kind == pointerType)
9285                      {
9286                         Type t = type;
9287                         while(t.kind == pointerType) t = t.type;
9288                         t.constant = true;
9289                      }
9290
9291                      ((Expression)exp.index.index->last).destType = type;
9292                   }
9293                }
9294             }
9295          }
9296
9297          for(e = exp.index.index->first; e; e = e.next)
9298          {
9299             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9300             {
9301                if(e.destType) FreeType(e.destType);
9302                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9303             }
9304             ProcessExpressionType(e);
9305             if(!e.next)
9306             {
9307                // Check if this type is int
9308             }
9309             if(!e.isConstant)
9310                exp.isConstant = false;
9311          }
9312
9313          if(!exp.expType)
9314             exp.expType = Dereference(exp.index.exp.expType);
9315          if(exp.expType)
9316             DeclareType(exp.expType, false, false);
9317          break;
9318       }
9319       case callExp:
9320       {
9321          Expression e;
9322          Type functionType;
9323          Type methodType = null;
9324          char name[1024];
9325          name[0] = '\0';
9326
9327          if(inCompiler)
9328          {
9329             PrintExpression(exp.call.exp,  name);
9330             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9331             {
9332                //exp.call.exp.expType = null;
9333                PrintExpression(exp.call.exp,  name);
9334             }
9335          }
9336          if(exp.call.exp.type == identifierExp)
9337          {
9338             Expression idExp = exp.call.exp;
9339             Identifier id = idExp.identifier;
9340             if(!strcmp(id.string, "__builtin_frame_address"))
9341             {
9342                exp.expType = ProcessTypeString("void *", true);
9343                if(exp.call.arguments && exp.call.arguments->first)
9344                   ProcessExpressionType(exp.call.arguments->first);
9345                break;
9346             }
9347             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9348             {
9349                exp.expType = ProcessTypeString("int", true);
9350                if(exp.call.arguments && exp.call.arguments->first)
9351                   ProcessExpressionType(exp.call.arguments->first);
9352                break;
9353             }
9354             else if(!strcmp(id.string, "Max") ||
9355                !strcmp(id.string, "Min") ||
9356                !strcmp(id.string, "Sgn") ||
9357                !strcmp(id.string, "Abs"))
9358             {
9359                Expression a = null;
9360                Expression b = null;
9361                Expression tempExp1 = null, tempExp2 = null;
9362                if((!strcmp(id.string, "Max") ||
9363                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9364                {
9365                   a = exp.call.arguments->first;
9366                   b = exp.call.arguments->last;
9367                   tempExp1 = a;
9368                   tempExp2 = b;
9369                }
9370                else if(exp.call.arguments->count == 1)
9371                {
9372                   a = exp.call.arguments->first;
9373                   tempExp1 = a;
9374                }
9375
9376                if(a)
9377                {
9378                   exp.call.arguments->Clear();
9379                   idExp.identifier = null;
9380
9381                   FreeExpContents(exp);
9382
9383                   ProcessExpressionType(a);
9384                   if(b)
9385                      ProcessExpressionType(b);
9386
9387                   exp.type = bracketsExp;
9388                   exp.list = MkList();
9389
9390                   if(a.expType && (!b || b.expType))
9391                   {
9392                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9393                      {
9394                         // Use the simpleStruct name/ids for now...
9395                         if(inCompiler)
9396                         {
9397                            OldList * specs = MkList();
9398                            OldList * decls = MkList();
9399                            Declaration decl;
9400                            char temp1[1024], temp2[1024];
9401
9402                            GetTypeSpecs(a.expType, specs);
9403
9404                            if(a && !a.isConstant && a.type != identifierExp)
9405                            {
9406                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9407                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9408                               tempExp1 = QMkExpId(temp1);
9409                               tempExp1.expType = a.expType;
9410                               if(a.expType)
9411                                  a.expType.refCount++;
9412                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9413                            }
9414                            if(b && !b.isConstant && b.type != identifierExp)
9415                            {
9416                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9417                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9418                               tempExp2 = QMkExpId(temp2);
9419                               tempExp2.expType = b.expType;
9420                               if(b.expType)
9421                                  b.expType.refCount++;
9422                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9423                            }
9424
9425                            decl = MkDeclaration(specs, decls);
9426                            if(!curCompound.compound.declarations)
9427                               curCompound.compound.declarations = MkList();
9428                            curCompound.compound.declarations->Insert(null, decl);
9429                         }
9430                      }
9431                   }
9432
9433                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9434                   {
9435                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9436                      ListAdd(exp.list,
9437                         MkExpCondition(MkExpBrackets(MkListOne(
9438                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9439                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9440                      exp.expType = a.expType;
9441                      if(a.expType)
9442                         a.expType.refCount++;
9443                   }
9444                   else if(!strcmp(id.string, "Abs"))
9445                   {
9446                      ListAdd(exp.list,
9447                         MkExpCondition(MkExpBrackets(MkListOne(
9448                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9449                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9450                      exp.expType = a.expType;
9451                      if(a.expType)
9452                         a.expType.refCount++;
9453                   }
9454                   else if(!strcmp(id.string, "Sgn"))
9455                   {
9456                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9457                      ListAdd(exp.list,
9458                         MkExpCondition(MkExpBrackets(MkListOne(
9459                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9460                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9461                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9462                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9463                      exp.expType = ProcessTypeString("int", false);
9464                   }
9465
9466                   FreeExpression(tempExp1);
9467                   if(tempExp2) FreeExpression(tempExp2);
9468
9469                   FreeIdentifier(id);
9470                   break;
9471                }
9472             }
9473          }
9474
9475          {
9476             Type dummy
9477             {
9478                count = 1;
9479                refCount = 1;
9480             };
9481             if(!exp.call.exp.destType)
9482             {
9483                exp.call.exp.destType = dummy;
9484                dummy.refCount++;
9485             }
9486             ProcessExpressionType(exp.call.exp);
9487             if(exp.call.exp.destType == dummy)
9488             {
9489                FreeType(dummy);
9490                exp.call.exp.destType = null;
9491             }
9492             FreeType(dummy);
9493          }
9494
9495          // Check argument types against parameter types
9496          functionType = exp.call.exp.expType;
9497
9498          if(functionType && functionType.kind == TypeKind::methodType)
9499          {
9500             methodType = functionType;
9501             functionType = methodType.method.dataType;
9502
9503             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9504             // TOCHECK: Instead of doing this here could this be done per param?
9505             if(exp.call.exp.expType.usedClass)
9506             {
9507                char typeString[1024];
9508                typeString[0] = '\0';
9509                {
9510                   Symbol back = functionType.thisClass;
9511                   // Do not output class specifier here (thisclass was added to this)
9512                   functionType.thisClass = null;
9513                   PrintType(functionType, typeString, true, true);
9514                   functionType.thisClass = back;
9515                }
9516                if(strstr(typeString, "thisclass"))
9517                {
9518                   OldList * specs = MkList();
9519                   Declarator decl;
9520                   {
9521                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9522
9523                      decl = SpecDeclFromString(typeString, specs, null);
9524
9525                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9526                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9527                         exp.call.exp.expType.usedClass))
9528                         thisClassParams = false;
9529
9530                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9531                      {
9532                         Class backupThisClass = thisClass;
9533                         thisClass = exp.call.exp.expType.usedClass;
9534                         ProcessDeclarator(decl);
9535                         thisClass = backupThisClass;
9536                      }
9537
9538                      thisClassParams = true;
9539
9540                      functionType = ProcessType(specs, decl);
9541                      functionType.refCount = 0;
9542                      FinishTemplatesContext(context);
9543
9544                      // Mark parameters that were 'thisclass'
9545                      /*{
9546                         Type p, op;
9547                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9548                            p.wasThisClass = op.kind == thisClassType;
9549                      }*/
9550                   }
9551
9552                   FreeList(specs, FreeSpecifier);
9553                   FreeDeclarator(decl);
9554                 }
9555             }
9556          }
9557          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9558          {
9559             Type type = functionType.type;
9560             if(!functionType.refCount)
9561             {
9562                functionType.type = null;
9563                FreeType(functionType);
9564             }
9565             //methodType = functionType;
9566             functionType = type;
9567          }
9568          if(functionType && functionType.kind != TypeKind::functionType)
9569          {
9570             Compiler_Error($"called object %s is not a function\n", name);
9571          }
9572          else if(functionType)
9573          {
9574             bool emptyParams = false, noParams = false;
9575             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9576             Type type = functionType.params.first;
9577             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9578             int extra = 0;
9579             Location oldyylloc = yylloc;
9580
9581             if(!type) emptyParams = true;
9582
9583             // WORKING ON THIS:
9584             if(functionType.extraParam && e && functionType.thisClass)
9585             {
9586                e.destType = MkClassType(functionType.thisClass.string);
9587                e = e.next;
9588             }
9589
9590             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9591             // Fixed #141 by adding '&& !functionType.extraParam'
9592             if(!functionType.staticMethod && !functionType.extraParam)
9593             {
9594                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9595                   memberExp.member.exp.expType._class)
9596                {
9597                   type = MkClassType(memberExp.member.exp.expType._class.string);
9598                   if(e)
9599                   {
9600                      e.destType = type;
9601                      e = e.next;
9602                      type = functionType.params.first;
9603                   }
9604                   else
9605                      type.refCount = 0;
9606                }
9607                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9608                {
9609                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9610                   type.byReference = functionType.byReference;
9611                   type.typedByReference = functionType.typedByReference;
9612                   if(e)
9613                   {
9614                      // Allow manually passing a class for typed object
9615                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9616                         e = e.next;
9617                      e.destType = type;
9618                      e = e.next;
9619                      type = functionType.params.first;
9620                   }
9621                   else
9622                      type.refCount = 0;
9623                   //extra = 1;
9624                }
9625             }
9626
9627             if(type && type.kind == voidType)
9628             {
9629                noParams = true;
9630                if(!type.refCount) FreeType(type);
9631                type = null;
9632             }
9633
9634             for( ; e; e = e.next)
9635             {
9636                if(!type && !emptyParams)
9637                {
9638                   yylloc = e.loc;
9639                   if(methodType && methodType.methodClass)
9640                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9641                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9642                         noParams ? 0 : functionType.params.count);
9643                   else
9644                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9645                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9646                         noParams ? 0 : functionType.params.count);
9647                   break;
9648                }
9649
9650                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9651                {
9652                   Type templatedType = null;
9653                   Class _class = methodType.usedClass;
9654                   ClassTemplateParameter curParam = null;
9655                   int id = 0;
9656                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9657                   {
9658                      Class sClass;
9659                      for(sClass = _class; sClass; sClass = sClass.base)
9660                      {
9661                         if(sClass.templateClass) sClass = sClass.templateClass;
9662                         id = 0;
9663                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9664                         {
9665                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9666                            {
9667                               Class nextClass;
9668                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9669                               {
9670                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9671                                  id += nextClass.templateParams.count;
9672                               }
9673                               break;
9674                            }
9675                            id++;
9676                         }
9677                         if(curParam) break;
9678                      }
9679                   }
9680                   if(curParam && _class.templateArgs[id].dataTypeString)
9681                   {
9682                      bool constant = type.constant;
9683                      ClassTemplateArgument arg = _class.templateArgs[id];
9684                      {
9685                         Context context = SetupTemplatesContext(_class);
9686
9687                         /*if(!arg.dataType)
9688                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9689                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9690                         FinishTemplatesContext(context);
9691                      }
9692
9693                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9694                      else if(templatedType.kind == pointerType)
9695                      {
9696                         Type t = templatedType.type;
9697                         while(t.kind == pointerType) t = t.type;
9698                         if(constant) t.constant = constant;
9699                      }
9700
9701                      e.destType = templatedType;
9702                      if(templatedType)
9703                      {
9704                         templatedType.passAsTemplate = true;
9705                         // templatedType.refCount++;
9706                      }
9707                   }
9708                   else
9709                   {
9710                      e.destType = type;
9711                      if(type) type.refCount++;
9712                   }
9713                }
9714                else
9715                {
9716                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9717                   {
9718                      e.destType = type.prev;
9719                      e.destType.refCount++;
9720                   }
9721                   else
9722                   {
9723                      e.destType = type;
9724                      if(type) type.refCount++;
9725                   }
9726                }
9727                // Don't reach the end for the ellipsis
9728                if(type && type.kind != ellipsisType)
9729                {
9730                   Type next = type.next;
9731                   if(!type.refCount) FreeType(type);
9732                   type = next;
9733                }
9734             }
9735
9736             if(type && type.kind != ellipsisType)
9737             {
9738                if(methodType && methodType.methodClass)
9739                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9740                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9741                      functionType.params.count + extra);
9742                else
9743                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9744                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9745                      functionType.params.count + extra);
9746             }
9747             yylloc = oldyylloc;
9748             if(type && !type.refCount) FreeType(type);
9749          }
9750          else
9751          {
9752             functionType = Type
9753             {
9754                refCount = 0;
9755                kind = TypeKind::functionType;
9756             };
9757
9758             if(exp.call.exp.type == identifierExp)
9759             {
9760                char * string = exp.call.exp.identifier.string;
9761                if(inCompiler)
9762                {
9763                   Symbol symbol;
9764                   Location oldyylloc = yylloc;
9765
9766                   yylloc = exp.call.exp.identifier.loc;
9767                   if(strstr(string, "__builtin_") == string)
9768                   {
9769                      if(exp.destType)
9770                      {
9771                         functionType.returnType = exp.destType;
9772                         exp.destType.refCount++;
9773                      }
9774                   }
9775                   else
9776                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9777                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9778                   globalContext.symbols.Add((BTNode)symbol);
9779                   if(strstr(symbol.string, "::"))
9780                      globalContext.hasNameSpace = true;
9781
9782                   yylloc = oldyylloc;
9783                }
9784             }
9785             else if(exp.call.exp.type == memberExp)
9786             {
9787                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9788                   exp.call.exp.member.member.string);*/
9789             }
9790             else
9791                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9792
9793             if(!functionType.returnType)
9794             {
9795                functionType.returnType = Type
9796                {
9797                   refCount = 1;
9798                   kind = intType;
9799                };
9800             }
9801          }
9802          if(functionType && functionType.kind == TypeKind::functionType)
9803          {
9804             exp.expType = functionType.returnType;
9805
9806             if(functionType.returnType)
9807                functionType.returnType.refCount++;
9808
9809             if(!functionType.refCount)
9810                FreeType(functionType);
9811          }
9812
9813          if(exp.call.arguments)
9814          {
9815             for(e = exp.call.arguments->first; e; e = e.next)
9816                ProcessExpressionType(e);
9817          }
9818          break;
9819       }
9820       case memberExp:
9821       {
9822          Type type;
9823          Location oldyylloc = yylloc;
9824          bool thisPtr;
9825          Expression checkExp = exp.member.exp;
9826          while(checkExp)
9827          {
9828             if(checkExp.type == castExp)
9829                checkExp = checkExp.cast.exp;
9830             else if(checkExp.type == bracketsExp)
9831                checkExp = checkExp.list ? checkExp.list->first : null;
9832             else
9833                break;
9834          }
9835
9836          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9837          exp.thisPtr = thisPtr;
9838
9839          // DOING THIS LATER NOW...
9840          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9841          {
9842             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9843             /* TODO: Name Space Fix ups
9844             if(!exp.member.member.classSym)
9845                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9846             */
9847          }
9848
9849          ProcessExpressionType(exp.member.exp);
9850          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9851             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9852          {
9853             exp.isConstant = false;
9854          }
9855          else
9856             exp.isConstant = exp.member.exp.isConstant;
9857          type = exp.member.exp.expType;
9858
9859          yylloc = exp.loc;
9860
9861          if(type && (type.kind == templateType))
9862          {
9863             Class _class = thisClass ? thisClass : currentClass;
9864             ClassTemplateParameter param = null;
9865             if(_class)
9866             {
9867                for(param = _class.templateParams.first; param; param = param.next)
9868                {
9869                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9870                      break;
9871                }
9872             }
9873             if(param && param.defaultArg.member)
9874             {
9875                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9876                if(argExp)
9877                {
9878                   Expression expMember = exp.member.exp;
9879                   Declarator decl;
9880                   OldList * specs = MkList();
9881                   char thisClassTypeString[1024];
9882
9883                   FreeIdentifier(exp.member.member);
9884
9885                   ProcessExpressionType(argExp);
9886
9887                   {
9888                      char * colon = strstr(param.defaultArg.memberString, "::");
9889                      if(colon)
9890                      {
9891                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9892                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9893                      }
9894                      else
9895                         strcpy(thisClassTypeString, _class.fullName);
9896                   }
9897
9898                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9899
9900                   exp.expType = ProcessType(specs, decl);
9901                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9902                   {
9903                      Class expClass = exp.expType._class.registered;
9904                      Class cClass = null;
9905                      int paramCount = 0;
9906                      int lastParam = -1;
9907
9908                      char templateString[1024];
9909                      ClassTemplateParameter param;
9910                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9911                      for(cClass = expClass; cClass; cClass = cClass.base)
9912                      {
9913                         int p = 0;
9914                         for(param = cClass.templateParams.first; param; param = param.next)
9915                         {
9916                            int id = p;
9917                            Class sClass;
9918                            ClassTemplateArgument arg;
9919                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9920                            arg = expClass.templateArgs[id];
9921
9922                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9923                            {
9924                               ClassTemplateParameter cParam;
9925                               //int p = numParams - sClass.templateParams.count;
9926                               int p = 0;
9927                               Class nextClass;
9928                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9929
9930                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9931                               {
9932                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9933                                  {
9934                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9935                                     {
9936                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9937                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9938                                        break;
9939                                     }
9940                                  }
9941                               }
9942                            }
9943
9944                            {
9945                               char argument[256];
9946                               argument[0] = '\0';
9947                               /*if(arg.name)
9948                               {
9949                                  strcat(argument, arg.name.string);
9950                                  strcat(argument, " = ");
9951                               }*/
9952                               switch(param.type)
9953                               {
9954                                  case expression:
9955                                  {
9956                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9957                                     char expString[1024];
9958                                     OldList * specs = MkList();
9959                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9960                                     Expression exp;
9961                                     char * string = PrintHexUInt64(arg.expression.ui64);
9962                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9963                                     delete string;
9964
9965                                     ProcessExpressionType(exp);
9966                                     ComputeExpression(exp);
9967                                     expString[0] = '\0';
9968                                     PrintExpression(exp, expString);
9969                                     strcat(argument, expString);
9970                                     // delete exp;
9971                                     FreeExpression(exp);
9972                                     break;
9973                                  }
9974                                  case identifier:
9975                                  {
9976                                     strcat(argument, arg.member.name);
9977                                     break;
9978                                  }
9979                                  case TemplateParameterType::type:
9980                                  {
9981                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9982                                     {
9983                                        if(!strcmp(arg.dataTypeString, "thisclass"))
9984                                           strcat(argument, thisClassTypeString);
9985                                        else
9986                                           strcat(argument, arg.dataTypeString);
9987                                     }
9988                                     break;
9989                                  }
9990                               }
9991                               if(argument[0])
9992                               {
9993                                  if(paramCount) strcat(templateString, ", ");
9994                                  if(lastParam != p - 1)
9995                                  {
9996                                     strcat(templateString, param.name);
9997                                     strcat(templateString, " = ");
9998                                  }
9999                                  strcat(templateString, argument);
10000                                  paramCount++;
10001                                  lastParam = p;
10002                               }
10003                               p++;
10004                            }
10005                         }
10006                      }
10007                      {
10008                         int len = strlen(templateString);
10009                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10010                         templateString[len++] = '>';
10011                         templateString[len++] = '\0';
10012                      }
10013                      {
10014                         Context context = SetupTemplatesContext(_class);
10015                         FreeType(exp.expType);
10016                         exp.expType = ProcessTypeString(templateString, false);
10017                         FinishTemplatesContext(context);
10018                      }
10019                   }
10020
10021                   // *([expType] *)(((byte *)[exp.member.exp]) + [argExp].member.offset)
10022                   exp.type = bracketsExp;
10023                   exp.list = MkListOne(MkExpOp(null, '*',
10024                   /*opExp;
10025                   exp.op.op = '*';
10026                   exp.op.exp1 = null;
10027                   exp.op.exp2 = */
10028                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10029                      MkExpBrackets(MkListOne(
10030                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), expMember))),
10031                            '+',
10032                            MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10033                            '+',
10034                            MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10035
10036                            ));
10037                }
10038             }
10039             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10040                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10041             {
10042                type = ProcessTemplateParameterType(type.templateParameter);
10043             }
10044          }
10045          // TODO: *** This seems to be where we should add method support for all basic types ***
10046          if(type && (type.kind == templateType));
10047          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10048                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10049                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10050                           (type.kind == pointerType && type.type.kind == charType)))
10051          {
10052             Identifier id = exp.member.member;
10053             TypeKind typeKind = type.kind;
10054             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10055             if(typeKind == subClassType && exp.member.exp.type == classExp)
10056             {
10057                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10058                typeKind = classType;
10059             }
10060
10061             if(id)
10062             {
10063                if(typeKind == intType || typeKind == enumType)
10064                   _class = eSystem_FindClass(privateModule, "int");
10065                else if(!_class)
10066                {
10067                   if(type.kind == classType && type._class && type._class.registered)
10068                   {
10069                      _class = type._class.registered;
10070                   }
10071                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10072                   {
10073                      _class = FindClass("char *").registered;
10074                   }
10075                   else if(type.kind == pointerType)
10076                   {
10077                      _class = eSystem_FindClass(privateModule, "uintptr");
10078                      FreeType(exp.expType);
10079                      exp.expType = ProcessTypeString("uintptr", false);
10080                      exp.byReference = true;
10081                   }
10082                   else
10083                   {
10084                      char string[1024] = "";
10085                      Symbol classSym;
10086                      PrintTypeNoConst(type, string, false, true);
10087                      classSym = FindClass(string);
10088                      if(classSym) _class = classSym.registered;
10089                   }
10090                }
10091             }
10092
10093             if(_class && id)
10094             {
10095                /*bool thisPtr =
10096                   (exp.member.exp.type == identifierExp &&
10097                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10098                Property prop = null;
10099                Method method = null;
10100                DataMember member = null;
10101                Property revConvert = null;
10102                ClassProperty classProp = null;
10103
10104                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10105                   exp.member.memberType = propertyMember;
10106
10107                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10108                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10109
10110                if(typeKind != subClassType)
10111                {
10112                   // Prioritize data members over properties for "this"
10113                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10114                   {
10115                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10116                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10117                      {
10118                         prop = eClass_FindProperty(_class, id.string, privateModule);
10119                         if(prop)
10120                            member = null;
10121                      }
10122                      if(!member && !prop)
10123                         prop = eClass_FindProperty(_class, id.string, privateModule);
10124                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10125                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10126                         exp.member.thisPtr = true;
10127                   }
10128                   // Prioritize properties over data members otherwise
10129                   else
10130                   {
10131                      bool useMemberForNonConst = false;
10132                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10133                      if(!id.classSym)
10134                      {
10135                         prop = eClass_FindProperty(_class, id.string, null);
10136
10137                         useMemberForNonConst = prop && exp.destType &&
10138                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10139                               !strncmp(prop.dataTypeString, "const ", 6);
10140
10141                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10142                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10143                      }
10144
10145                      if((!prop || useMemberForNonConst) && !member)
10146                      {
10147                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10148                         if(!method)
10149                         {
10150                            prop = eClass_FindProperty(_class, id.string, privateModule);
10151
10152                            useMemberForNonConst |= prop && exp.destType &&
10153                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10154                                  !strncmp(prop.dataTypeString, "const ", 6);
10155
10156                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10157                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10158                         }
10159                      }
10160
10161                      if(member && prop)
10162                      {
10163                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10164                            prop = null;
10165                         else
10166                            member = null;
10167                      }
10168                   }
10169                }
10170                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10171                   method = eClass_FindMethod(_class, id.string, privateModule);
10172                if(!prop && !member && !method)
10173                {
10174                   if(typeKind == subClassType)
10175                   {
10176                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10177                      if(classProp)
10178                      {
10179                         exp.member.memberType = classPropertyMember;
10180                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10181                      }
10182                      else
10183                      {
10184                         // Assume this is a class_data member
10185                         char structName[1024];
10186                         Identifier id = exp.member.member;
10187                         Expression classExp = exp.member.exp;
10188                         type.refCount++;
10189
10190                         FreeType(classExp.expType);
10191                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10192
10193                         strcpy(structName, "__ecereClassData_");
10194                         FullClassNameCat(structName, type._class.string, false);
10195                         exp.type = pointerExp;
10196                         exp.member.member = id;
10197
10198                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10199                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10200                               MkExpBrackets(MkListOne(MkExpOp(
10201                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10202                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10203                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10204                                  )));
10205
10206                         FreeType(type);
10207
10208                         ProcessExpressionType(exp);
10209                         return;
10210                      }
10211                   }
10212                   else
10213                   {
10214                      // Check for reverse conversion
10215                      // (Convert in an instantiation later, so that we can use
10216                      //  deep properties system)
10217                      Symbol classSym = FindClass(id.string);
10218                      if(classSym)
10219                      {
10220                         Class convertClass = classSym.registered;
10221                         if(convertClass)
10222                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10223                      }
10224                   }
10225                }
10226
10227                //if(!exp.member.exp.destType)
10228                if(exp.member.exp.destType)
10229                   FreeType(exp.member.exp.destType);
10230                {
10231                   if(method && !method._class.symbol)
10232                      method._class.symbol = FindClass(method._class.fullName);
10233                   if(prop && !prop._class.symbol)
10234                      prop._class.symbol = FindClass(prop._class.fullName);
10235
10236                   exp.member.exp.destType = Type
10237                   {
10238                      refCount = 1;
10239                      kind = classType;
10240                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10241                      // wasThisClass = type ? type.wasThisClass : false;
10242                   };
10243                }
10244
10245                if(prop)
10246                {
10247                   exp.member.memberType = propertyMember;
10248                   if(!prop.dataType)
10249                      ProcessPropertyType(prop);
10250                   exp.expType = prop.dataType;
10251                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10252                   {
10253                      Type type { };
10254                      CopyTypeInto(type, exp.expType);
10255                      type.refCount = 1;
10256                      type.constant = true;
10257                      exp.expType = type;
10258                   }
10259                   else if(prop.dataType)
10260                      prop.dataType.refCount++;
10261                }
10262                else if(member)
10263                {
10264                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10265                   {
10266                      FreeExpContents(exp);
10267                      exp.type = identifierExp;
10268                      exp.identifier = MkIdentifier("class");
10269                      ProcessExpressionType(exp);
10270                      return;
10271                   }
10272
10273                   exp.member.memberType = dataMember;
10274                   DeclareStruct(_class.fullName, false);
10275                   if(!member.dataType)
10276                   {
10277                      Context context = SetupTemplatesContext(_class);
10278                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10279                      FinishTemplatesContext(context);
10280                   }
10281                   exp.expType = member.dataType;
10282                   if(member.dataType) member.dataType.refCount++;
10283                }
10284                else if(revConvert)
10285                {
10286                   exp.member.memberType = reverseConversionMember;
10287                   exp.expType = MkClassType(revConvert._class.fullName);
10288                }
10289                else if(method)
10290                {
10291                   //if(inCompiler)
10292                   {
10293                      /*if(id._class)
10294                      {
10295                         exp.type = identifierExp;
10296                         exp.identifier = exp.member.member;
10297                      }
10298                      else*/
10299                         exp.member.memberType = methodMember;
10300                   }
10301                   if(!method.dataType)
10302                      ProcessMethodType(method);
10303                   exp.expType = Type
10304                   {
10305                      refCount = 1;
10306                      kind = methodType;
10307                      method = method;
10308                   };
10309
10310                   // Tricky spot here... To use instance versus class virtual table
10311                   // Put it back to what it was... What did we break?
10312
10313                   // Had to put it back for overriding Main of Thread global instance
10314
10315                   //exp.expType.methodClass = _class;
10316                   exp.expType.methodClass = (id && id._class) ? _class : null;
10317
10318                   // Need the actual class used for templated classes
10319                   exp.expType.usedClass = _class;
10320                }
10321                else if(!classProp)
10322                {
10323                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10324                   {
10325                      FreeExpContents(exp);
10326                      exp.type = identifierExp;
10327                      exp.identifier = MkIdentifier("class");
10328                      FreeType(exp.expType);
10329                      exp.expType = MkClassType("ecere::com::Class");
10330                      return;
10331                   }
10332                   yylloc = exp.member.member.loc;
10333                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10334                   if(inCompiler)
10335                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10336                }
10337
10338                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10339                {
10340                   Class tClass;
10341
10342                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10343                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10344
10345                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10346                   {
10347                      int id = 0;
10348                      ClassTemplateParameter curParam = null;
10349                      Class sClass;
10350
10351                      for(sClass = tClass; sClass; sClass = sClass.base)
10352                      {
10353                         id = 0;
10354                         if(sClass.templateClass) sClass = sClass.templateClass;
10355                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10356                         {
10357                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10358                            {
10359                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10360                                  id += sClass.templateParams.count;
10361                               break;
10362                            }
10363                            id++;
10364                         }
10365                         if(curParam) break;
10366                      }
10367
10368                      if(curParam && tClass.templateArgs[id].dataTypeString)
10369                      {
10370                         ClassTemplateArgument arg = tClass.templateArgs[id];
10371                         Context context = SetupTemplatesContext(tClass);
10372                         bool constant = exp.expType.constant;
10373                         /*if(!arg.dataType)
10374                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10375                         FreeType(exp.expType);
10376
10377                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10378                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10379                         else if(exp.expType.kind == pointerType)
10380                         {
10381                            Type t = exp.expType.type;
10382                            while(t.kind == pointerType) t = t.type;
10383                            if(constant) t.constant = constant;
10384                         }
10385                         if(exp.expType)
10386                         {
10387                            if(exp.expType.kind == thisClassType)
10388                            {
10389                               FreeType(exp.expType);
10390                               exp.expType = ReplaceThisClassType(_class);
10391                            }
10392
10393                            if(tClass.templateClass && (exp.expType.kind != templateType || (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType))))
10394                               exp.expType.passAsTemplate = true;
10395                            //exp.expType.refCount++;
10396                            if(!exp.destType)
10397                            {
10398                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10399                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10400                               else if(exp.destType.kind == pointerType)
10401                               {
10402                                  Type t = exp.destType.type;
10403                                  while(t.kind == pointerType) t = t.type;
10404                                  if(constant) t.constant = constant;
10405                               }
10406
10407                               //exp.destType.refCount++;
10408
10409                               if(exp.destType.kind == thisClassType)
10410                               {
10411                                  FreeType(exp.destType);
10412                                  exp.destType = ReplaceThisClassType(_class);
10413                               }
10414                            }
10415                         }
10416                         FinishTemplatesContext(context);
10417                      }
10418                   }
10419                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10420                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10421                   {
10422                      int id = 0;
10423                      ClassTemplateParameter curParam = null;
10424                      Class sClass;
10425
10426                      for(sClass = tClass; sClass; sClass = sClass.base)
10427                      {
10428                         id = 0;
10429                         if(sClass.templateClass) sClass = sClass.templateClass;
10430                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10431                         {
10432                            if(curParam.type == TemplateParameterType::type &&
10433                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10434                            {
10435                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10436                                  id += sClass.templateParams.count;
10437                               break;
10438                            }
10439                            id++;
10440                         }
10441                         if(curParam) break;
10442                      }
10443
10444                      if(curParam)
10445                      {
10446                         ClassTemplateArgument arg = tClass.templateArgs[id];
10447                         Context context = SetupTemplatesContext(tClass);
10448                         Type basicType;
10449                         /*if(!arg.dataType)
10450                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10451
10452                         basicType = ProcessTypeString(arg.dataTypeString, false);
10453                         if(basicType)
10454                         {
10455                            if(basicType.kind == thisClassType)
10456                            {
10457                               FreeType(basicType);
10458                               basicType = ReplaceThisClassType(_class);
10459                            }
10460
10461                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10462                            if(tClass.templateClass)
10463                               basicType.passAsTemplate = true;
10464                            */
10465
10466                            FreeType(exp.expType);
10467
10468                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10469                            //exp.expType.refCount++;
10470                            if(!exp.destType)
10471                            {
10472                               exp.destType = exp.expType;
10473                               exp.destType.refCount++;
10474                            }
10475
10476                            {
10477                               Expression newExp { };
10478                               OldList * specs = MkList();
10479                               Declarator decl;
10480                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10481                               *newExp = *exp;
10482                               if(exp.destType) exp.destType.refCount++;
10483                               if(exp.expType)  exp.expType.refCount++;
10484                               exp.type = castExp;
10485                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10486                               exp.cast.exp = newExp;
10487                               //FreeType(exp.expType);
10488                               //exp.expType = null;
10489                               //ProcessExpressionType(sourceExp);
10490                            }
10491                         }
10492                         FinishTemplatesContext(context);
10493                      }
10494                   }
10495                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10496                   {
10497                      Class expClass = exp.expType._class.registered;
10498                      if(expClass)
10499                      {
10500                         Class cClass = null;
10501                         int p = 0;
10502                         int paramCount = 0;
10503                         int lastParam = -1;
10504                         char templateString[1024];
10505                         ClassTemplateParameter param;
10506                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10507                         while(cClass != expClass)
10508                         {
10509                            Class sClass;
10510                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10511                            cClass = sClass;
10512
10513                            for(param = cClass.templateParams.first; param; param = param.next)
10514                            {
10515                               Class cClassCur = null;
10516                               int cp = 0;
10517                               ClassTemplateParameter paramCur = null;
10518                               ClassTemplateArgument arg;
10519                               while(cClassCur != tClass && !paramCur)
10520                               {
10521                                  Class sClassCur;
10522                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10523                                  cClassCur = sClassCur;
10524
10525                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10526                                  {
10527                                     if(!strcmp(paramCur.name, param.name))
10528                                     {
10529
10530                                        break;
10531                                     }
10532                                     cp++;
10533                                  }
10534                               }
10535                               if(paramCur && paramCur.type == TemplateParameterType::type)
10536                                  arg = tClass.templateArgs[cp];
10537                               else
10538                                  arg = expClass.templateArgs[p];
10539
10540                               {
10541                                  char argument[256];
10542                                  argument[0] = '\0';
10543                                  /*if(arg.name)
10544                                  {
10545                                     strcat(argument, arg.name.string);
10546                                     strcat(argument, " = ");
10547                                  }*/
10548                                  switch(param.type)
10549                                  {
10550                                     case expression:
10551                                     {
10552                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10553                                        char expString[1024];
10554                                        OldList * specs = MkList();
10555                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10556                                        Expression exp;
10557                                        char * string = PrintHexUInt64(arg.expression.ui64);
10558                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10559                                        delete string;
10560
10561                                        ProcessExpressionType(exp);
10562                                        ComputeExpression(exp);
10563                                        expString[0] = '\0';
10564                                        PrintExpression(exp, expString);
10565                                        strcat(argument, expString);
10566                                        // delete exp;
10567                                        FreeExpression(exp);
10568                                        break;
10569                                     }
10570                                     case identifier:
10571                                     {
10572                                        strcat(argument, arg.member.name);
10573                                        break;
10574                                     }
10575                                     case TemplateParameterType::type:
10576                                     {
10577                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10578                                           strcat(argument, arg.dataTypeString);
10579                                        break;
10580                                     }
10581                                  }
10582                                  if(argument[0])
10583                                  {
10584                                     if(paramCount) strcat(templateString, ", ");
10585                                     if(lastParam != p - 1)
10586                                     {
10587                                        strcat(templateString, param.name);
10588                                        strcat(templateString, " = ");
10589                                     }
10590                                     strcat(templateString, argument);
10591                                     paramCount++;
10592                                     lastParam = p;
10593                                  }
10594                               }
10595                               p++;
10596                            }
10597                         }
10598                         {
10599                            int len = strlen(templateString);
10600                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10601                            templateString[len++] = '>';
10602                            templateString[len++] = '\0';
10603                         }
10604
10605                         FreeType(exp.expType);
10606                         {
10607                            Context context = SetupTemplatesContext(tClass);
10608                            exp.expType = ProcessTypeString(templateString, false);
10609                            FinishTemplatesContext(context);
10610                         }
10611                      }
10612                   }
10613                }
10614             }
10615             else
10616                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10617          }
10618          else if(type && (type.kind == structType || type.kind == unionType))
10619          {
10620             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10621             if(memberType)
10622             {
10623                exp.expType = memberType;
10624                if(memberType)
10625                   memberType.refCount++;
10626             }
10627          }
10628          else
10629          {
10630             char expString[10240];
10631             expString[0] = '\0';
10632             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10633             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10634          }
10635
10636          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10637          {
10638             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10639             {
10640                Identifier id = exp.member.member;
10641                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10642                if(_class)
10643                {
10644                   FreeType(exp.expType);
10645                   exp.expType = ReplaceThisClassType(_class);
10646                }
10647             }
10648          }
10649          yylloc = oldyylloc;
10650          break;
10651       }
10652       // Convert x->y into (*x).y
10653       case pointerExp:
10654       {
10655          Type destType = exp.destType;
10656
10657          // DOING THIS LATER NOW...
10658          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10659          {
10660             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10661             /* TODO: Name Space Fix ups
10662             if(!exp.member.member.classSym)
10663                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10664             */
10665          }
10666
10667          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10668          exp.type = memberExp;
10669          if(destType)
10670             destType.count++;
10671          ProcessExpressionType(exp);
10672          if(destType)
10673             destType.count--;
10674          break;
10675       }
10676       case classSizeExp:
10677       {
10678          //ComputeExpression(exp);
10679
10680          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10681          if(classSym && classSym.registered)
10682          {
10683             if(classSym.registered.type == noHeadClass)
10684             {
10685                char name[1024];
10686                name[0] = '\0';
10687                DeclareStruct(classSym.string, false);
10688                FreeSpecifier(exp._class);
10689                exp.type = typeSizeExp;
10690                FullClassNameCat(name, classSym.string, false);
10691                exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10692             }
10693             else
10694             {
10695                if(classSym.registered.fixed)
10696                {
10697                   FreeSpecifier(exp._class);
10698                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10699                   exp.type = constantExp;
10700                }
10701                else
10702                {
10703                   char className[1024];
10704                   strcpy(className, "__ecereClass_");
10705                   FullClassNameCat(className, classSym.string, true);
10706                   //MangleClassName(className);
10707
10708                   DeclareClass(classSym, className);
10709
10710                   FreeExpContents(exp);
10711                   exp.type = pointerExp;
10712                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10713                   exp.member.member = MkIdentifier("structSize");
10714                }
10715             }
10716          }
10717
10718          exp.expType = Type
10719          {
10720             refCount = 1;
10721             kind = intSizeType;
10722          };
10723          // exp.isConstant = true;
10724          break;
10725       }
10726       case typeSizeExp:
10727       {
10728          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10729
10730          exp.expType = Type
10731          {
10732             refCount = 1;
10733             kind = intSizeType;
10734          };
10735          exp.isConstant = true;
10736
10737          DeclareType(type, false, false);
10738          FreeType(type);
10739          break;
10740       }
10741       case castExp:
10742       {
10743          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10744          type.count = 1;
10745          FreeType(exp.cast.exp.destType);
10746          exp.cast.exp.destType = type;
10747          type.refCount++;
10748          type.casted = true;
10749          ProcessExpressionType(exp.cast.exp);
10750          type.casted = false;
10751          type.count = 0;
10752          exp.expType = type;
10753          //type.refCount++;
10754
10755          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10756          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10757          {
10758             void * prev = exp.prev, * next = exp.next;
10759             Type expType = exp.cast.exp.destType;
10760             Expression castExp = exp.cast.exp;
10761             Type destType = exp.destType;
10762
10763             if(expType) expType.refCount++;
10764
10765             //FreeType(exp.destType);
10766             FreeType(exp.expType);
10767             FreeTypeName(exp.cast.typeName);
10768
10769             *exp = *castExp;
10770             FreeType(exp.expType);
10771             FreeType(exp.destType);
10772
10773             exp.expType = expType;
10774             exp.destType = destType;
10775
10776             delete castExp;
10777
10778             exp.prev = prev;
10779             exp.next = next;
10780
10781          }
10782          else
10783          {
10784             exp.isConstant = exp.cast.exp.isConstant;
10785          }
10786          //FreeType(type);
10787          break;
10788       }
10789       case extensionInitializerExp:
10790       {
10791          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10792          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10793          // ProcessInitializer(exp.initializer.initializer, type);
10794          exp.expType = type;
10795          break;
10796       }
10797       case vaArgExp:
10798       {
10799          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10800          ProcessExpressionType(exp.vaArg.exp);
10801          exp.expType = type;
10802          break;
10803       }
10804       case conditionExp:
10805       {
10806          Expression e;
10807          exp.isConstant = true;
10808
10809          FreeType(exp.cond.cond.destType);
10810          exp.cond.cond.destType = MkClassType("bool");
10811          exp.cond.cond.destType.truth = true;
10812          ProcessExpressionType(exp.cond.cond);
10813          if(!exp.cond.cond.isConstant)
10814             exp.isConstant = false;
10815          for(e = exp.cond.exp->first; e; e = e.next)
10816          {
10817             if(!e.next)
10818             {
10819                FreeType(e.destType);
10820                e.destType = exp.destType;
10821                if(e.destType) e.destType.refCount++;
10822             }
10823             ProcessExpressionType(e);
10824             if(!e.next)
10825             {
10826                exp.expType = e.expType;
10827                if(e.expType) e.expType.refCount++;
10828             }
10829             if(!e.isConstant)
10830                exp.isConstant = false;
10831          }
10832
10833          FreeType(exp.cond.elseExp.destType);
10834          // Added this check if we failed to find an expType
10835          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10836
10837          // Reversed it...
10838          exp.cond.elseExp.destType = exp.destType ? exp.destType : exp.expType;
10839
10840          if(exp.cond.elseExp.destType)
10841             exp.cond.elseExp.destType.refCount++;
10842          ProcessExpressionType(exp.cond.elseExp);
10843
10844          // FIXED THIS: Was done before calling process on elseExp
10845          if(!exp.cond.elseExp.isConstant)
10846             exp.isConstant = false;
10847          break;
10848       }
10849       case extensionCompoundExp:
10850       {
10851          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10852          {
10853             Statement last = exp.compound.compound.statements->last;
10854             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10855             {
10856                ((Expression)last.expressions->last).destType = exp.destType;
10857                if(exp.destType)
10858                   exp.destType.refCount++;
10859             }
10860             ProcessStatement(exp.compound);
10861             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10862             if(exp.expType)
10863                exp.expType.refCount++;
10864          }
10865          break;
10866       }
10867       case classExp:
10868       {
10869          Specifier spec = exp._classExp.specifiers->first;
10870          if(spec && spec.type == nameSpecifier)
10871          {
10872             exp.expType = MkClassType(spec.name);
10873             exp.expType.kind = subClassType;
10874             exp.byReference = true;
10875          }
10876          else
10877          {
10878             exp.expType = MkClassType("ecere::com::Class");
10879             exp.byReference = true;
10880          }
10881          break;
10882       }
10883       case classDataExp:
10884       {
10885          Class _class = thisClass ? thisClass : currentClass;
10886          if(_class)
10887          {
10888             Identifier id = exp.classData.id;
10889             char structName[1024];
10890             Expression classExp;
10891             strcpy(structName, "__ecereClassData_");
10892             FullClassNameCat(structName, _class.fullName, false);
10893             exp.type = pointerExp;
10894             exp.member.member = id;
10895             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10896                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10897             else
10898                classExp = MkExpIdentifier(MkIdentifier("class"));
10899
10900             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10901                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10902                   MkExpBrackets(MkListOne(MkExpOp(
10903                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10904                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10905                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10906                      )));
10907
10908             ProcessExpressionType(exp);
10909             return;
10910          }
10911          break;
10912       }
10913       case arrayExp:
10914       {
10915          Type type = null;
10916          const char * typeString = null;
10917          char typeStringBuf[1024];
10918          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
10919             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
10920          {
10921             Class templateClass = exp.destType._class.registered;
10922             typeString = templateClass.templateArgs[2].dataTypeString;
10923          }
10924          else if(exp.list)
10925          {
10926             // Guess type from expressions in the array
10927             Expression e;
10928             for(e = exp.list->first; e; e = e.next)
10929             {
10930                ProcessExpressionType(e);
10931                if(e.expType)
10932                {
10933                   if(!type) { type = e.expType; type.refCount++; }
10934                   else
10935                   {
10936                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
10937                      if(!MatchTypeExpression(e, type, null, false, true))
10938                      {
10939                         FreeType(type);
10940                         type = e.expType;
10941                         e.expType = null;
10942
10943                         e = exp.list->first;
10944                         ProcessExpressionType(e);
10945                         if(e.expType)
10946                         {
10947                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
10948                            if(!MatchTypeExpression(e, type, null, false, true))
10949                            {
10950                               FreeType(e.expType);
10951                               e.expType = null;
10952                               FreeType(type);
10953                               type = null;
10954                               break;
10955                            }
10956                         }
10957                      }
10958                   }
10959                   if(e.expType)
10960                   {
10961                      FreeType(e.expType);
10962                      e.expType = null;
10963                   }
10964                }
10965             }
10966             if(type)
10967             {
10968                typeStringBuf[0] = '\0';
10969                PrintTypeNoConst(type, typeStringBuf, false, true);
10970                typeString = typeStringBuf;
10971                FreeType(type);
10972                type = null;
10973             }
10974          }
10975          if(typeString)
10976          {
10977             /*
10978             (Container)& (struct BuiltInContainer)
10979             {
10980                ._vTbl = class(BuiltInContainer)._vTbl,
10981                ._class = class(BuiltInContainer),
10982                .refCount = 0,
10983                .data = (int[]){ 1, 7, 3, 4, 5 },
10984                .count = 5,
10985                .type = class(int),
10986             }
10987             */
10988             char templateString[1024];
10989             OldList * initializers = MkList();
10990             OldList * structInitializers = MkList();
10991             OldList * specs = MkList();
10992             Expression expExt;
10993             Declarator decl = SpecDeclFromString(typeString, specs, null);
10994             sprintf(templateString, "Container<%s>", typeString);
10995
10996             if(exp.list)
10997             {
10998                Expression e;
10999                type = ProcessTypeString(typeString, false);
11000                while((e = exp.list->first))
11001                {
11002                   exp.list->Remove(e);
11003                   e.destType = type;
11004                   type.refCount++;
11005                   ProcessExpressionType(e);
11006                   ListAdd(initializers, MkInitializerAssignment(e));
11007                }
11008                FreeType(type);
11009                delete exp.list;
11010             }
11011
11012             DeclareStruct("ecere::com::BuiltInContainer", false);
11013
11014             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11015                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11016             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11017                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11018             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11019                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11020             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11021                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11022                MkInitializerList(initializers))));
11023                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11024             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11025                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11026             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11027                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11028             exp.expType = ProcessTypeString(templateString, false);
11029             exp.type = bracketsExp;
11030             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11031                MkExpOp(null, '&',
11032                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11033                   MkInitializerList(structInitializers)))));
11034             ProcessExpressionType(expExt);
11035          }
11036          else
11037          {
11038             exp.expType = ProcessTypeString("Container", false);
11039             Compiler_Error($"Couldn't determine type of array elements\n");
11040          }
11041          break;
11042       }
11043    }
11044
11045    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11046    {
11047       FreeType(exp.expType);
11048       exp.expType = ReplaceThisClassType(thisClass);
11049    }
11050
11051    // Resolve structures here
11052    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11053    {
11054       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11055       // TODO: Fix members reference...
11056       if(symbol)
11057       {
11058          if(exp.expType.kind != enumType)
11059          {
11060             Type member;
11061             String enumName = CopyString(exp.expType.enumName);
11062
11063             // Fixed a memory leak on self-referencing C structs typedefs
11064             // by instantiating a new type rather than simply copying members
11065             // into exp.expType
11066             FreeType(exp.expType);
11067             exp.expType = Type { };
11068             exp.expType.kind = symbol.type.kind;
11069             exp.expType.refCount++;
11070             exp.expType.enumName = enumName;
11071
11072             exp.expType.members = symbol.type.members;
11073             for(member = symbol.type.members.first; member; member = member.next)
11074                member.refCount++;
11075          }
11076          else
11077          {
11078             NamedLink64 member;
11079             for(member = symbol.type.members.first; member; member = member.next)
11080             {
11081                NamedLink64 value { name = CopyString(member.name) };
11082                exp.expType.members.Add(value);
11083             }
11084          }
11085       }
11086    }
11087
11088    yylloc = exp.loc;
11089    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11090    else if(exp.destType && !exp.destType.keepCast)
11091    {
11092       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11093          exp.needTemplateCast = 1;
11094
11095       if(exp.destType.kind == voidType);
11096       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11097       {
11098          if(!exp.destType.count || unresolved)
11099          {
11100             if(!exp.expType)
11101             {
11102                yylloc = exp.loc;
11103                if(exp.destType.kind != ellipsisType)
11104                {
11105                   char type2[1024];
11106                   type2[0] = '\0';
11107                   if(inCompiler)
11108                   {
11109                      char expString[10240];
11110                      expString[0] = '\0';
11111
11112                      PrintType(exp.destType, type2, false, true);
11113
11114                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11115                      if(unresolved)
11116                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11117                      else if(exp.type != dummyExp)
11118                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11119                   }
11120                }
11121                else
11122                {
11123                   char expString[10240] ;
11124                   expString[0] = '\0';
11125                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11126
11127                   if(unresolved)
11128                      Compiler_Error($"unresolved identifier %s\n", expString);
11129                   else if(exp.type != dummyExp)
11130                      Compiler_Error($"couldn't determine type of %s\n", expString);
11131                }
11132             }
11133             else
11134             {
11135                char type1[1024];
11136                char type2[1024];
11137                type1[0] = '\0';
11138                type2[0] = '\0';
11139                if(inCompiler)
11140                {
11141                   PrintType(exp.expType, type1, false, true);
11142                   PrintType(exp.destType, type2, false, true);
11143                }
11144
11145                //CheckExpressionType(exp, exp.destType, false);
11146
11147                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11148                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11149                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11150                else
11151                {
11152                   char expString[10240];
11153                   expString[0] = '\0';
11154                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11155
11156 #ifdef _DEBUG
11157                   CheckExpressionType(exp, exp.destType, false, true);
11158 #endif
11159                   // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11160                   if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11161                                      !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11162                                      !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11163                                      !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11164                      Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11165
11166                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11167                   FreeType(exp.expType);
11168                   exp.destType.refCount++;
11169                   exp.expType = exp.destType;
11170                }
11171             }
11172          }
11173       }
11174       // Cast function pointers to void * as eC already checked compatibility
11175       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11176               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11177       {
11178          Expression nbExp = GetNonBracketsExp(exp);
11179          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11180          {
11181             Expression e = MoveExpContents(exp);
11182             exp.cast.exp = MkExpBrackets(MkListOne(e));
11183             exp.type = castExp;
11184             exp.cast.exp.destType = exp.destType;
11185             if(exp.destType) exp.destType.refCount++;
11186             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11187          }
11188       }
11189    }
11190    else if(unresolved)
11191    {
11192       if(exp.identifier._class && exp.identifier._class.name)
11193          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11194       else if(exp.identifier.string && exp.identifier.string[0])
11195          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11196    }
11197    else if(!exp.expType && exp.type != dummyExp)
11198    {
11199       char expString[10240];
11200       expString[0] = '\0';
11201       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11202       Compiler_Error($"couldn't determine type of %s\n", expString);
11203    }
11204
11205    // Let's try to support any_object & typed_object here:
11206    if(inCompiler)
11207       ApplyAnyObjectLogic(exp);
11208
11209    // Mark nohead classes as by reference, unless we're casting them to an integral type
11210    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11211       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11212          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11213           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11214    {
11215       exp.byReference = true;
11216    }
11217    yylloc = oldyylloc;
11218 }
11219
11220 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11221 {
11222    // THIS CODE WILL FIND NEXT MEMBER...
11223    if(*curMember)
11224    {
11225       *curMember = (*curMember).next;
11226
11227       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11228       {
11229          *curMember = subMemberStack[--(*subMemberStackPos)];
11230          *curMember = (*curMember).next;
11231       }
11232
11233       // SKIP ALL PROPERTIES HERE...
11234       while((*curMember) && (*curMember).isProperty)
11235          *curMember = (*curMember).next;
11236
11237       if(subMemberStackPos)
11238       {
11239          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11240          {
11241             subMemberStack[(*subMemberStackPos)++] = *curMember;
11242
11243             *curMember = (*curMember).members.first;
11244             while(*curMember && (*curMember).isProperty)
11245                *curMember = (*curMember).next;
11246          }
11247       }
11248    }
11249    while(!*curMember)
11250    {
11251       if(!*curMember)
11252       {
11253          if(subMemberStackPos && *subMemberStackPos)
11254          {
11255             *curMember = subMemberStack[--(*subMemberStackPos)];
11256             *curMember = (*curMember).next;
11257          }
11258          else
11259          {
11260             Class lastCurClass = *curClass;
11261
11262             if(*curClass == _class) break;     // REACHED THE END
11263
11264             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11265             *curMember = (*curClass).membersAndProperties.first;
11266          }
11267
11268          while((*curMember) && (*curMember).isProperty)
11269             *curMember = (*curMember).next;
11270          if(subMemberStackPos)
11271          {
11272             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11273             {
11274                subMemberStack[(*subMemberStackPos)++] = *curMember;
11275
11276                *curMember = (*curMember).members.first;
11277                while(*curMember && (*curMember).isProperty)
11278                   *curMember = (*curMember).next;
11279             }
11280          }
11281       }
11282    }
11283 }
11284
11285
11286 static void ProcessInitializer(Initializer init, Type type)
11287 {
11288    switch(init.type)
11289    {
11290       case expInitializer:
11291          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11292          {
11293             // TESTING THIS FOR SHUTTING = 0 WARNING
11294             if(init.exp && !init.exp.destType)
11295             {
11296                FreeType(init.exp.destType);
11297                init.exp.destType = type;
11298                if(type) type.refCount++;
11299             }
11300             if(init.exp)
11301             {
11302                ProcessExpressionType(init.exp);
11303                init.isConstant = init.exp.isConstant;
11304             }
11305             break;
11306          }
11307          else
11308          {
11309             Expression exp = init.exp;
11310             Instantiation inst = exp.instance;
11311             MembersInit members;
11312
11313             init.type = listInitializer;
11314             init.list = MkList();
11315
11316             if(inst.members)
11317             {
11318                for(members = inst.members->first; members; members = members.next)
11319                {
11320                   if(members.type == dataMembersInit)
11321                   {
11322                      MemberInit member;
11323                      for(member = members.dataMembers->first; member; member = member.next)
11324                      {
11325                         ListAdd(init.list, member.initializer);
11326                         member.initializer = null;
11327                      }
11328                   }
11329                   // Discard all MembersInitMethod
11330                }
11331             }
11332             FreeExpression(exp);
11333          }
11334       case listInitializer:
11335       {
11336          Initializer i;
11337          Type initializerType = null;
11338          Class curClass = null;
11339          DataMember curMember = null;
11340          DataMember subMemberStack[256];
11341          int subMemberStackPos = 0;
11342
11343          if(type && type.kind == arrayType)
11344             initializerType = Dereference(type);
11345          else if(type && (type.kind == structType || type.kind == unionType))
11346             initializerType = type.members.first;
11347
11348          for(i = init.list->first; i; i = i.next)
11349          {
11350             if(type && type.kind == classType && type._class && type._class.registered)
11351             {
11352                // 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)
11353                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11354                // TODO: Generate error on initializing a private data member this way from another module...
11355                if(curMember)
11356                {
11357                   if(!curMember.dataType)
11358                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11359                   initializerType = curMember.dataType;
11360                }
11361             }
11362             ProcessInitializer(i, initializerType);
11363             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11364                initializerType = initializerType.next;
11365             if(!i.isConstant)
11366                init.isConstant = false;
11367          }
11368
11369          if(type && type.kind == arrayType)
11370             FreeType(initializerType);
11371
11372          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11373          {
11374             Compiler_Error($"Assigning list initializer to non list\n");
11375          }
11376          break;
11377       }
11378    }
11379 }
11380
11381 static void ProcessSpecifier(Specifier spec, bool declareStruct)
11382 {
11383    switch(spec.type)
11384    {
11385       case baseSpecifier:
11386       {
11387          if(spec.specifier == THISCLASS)
11388          {
11389             if(thisClass)
11390             {
11391                spec.type = nameSpecifier;
11392                spec.name = ReplaceThisClass(thisClass);
11393                spec.symbol = FindClass(spec.name);
11394                ProcessSpecifier(spec, declareStruct);
11395             }
11396          }
11397          break;
11398       }
11399       case nameSpecifier:
11400       {
11401          Symbol symbol = FindType(curContext, spec.name);
11402          if(symbol)
11403             DeclareType(symbol.type, true, true);
11404          else if((symbol = spec.symbol /*FindClass(spec.name)*/) && symbol.registered && symbol.registered.type == structClass && declareStruct)
11405             DeclareStruct(spec.name, false);
11406          break;
11407       }
11408       case enumSpecifier:
11409       {
11410          Enumerator e;
11411          if(spec.list)
11412          {
11413             for(e = spec.list->first; e; e = e.next)
11414             {
11415                if(e.exp)
11416                   ProcessExpressionType(e.exp);
11417             }
11418          }
11419          break;
11420       }
11421       case structSpecifier:
11422       case unionSpecifier:
11423       {
11424          if(spec.definitions)
11425          {
11426             //ClassDef def;
11427             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11428             //if(symbol)
11429                ProcessClass(spec.definitions, symbol);
11430             /*else
11431             {
11432                for(def = spec.definitions->first; def; def = def.next)
11433                {
11434                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11435                      ProcessDeclaration(def.decl);
11436                }
11437             }*/
11438          }
11439          break;
11440       }
11441       /*
11442       case classSpecifier:
11443       {
11444          Symbol classSym = FindClass(spec.name);
11445          if(classSym && classSym.registered && classSym.registered.type == structClass)
11446             DeclareStruct(spec.name, false);
11447          break;
11448       }
11449       */
11450    }
11451 }
11452
11453
11454 static void ProcessDeclarator(Declarator decl)
11455 {
11456    switch(decl.type)
11457    {
11458       case identifierDeclarator:
11459          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11460          {
11461             FreeSpecifier(decl.identifier._class);
11462             decl.identifier._class = null;
11463          }
11464          break;
11465       case arrayDeclarator:
11466          if(decl.array.exp)
11467             ProcessExpressionType(decl.array.exp);
11468       case structDeclarator:
11469       case bracketsDeclarator:
11470       case functionDeclarator:
11471       case pointerDeclarator:
11472       case extendedDeclarator:
11473       case extendedDeclaratorEnd:
11474          if(decl.declarator)
11475             ProcessDeclarator(decl.declarator);
11476          if(decl.type == functionDeclarator)
11477          {
11478             Identifier id = GetDeclId(decl);
11479             if(id && id._class)
11480             {
11481                TypeName param
11482                {
11483                   qualifiers = MkListOne(id._class);
11484                   declarator = null;
11485                };
11486                if(!decl.function.parameters)
11487                   decl.function.parameters = MkList();
11488                decl.function.parameters->Insert(null, param);
11489                id._class = null;
11490             }
11491             if(decl.function.parameters)
11492             {
11493                TypeName param;
11494
11495                for(param = decl.function.parameters->first; param; param = param.next)
11496                {
11497                   if(param.qualifiers && param.qualifiers->first)
11498                   {
11499                      Specifier spec = param.qualifiers->first;
11500                      if(spec && spec.specifier == TYPED_OBJECT)
11501                      {
11502                         Declarator d = param.declarator;
11503                         TypeName newParam
11504                         {
11505                            qualifiers = MkListOne(MkSpecifier(VOID));
11506                            declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11507                         };
11508                         if(d.type != pointerDeclarator)
11509                            newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11510
11511                         FreeList(param.qualifiers, FreeSpecifier);
11512
11513                         param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11514                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11515
11516                         decl.function.parameters->Insert(param, newParam);
11517                         param = newParam;
11518                      }
11519                      else if(spec && spec.specifier == ANY_OBJECT)
11520                      {
11521                         Declarator d = param.declarator;
11522
11523                         FreeList(param.qualifiers, FreeSpecifier);
11524
11525                         param.qualifiers = MkListOne(MkSpecifier(VOID));
11526                         if(d.type != pointerDeclarator)
11527                            param.qualifiers->Insert(null, MkSpecifier(CONST));
11528                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11529                      }
11530                      else if(spec.specifier == THISCLASS)
11531                      {
11532                         if(thisClass)
11533                         {
11534                            spec.type = nameSpecifier;
11535                            spec.name = ReplaceThisClass(thisClass);
11536                            spec.symbol = FindClass(spec.name);
11537                            ProcessSpecifier(spec, false);
11538                         }
11539                      }
11540                   }
11541
11542                   if(param.declarator)
11543                      ProcessDeclarator(param.declarator);
11544                }
11545             }
11546          }
11547          break;
11548    }
11549 }
11550
11551 static void ProcessDeclaration(Declaration decl)
11552 {
11553    yylloc = decl.loc;
11554    switch(decl.type)
11555    {
11556       case initDeclaration:
11557       {
11558          bool declareStruct = false;
11559          /*
11560          lineNum = decl.pos.line;
11561          column = decl.pos.col;
11562          */
11563
11564          if(decl.declarators)
11565          {
11566             InitDeclarator d;
11567
11568             for(d = decl.declarators->first; d; d = d.next)
11569             {
11570                Type type, subType;
11571                ProcessDeclarator(d.declarator);
11572
11573                type = ProcessType(decl.specifiers, d.declarator);
11574
11575                if(d.initializer)
11576                {
11577                   ProcessInitializer(d.initializer, type);
11578
11579                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11580
11581                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11582                      d.initializer.exp.type == instanceExp)
11583                   {
11584                      if(type.kind == classType && type._class ==
11585                         d.initializer.exp.expType._class)
11586                      {
11587                         Instantiation inst = d.initializer.exp.instance;
11588                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11589
11590                         d.initializer.exp.instance = null;
11591                         if(decl.specifiers)
11592                            FreeList(decl.specifiers, FreeSpecifier);
11593                         FreeList(decl.declarators, FreeInitDeclarator);
11594
11595                         d = null;
11596
11597                         decl.type = instDeclaration;
11598                         decl.inst = inst;
11599                      }
11600                   }
11601                }
11602                for(subType = type; subType;)
11603                {
11604                   if(subType.kind == classType)
11605                   {
11606                      declareStruct = true;
11607                      break;
11608                   }
11609                   else if(subType.kind == pointerType)
11610                      break;
11611                   else if(subType.kind == arrayType)
11612                      subType = subType.arrayType;
11613                   else
11614                      break;
11615                }
11616
11617                FreeType(type);
11618                if(!d) break;
11619             }
11620          }
11621
11622          if(decl.specifiers)
11623          {
11624             Specifier s;
11625             for(s = decl.specifiers->first; s; s = s.next)
11626             {
11627                ProcessSpecifier(s, declareStruct);
11628             }
11629          }
11630          break;
11631       }
11632       case instDeclaration:
11633       {
11634          ProcessInstantiationType(decl.inst);
11635          break;
11636       }
11637       case structDeclaration:
11638       {
11639          Specifier spec;
11640          Declarator d;
11641          bool declareStruct = false;
11642
11643          if(decl.declarators)
11644          {
11645             for(d = decl.declarators->first; d; d = d.next)
11646             {
11647                Type type = ProcessType(decl.specifiers, d.declarator);
11648                Type subType;
11649                ProcessDeclarator(d);
11650                for(subType = type; subType;)
11651                {
11652                   if(subType.kind == classType)
11653                   {
11654                      declareStruct = true;
11655                      break;
11656                   }
11657                   else if(subType.kind == pointerType)
11658                      break;
11659                   else if(subType.kind == arrayType)
11660                      subType = subType.arrayType;
11661                   else
11662                      break;
11663                }
11664                FreeType(type);
11665             }
11666          }
11667          if(decl.specifiers)
11668          {
11669             for(spec = decl.specifiers->first; spec; spec = spec.next)
11670                ProcessSpecifier(spec, declareStruct);
11671          }
11672          break;
11673       }
11674    }
11675 }
11676
11677 static FunctionDefinition curFunction;
11678
11679 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11680 {
11681    char propName[1024], propNameM[1024];
11682    char getName[1024], setName[1024];
11683    OldList * args;
11684
11685    DeclareProperty(prop, setName, getName);
11686
11687    // eInstance_FireWatchers(object, prop);
11688    strcpy(propName, "__ecereProp_");
11689    FullClassNameCat(propName, prop._class.fullName, false);
11690    strcat(propName, "_");
11691    // strcat(propName, prop.name);
11692    FullClassNameCat(propName, prop.name, true);
11693    //MangleClassName(propName);
11694
11695    strcpy(propNameM, "__ecerePropM_");
11696    FullClassNameCat(propNameM, prop._class.fullName, false);
11697    strcat(propNameM, "_");
11698    // strcat(propNameM, prop.name);
11699    FullClassNameCat(propNameM, prop.name, true);
11700    //MangleClassName(propNameM);
11701
11702    if(prop.isWatchable)
11703    {
11704       args = MkList();
11705       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11706       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11707       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11708
11709       args = MkList();
11710       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11711       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11712       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11713    }
11714
11715
11716    {
11717       args = MkList();
11718       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11719       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11720       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11721
11722       args = MkList();
11723       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11724       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11725       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11726    }
11727
11728    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11729       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11730       curFunction.propSet.fireWatchersDone = true;
11731 }
11732
11733 static void ProcessStatement(Statement stmt)
11734 {
11735    yylloc = stmt.loc;
11736    /*
11737    lineNum = stmt.pos.line;
11738    column = stmt.pos.col;
11739    */
11740    switch(stmt.type)
11741    {
11742       case labeledStmt:
11743          ProcessStatement(stmt.labeled.stmt);
11744          break;
11745       case caseStmt:
11746          // This expression should be constant...
11747          if(stmt.caseStmt.exp)
11748          {
11749             FreeType(stmt.caseStmt.exp.destType);
11750             stmt.caseStmt.exp.destType = curSwitchType;
11751             if(curSwitchType) curSwitchType.refCount++;
11752             ProcessExpressionType(stmt.caseStmt.exp);
11753             ComputeExpression(stmt.caseStmt.exp);
11754          }
11755          if(stmt.caseStmt.stmt)
11756             ProcessStatement(stmt.caseStmt.stmt);
11757          break;
11758       case compoundStmt:
11759       {
11760          if(stmt.compound.context)
11761          {
11762             Declaration decl;
11763             Statement s;
11764
11765             Statement prevCompound = curCompound;
11766             Context prevContext = curContext;
11767
11768             if(!stmt.compound.isSwitch)
11769                curCompound = stmt;
11770             curContext = stmt.compound.context;
11771
11772             if(stmt.compound.declarations)
11773             {
11774                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
11775                   ProcessDeclaration(decl);
11776             }
11777             if(stmt.compound.statements)
11778             {
11779                for(s = stmt.compound.statements->first; s; s = s.next)
11780                   ProcessStatement(s);
11781             }
11782
11783             curContext = prevContext;
11784             curCompound = prevCompound;
11785          }
11786          break;
11787       }
11788       case expressionStmt:
11789       {
11790          Expression exp;
11791          if(stmt.expressions)
11792          {
11793             for(exp = stmt.expressions->first; exp; exp = exp.next)
11794                ProcessExpressionType(exp);
11795          }
11796          break;
11797       }
11798       case ifStmt:
11799       {
11800          Expression exp;
11801
11802          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
11803          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
11804          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
11805          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
11806          {
11807             ProcessExpressionType(exp);
11808          }
11809          if(stmt.ifStmt.stmt)
11810             ProcessStatement(stmt.ifStmt.stmt);
11811          if(stmt.ifStmt.elseStmt)
11812             ProcessStatement(stmt.ifStmt.elseStmt);
11813          break;
11814       }
11815       case switchStmt:
11816       {
11817          Type oldSwitchType = curSwitchType;
11818          if(stmt.switchStmt.exp)
11819          {
11820             Expression exp;
11821             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
11822             {
11823                if(!exp.next)
11824                {
11825                   /*
11826                   Type destType
11827                   {
11828                      kind = intType;
11829                      refCount = 1;
11830                   };
11831                   e.exp.destType = destType;
11832                   */
11833
11834                   ProcessExpressionType(exp);
11835                }
11836                if(!exp.next)
11837                   curSwitchType = exp.expType;
11838             }
11839          }
11840          ProcessStatement(stmt.switchStmt.stmt);
11841          curSwitchType = oldSwitchType;
11842          break;
11843       }
11844       case whileStmt:
11845       {
11846          if(stmt.whileStmt.exp)
11847          {
11848             Expression exp;
11849
11850             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
11851             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
11852             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
11853             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
11854             {
11855                ProcessExpressionType(exp);
11856             }
11857          }
11858          if(stmt.whileStmt.stmt)
11859             ProcessStatement(stmt.whileStmt.stmt);
11860          break;
11861       }
11862       case doWhileStmt:
11863       {
11864          if(stmt.doWhile.exp)
11865          {
11866             Expression exp;
11867
11868             if(stmt.doWhile.exp->last)
11869             {
11870                FreeType(((Expression)stmt.doWhile.exp->last).destType);
11871                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
11872                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
11873             }
11874             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
11875             {
11876                ProcessExpressionType(exp);
11877             }
11878          }
11879          if(stmt.doWhile.stmt)
11880             ProcessStatement(stmt.doWhile.stmt);
11881          break;
11882       }
11883       case forStmt:
11884       {
11885          Expression exp;
11886          if(stmt.forStmt.init)
11887             ProcessStatement(stmt.forStmt.init);
11888
11889          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
11890          {
11891             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
11892             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
11893             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
11894          }
11895
11896          if(stmt.forStmt.check)
11897             ProcessStatement(stmt.forStmt.check);
11898          if(stmt.forStmt.increment)
11899          {
11900             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
11901                ProcessExpressionType(exp);
11902          }
11903
11904          if(stmt.forStmt.stmt)
11905             ProcessStatement(stmt.forStmt.stmt);
11906          break;
11907       }
11908       case forEachStmt:
11909       {
11910          Identifier id = stmt.forEachStmt.id;
11911          OldList * exp = stmt.forEachStmt.exp;
11912          OldList * filter = stmt.forEachStmt.filter;
11913          Statement block = stmt.forEachStmt.stmt;
11914          char iteratorType[1024];
11915          Type source;
11916          Expression e;
11917          bool isBuiltin = exp && exp->last &&
11918             (((Expression)exp->last).type == ExpressionType::arrayExp ||
11919               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
11920          Expression arrayExp;
11921          const char * typeString = null;
11922          int builtinCount = 0;
11923
11924          for(e = exp ? exp->first : null; e; e = e.next)
11925          {
11926             if(!e.next)
11927             {
11928                FreeType(e.destType);
11929                e.destType = ProcessTypeString("Container", false);
11930             }
11931             if(!isBuiltin || e.next)
11932                ProcessExpressionType(e);
11933          }
11934
11935          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
11936          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
11937             eClass_IsDerived(source._class.registered, containerClass)))
11938          {
11939             Class _class = source ? source._class.registered : null;
11940             Symbol symbol;
11941             Expression expIt = null;
11942             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
11943             Class arrayClass = eSystem_FindClass(privateModule, "Array");
11944             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
11945             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
11946             stmt.type = compoundStmt;
11947
11948             stmt.compound.context = Context { };
11949             stmt.compound.context.parent = curContext;
11950             curContext = stmt.compound.context;
11951
11952             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
11953             {
11954                Class mapClass = eSystem_FindClass(privateModule, "Map");
11955                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
11956                isCustomAVLTree = true;
11957                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
11958                   isAVLTree = true;
11959                else */if(eClass_IsDerived(source._class.registered, mapClass))
11960                   isMap = true;
11961             }
11962             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
11963             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
11964             {
11965                Class listClass = eSystem_FindClass(privateModule, "List");
11966                isLinkList = true;
11967                isList = eClass_IsDerived(source._class.registered, listClass);
11968             }
11969
11970             if(isArray)
11971             {
11972                Declarator decl;
11973                OldList * specs = MkList();
11974                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
11975                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
11976                stmt.compound.declarations = MkListOne(
11977                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11978                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11979                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
11980                      MkInitializerAssignment(MkExpBrackets(exp))))));
11981             }
11982             else if(isBuiltin)
11983             {
11984                Type type = null;
11985                char typeStringBuf[1024];
11986
11987                // TODO: Merge this code?
11988                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
11989                if(((Expression)exp->last).type == castExp)
11990                {
11991                   TypeName typeName = ((Expression)exp->last).cast.typeName;
11992                   if(typeName)
11993                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
11994                }
11995
11996                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
11997                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
11998                   arrayExp.destType._class.registered.templateArgs)
11999                {
12000                   Class templateClass = arrayExp.destType._class.registered;
12001                   typeString = templateClass.templateArgs[2].dataTypeString;
12002                }
12003                else if(arrayExp.list)
12004                {
12005                   // Guess type from expressions in the array
12006                   Expression e;
12007                   for(e = arrayExp.list->first; e; e = e.next)
12008                   {
12009                      ProcessExpressionType(e);
12010                      if(e.expType)
12011                      {
12012                         if(!type) { type = e.expType; type.refCount++; }
12013                         else
12014                         {
12015                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12016                            if(!MatchTypeExpression(e, type, null, false, true))
12017                            {
12018                               FreeType(type);
12019                               type = e.expType;
12020                               e.expType = null;
12021
12022                               e = arrayExp.list->first;
12023                               ProcessExpressionType(e);
12024                               if(e.expType)
12025                               {
12026                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12027                                  if(!MatchTypeExpression(e, type, null, false, true))
12028                                  {
12029                                     FreeType(e.expType);
12030                                     e.expType = null;
12031                                     FreeType(type);
12032                                     type = null;
12033                                     break;
12034                                  }
12035                               }
12036                            }
12037                         }
12038                         if(e.expType)
12039                         {
12040                            FreeType(e.expType);
12041                            e.expType = null;
12042                         }
12043                      }
12044                   }
12045                   if(type)
12046                   {
12047                      typeStringBuf[0] = '\0';
12048                      PrintType(type, typeStringBuf, false, true);
12049                      typeString = typeStringBuf;
12050                      FreeType(type);
12051                   }
12052                }
12053                if(typeString)
12054                {
12055                   OldList * initializers = MkList();
12056                   Declarator decl;
12057                   OldList * specs = MkList();
12058                   if(arrayExp.list)
12059                   {
12060                      Expression e;
12061
12062                      builtinCount = arrayExp.list->count;
12063                      type = ProcessTypeString(typeString, false);
12064                      while((e = arrayExp.list->first))
12065                      {
12066                         arrayExp.list->Remove(e);
12067                         e.destType = type;
12068                         type.refCount++;
12069                         ProcessExpressionType(e);
12070                         ListAdd(initializers, MkInitializerAssignment(e));
12071                      }
12072                      FreeType(type);
12073                      delete arrayExp.list;
12074                   }
12075                   decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12076                   stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12077                      MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12078
12079                   ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12080                      PlugDeclarator(
12081                         /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12082                         ), MkInitializerList(initializers)))));
12083                   FreeList(exp, FreeExpression);
12084                }
12085                else
12086                {
12087                   arrayExp.expType = ProcessTypeString("Container", false);
12088                   Compiler_Error($"Couldn't determine type of array elements\n");
12089                }
12090
12091                /*
12092                Declarator decl;
12093                OldList * specs = MkList();
12094
12095                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12096                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12097                stmt.compound.declarations = MkListOne(
12098                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12099                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12100                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12101                      MkInitializerAssignment(MkExpBrackets(exp))))));
12102                */
12103             }
12104             else if(isLinkList && !isList)
12105             {
12106                Declarator decl;
12107                OldList * specs = MkList();
12108                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12109                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12110                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12111                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12112                      MkInitializerAssignment(MkExpBrackets(exp))))));
12113             }
12114             /*else if(isCustomAVLTree)
12115             {
12116                Declarator decl;
12117                OldList * specs = MkList();
12118                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12119                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12120                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12121                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12122                      MkInitializerAssignment(MkExpBrackets(exp))))));
12123             }*/
12124             else if(_class.templateArgs)
12125             {
12126                if(isMap)
12127                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12128                else
12129                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12130
12131                stmt.compound.declarations = MkListOne(
12132                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12133                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12134                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12135             }
12136             symbol = FindSymbol(id.string, curContext, curContext, false, false);
12137
12138             if(block)
12139             {
12140                // Reparent sub-contexts in this statement
12141                switch(block.type)
12142                {
12143                   case compoundStmt:
12144                      if(block.compound.context)
12145                         block.compound.context.parent = stmt.compound.context;
12146                      break;
12147                   case ifStmt:
12148                      if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12149                         block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12150                      if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12151                         block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12152                      break;
12153                   case switchStmt:
12154                      if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12155                         block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12156                      break;
12157                   case whileStmt:
12158                      if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12159                         block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12160                      break;
12161                   case doWhileStmt:
12162                      if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12163                         block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12164                      break;
12165                   case forStmt:
12166                      if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12167                         block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12168                      break;
12169                   case forEachStmt:
12170                      if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12171                         block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12172                      break;
12173                   /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12174                   case labeledStmt:
12175                   case caseStmt
12176                   case expressionStmt:
12177                   case gotoStmt:
12178                   case continueStmt:
12179                   case breakStmt
12180                   case returnStmt:
12181                   case asmStmt:
12182                   case badDeclarationStmt:
12183                   case fireWatchersStmt:
12184                   case stopWatchingStmt:
12185                   case watchStmt:
12186                   */
12187                }
12188             }
12189             if(filter)
12190             {
12191                block = MkIfStmt(filter, block, null);
12192             }
12193             if(isArray)
12194             {
12195                stmt.compound.statements = MkListOne(MkForStmt(
12196                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12197                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12198                      MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12199                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12200                   block));
12201               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12202               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12203               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12204             }
12205             else if(isBuiltin)
12206             {
12207                char count[128];
12208                //OldList * specs = MkList();
12209                // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12210
12211                sprintf(count, "%d", builtinCount);
12212
12213                stmt.compound.statements = MkListOne(MkForStmt(
12214                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12215                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12216                      MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12217                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12218                   block));
12219
12220                /*
12221                Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12222                stmt.compound.statements = MkListOne(MkForStmt(
12223                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12224                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12225                      MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12226                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12227                   block));
12228               */
12229               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12230               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12231               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12232             }
12233             else if(isLinkList && !isList)
12234             {
12235                Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12236                Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12237                if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12238                   !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12239                {
12240                   stmt.compound.statements = MkListOne(MkForStmt(
12241                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12242                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12243                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12244                      block));
12245                }
12246                else
12247                {
12248                   OldList * specs = MkList();
12249                   Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12250                   stmt.compound.statements = MkListOne(MkForStmt(
12251                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12252                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12253                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12254                         MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12255                            MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12256                      block));
12257                }
12258                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12259                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12260                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12261             }
12262             /*else if(isCustomAVLTree)
12263             {
12264                stmt.compound.statements = MkListOne(MkForStmt(
12265                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12266                      MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12267                   MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12268                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12269                   block));
12270
12271                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12272                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12273                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12274             }*/
12275             else
12276             {
12277                stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12278                   MkIdentifier("Next")), null)), block));
12279             }
12280             ProcessExpressionType(expIt);
12281             if(stmt.compound.declarations->first)
12282                ProcessDeclaration(stmt.compound.declarations->first);
12283
12284             if(symbol)
12285                symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12286
12287             ProcessStatement(stmt);
12288             curContext = stmt.compound.context.parent;
12289             break;
12290          }
12291          else
12292          {
12293             Compiler_Error($"Expression is not a container\n");
12294          }
12295          break;
12296       }
12297       case gotoStmt:
12298          break;
12299       case continueStmt:
12300          break;
12301       case breakStmt:
12302          break;
12303       case returnStmt:
12304       {
12305          Expression exp;
12306          if(stmt.expressions)
12307          {
12308             for(exp = stmt.expressions->first; exp; exp = exp.next)
12309             {
12310                if(!exp.next)
12311                {
12312                   if(curFunction && !curFunction.type)
12313                      curFunction.type = ProcessType(
12314                         curFunction.specifiers, curFunction.declarator);
12315                   FreeType(exp.destType);
12316                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12317                   if(exp.destType) exp.destType.refCount++;
12318                }
12319                ProcessExpressionType(exp);
12320             }
12321          }
12322          break;
12323       }
12324       case badDeclarationStmt:
12325       {
12326          ProcessDeclaration(stmt.decl);
12327          break;
12328       }
12329       case asmStmt:
12330       {
12331          AsmField field;
12332          if(stmt.asmStmt.inputFields)
12333          {
12334             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12335                if(field.expression)
12336                   ProcessExpressionType(field.expression);
12337          }
12338          if(stmt.asmStmt.outputFields)
12339          {
12340             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12341                if(field.expression)
12342                   ProcessExpressionType(field.expression);
12343          }
12344          if(stmt.asmStmt.clobberedFields)
12345          {
12346             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12347             {
12348                if(field.expression)
12349                   ProcessExpressionType(field.expression);
12350             }
12351          }
12352          break;
12353       }
12354       case watchStmt:
12355       {
12356          PropertyWatch propWatch;
12357          OldList * watches = stmt._watch.watches;
12358          Expression object = stmt._watch.object;
12359          Expression watcher = stmt._watch.watcher;
12360          if(watcher)
12361             ProcessExpressionType(watcher);
12362          if(object)
12363             ProcessExpressionType(object);
12364
12365          if(inCompiler)
12366          {
12367             if(watcher || thisClass)
12368             {
12369                External external = curExternal;
12370                Context context = curContext;
12371
12372                stmt.type = expressionStmt;
12373                stmt.expressions = MkList();
12374
12375                curExternal = external.prev;
12376
12377                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12378                {
12379                   ClassFunction func;
12380                   char watcherName[1024];
12381                   Class watcherClass = watcher ?
12382                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12383                   External createdExternal;
12384
12385                   // Create a declaration above
12386                   External externalDecl = MkExternalDeclaration(null);
12387                   ast->Insert(curExternal.prev, externalDecl);
12388
12389                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12390                   if(propWatch.deleteWatch)
12391                      strcat(watcherName, "_delete");
12392                   else
12393                   {
12394                      Identifier propID;
12395                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12396                      {
12397                         strcat(watcherName, "_");
12398                         strcat(watcherName, propID.string);
12399                      }
12400                   }
12401
12402                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12403                   {
12404                      // TESTING THIS STUFF... BEWARE OF SYMBOL ID ISSUES
12405                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12406                         //MkListOne(MkTypeName(MkListOne(MkSpecifier(VOID)), null))), null);
12407                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12408                      ProcessClassFunctionBody(func, propWatch.compound);
12409                      propWatch.compound = null;
12410
12411                      //afterExternal = afterExternal ? afterExternal : curExternal;
12412
12413                      //createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal.prev);
12414                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12415                      // TESTING THIS...
12416                      createdExternal.symbol.idCode = external.symbol.idCode;
12417
12418                      curExternal = createdExternal;
12419                      ProcessFunction(createdExternal.function);
12420
12421
12422                      // Create a declaration above
12423                      {
12424                         Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
12425                            MkListOne(MkInitDeclarator(CopyDeclarator(createdExternal.function.declarator), null)));
12426                         externalDecl.declaration = decl;
12427                         if(decl.symbol && !decl.symbol.pointerExternal)
12428                            decl.symbol.pointerExternal = externalDecl;
12429                      }
12430
12431                      if(propWatch.deleteWatch)
12432                      {
12433                         OldList * args = MkList();
12434                         ListAdd(args, CopyExpression(object));
12435                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12436                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12437                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12438                      }
12439                      else
12440                      {
12441                         Class _class = object.expType._class.registered;
12442                         Identifier propID;
12443
12444                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12445                         {
12446                            char propName[1024];
12447                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12448                            if(prop)
12449                            {
12450                               char getName[1024], setName[1024];
12451                               OldList * args = MkList();
12452
12453                               DeclareProperty(prop, setName, getName);
12454
12455                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12456                               strcpy(propName, "__ecereProp_");
12457                               FullClassNameCat(propName, prop._class.fullName, false);
12458                               strcat(propName, "_");
12459                               // strcat(propName, prop.name);
12460                               FullClassNameCat(propName, prop.name, true);
12461
12462                               ListAdd(args, CopyExpression(object));
12463                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12464                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12465                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12466
12467                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12468                            }
12469                            else
12470                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12471                         }
12472                      }
12473                   }
12474                   else
12475                      Compiler_Error($"Invalid watched object\n");
12476                }
12477
12478                curExternal = external;
12479                curContext = context;
12480
12481                if(watcher)
12482                   FreeExpression(watcher);
12483                if(object)
12484                   FreeExpression(object);
12485                FreeList(watches, FreePropertyWatch);
12486             }
12487             else
12488                Compiler_Error($"No observer specified and not inside a _class\n");
12489          }
12490          else
12491          {
12492             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12493             {
12494                ProcessStatement(propWatch.compound);
12495             }
12496
12497          }
12498          break;
12499       }
12500       case fireWatchersStmt:
12501       {
12502          OldList * watches = stmt._watch.watches;
12503          Expression object = stmt._watch.object;
12504          Class _class;
12505          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12506          // printf("%X\n", watches);
12507          // printf("%X\n", stmt._watch.watches);
12508          if(object)
12509             ProcessExpressionType(object);
12510
12511          if(inCompiler)
12512          {
12513             _class = object ?
12514                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12515
12516             if(_class)
12517             {
12518                Identifier propID;
12519
12520                stmt.type = expressionStmt;
12521                stmt.expressions = MkList();
12522
12523                // Check if we're inside a property set
12524                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12525                {
12526                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12527                }
12528                else if(!watches)
12529                {
12530                   //Compiler_Error($"No property specified and not inside a property set\n");
12531                }
12532                if(watches)
12533                {
12534                   for(propID = watches->first; propID; propID = propID.next)
12535                   {
12536                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12537                      if(prop)
12538                      {
12539                         CreateFireWatcher(prop, object, stmt);
12540                      }
12541                      else
12542                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12543                   }
12544                }
12545                else
12546                {
12547                   // Fire all properties!
12548                   Property prop;
12549                   Class base;
12550                   for(base = _class; base; base = base.base)
12551                   {
12552                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12553                      {
12554                         if(prop.isProperty && prop.isWatchable)
12555                         {
12556                            CreateFireWatcher(prop, object, stmt);
12557                         }
12558                      }
12559                   }
12560                }
12561
12562                if(object)
12563                   FreeExpression(object);
12564                FreeList(watches, FreeIdentifier);
12565             }
12566             else
12567                Compiler_Error($"Invalid object specified and not inside a class\n");
12568          }
12569          break;
12570       }
12571       case stopWatchingStmt:
12572       {
12573          OldList * watches = stmt._watch.watches;
12574          Expression object = stmt._watch.object;
12575          Expression watcher = stmt._watch.watcher;
12576          Class _class;
12577          if(object)
12578             ProcessExpressionType(object);
12579          if(watcher)
12580             ProcessExpressionType(watcher);
12581          if(inCompiler)
12582          {
12583             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12584
12585             if(watcher || thisClass)
12586             {
12587                if(_class)
12588                {
12589                   Identifier propID;
12590
12591                   stmt.type = expressionStmt;
12592                   stmt.expressions = MkList();
12593
12594                   if(!watches)
12595                   {
12596                      OldList * args;
12597                      // eInstance_StopWatching(object, null, watcher);
12598                      args = MkList();
12599                      ListAdd(args, CopyExpression(object));
12600                      ListAdd(args, MkExpConstant("0"));
12601                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12602                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12603                   }
12604                   else
12605                   {
12606                      for(propID = watches->first; propID; propID = propID.next)
12607                      {
12608                         char propName[1024];
12609                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12610                         if(prop)
12611                         {
12612                            char getName[1024], setName[1024];
12613                            OldList * args = MkList();
12614
12615                            DeclareProperty(prop, setName, getName);
12616
12617                            // eInstance_StopWatching(object, prop, watcher);
12618                            strcpy(propName, "__ecereProp_");
12619                            FullClassNameCat(propName, prop._class.fullName, false);
12620                            strcat(propName, "_");
12621                            // strcat(propName, prop.name);
12622                            FullClassNameCat(propName, prop.name, true);
12623                            //MangleClassName(propName);
12624
12625                            ListAdd(args, CopyExpression(object));
12626                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12627                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12628                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12629                         }
12630                         else
12631                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12632                      }
12633                   }
12634
12635                   if(object)
12636                      FreeExpression(object);
12637                   if(watcher)
12638                      FreeExpression(watcher);
12639                   FreeList(watches, FreeIdentifier);
12640                }
12641                else
12642                   Compiler_Error($"Invalid object specified and not inside a class\n");
12643             }
12644             else
12645                Compiler_Error($"No observer specified and not inside a class\n");
12646          }
12647          break;
12648       }
12649    }
12650 }
12651
12652 static void ProcessFunction(FunctionDefinition function)
12653 {
12654    Identifier id = GetDeclId(function.declarator);
12655    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12656    Type type = symbol ? symbol.type : null;
12657    Class oldThisClass = thisClass;
12658    Context oldTopContext = topContext;
12659
12660    yylloc = function.loc;
12661    // Process thisClass
12662
12663    if(type && type.thisClass)
12664    {
12665       Symbol classSym = type.thisClass;
12666       Class _class = type.thisClass.registered;
12667       char className[1024];
12668       char structName[1024];
12669       Declarator funcDecl;
12670       Symbol thisSymbol;
12671
12672       bool typedObject = false;
12673
12674       if(_class && !_class.base)
12675       {
12676          _class = currentClass;
12677          if(_class && !_class.symbol)
12678             _class.symbol = FindClass(_class.fullName);
12679          classSym = _class ? _class.symbol : null;
12680          typedObject = true;
12681       }
12682
12683       thisClass = _class;
12684
12685       if(inCompiler && _class)
12686       {
12687          if(type.kind == functionType)
12688          {
12689             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12690             {
12691                //TypeName param = symbol.type.params.first;
12692                Type param = symbol.type.params.first;
12693                symbol.type.params.Remove(param);
12694                //FreeTypeName(param);
12695                FreeType(param);
12696             }
12697             if(type.classObjectType != classPointer)
12698             {
12699                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12700                symbol.type.staticMethod = true;
12701                symbol.type.thisClass = null;
12702
12703                // HIGH DANGER: VERIFYING THIS...
12704                symbol.type.extraParam = false;
12705             }
12706          }
12707
12708          strcpy(className, "__ecereClass_");
12709          FullClassNameCat(className, _class.fullName, true);
12710
12711          //MangleClassName(className);
12712
12713          structName[0] = 0;
12714          FullClassNameCat(structName, _class.fullName, false);
12715
12716          // [class] this
12717
12718
12719          funcDecl = GetFuncDecl(function.declarator);
12720          if(funcDecl)
12721          {
12722             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12723             {
12724                TypeName param = funcDecl.function.parameters->first;
12725                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12726                {
12727                   funcDecl.function.parameters->Remove(param);
12728                   FreeTypeName(param);
12729                }
12730             }
12731
12732             // DANGER: Watch for this... Check if it's a Conversion?
12733             // if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12734
12735             // WAS TRYING THIS FOR CONVERSION PROPERTIES ON NOHEAD CLASSES: if((_class.type == structClass) || function != (FunctionDefinition)symbol.externalSet)
12736             if(!function.propertyNoThis)
12737             {
12738                TypeName thisParam = null;
12739
12740                if(type.classObjectType != classPointer)
12741                {
12742                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12743                   if(!funcDecl.function.parameters)
12744                      funcDecl.function.parameters = MkList();
12745                   funcDecl.function.parameters->Insert(null, thisParam);
12746                }
12747
12748                if(typedObject)
12749                {
12750                   if(type.classObjectType != classPointer)
12751                   {
12752                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
12753                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
12754                   }
12755
12756                   thisParam = TypeName
12757                   {
12758                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
12759                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
12760                   };
12761                   funcDecl.function.parameters->Insert(null, thisParam);
12762                }
12763             }
12764          }
12765
12766          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12767          {
12768             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12769             funcDecl = GetFuncDecl(initDecl.declarator);
12770             if(funcDecl)
12771             {
12772                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12773                {
12774                   TypeName param = funcDecl.function.parameters->first;
12775                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12776                   {
12777                      funcDecl.function.parameters->Remove(param);
12778                      FreeTypeName(param);
12779                   }
12780                }
12781
12782                if(type.classObjectType != classPointer)
12783                {
12784                   // DANGER: Watch for this... Check if it's a Conversion?
12785                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12786                   {
12787                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12788
12789                      if(!funcDecl.function.parameters)
12790                         funcDecl.function.parameters = MkList();
12791                      funcDecl.function.parameters->Insert(null, thisParam);
12792                   }
12793                }
12794             }
12795          }
12796       }
12797
12798       // Add this to the context
12799       if(function.body)
12800       {
12801          if(type.classObjectType != classPointer)
12802          {
12803             thisSymbol = Symbol
12804             {
12805                string = CopyString("this");
12806                type = classSym ? MkClassType(classSym.string) : null; //_class.fullName);
12807             };
12808             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
12809
12810             if(typedObject && thisSymbol.type)
12811             {
12812                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
12813                thisSymbol.type.byReference = type.byReference;
12814                thisSymbol.type.typedByReference = type.byReference;
12815                /*
12816                thisSymbol = Symbol { string = CopyString("class") };
12817                function.body.compound.context.symbols.Add(thisSymbol);
12818                */
12819             }
12820          }
12821       }
12822
12823       // Pointer to class data
12824
12825       if(inCompiler && _class && (_class.type == normalClass /*|| _class.type == noHeadClass*/) && type.classObjectType != classPointer)
12826       {
12827          DataMember member = null;
12828          {
12829             Class base;
12830             for(base = _class; base && base.type != systemClass; base = base.next)
12831             {
12832                for(member = base.membersAndProperties.first; member; member = member.next)
12833                   if(!member.isProperty)
12834                      break;
12835                if(member)
12836                   break;
12837             }
12838          }
12839          for(member = _class.membersAndProperties.first; member; member = member.next)
12840             if(!member.isProperty)
12841                break;
12842          if(member)
12843          {
12844             char pointerName[1024];
12845
12846             Declaration decl;
12847             Initializer initializer;
12848             Expression exp, bytePtr;
12849
12850             strcpy(pointerName, "__ecerePointer_");
12851             FullClassNameCat(pointerName, _class.fullName, false);
12852             {
12853                char className[1024];
12854                strcpy(className, "__ecereClass_");
12855                FullClassNameCat(className, classSym.string, true);
12856                //MangleClassName(className);
12857
12858                // Testing This
12859                DeclareClass(classSym, className);
12860             }
12861
12862             // ((byte *) this)
12863             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
12864
12865             if(_class.fixed)
12866             {
12867                char string[256];
12868                sprintf(string, "%d", _class.offset);
12869                exp = QBrackets(MkExpOp(bytePtr, '+', MkExpConstant(string)));
12870             }
12871             else
12872             {
12873                // ([bytePtr] + [className]->offset)
12874                exp = QBrackets(MkExpOp(bytePtr, '+',
12875                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
12876             }
12877
12878             // (this ? [exp] : 0)
12879             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
12880             exp.expType = Type
12881             {
12882                refCount = 1;
12883                kind = pointerType;
12884                type = Type { refCount = 1, kind = voidType };
12885             };
12886
12887             if(function.body)
12888             {
12889                yylloc = function.body.loc;
12890                // ([structName] *) [exp]
12891                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
12892                initializer = MkInitializerAssignment(
12893                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
12894
12895                // [structName] * [pointerName] = [initializer];
12896                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
12897
12898                {
12899                   Context prevContext = curContext;
12900                   OldList * list;
12901                   curContext = function.body.compound.context;
12902
12903                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
12904                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
12905                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
12906
12907                   curContext = prevContext;
12908                }
12909
12910                // WHY?
12911                decl.symbol = null;
12912
12913                if(!function.body.compound.declarations)
12914                   function.body.compound.declarations = MkList();
12915                function.body.compound.declarations->Insert(null, decl);
12916             }
12917          }
12918       }
12919
12920
12921       // Loop through the function and replace undeclared identifiers
12922       // which are a member of the class (methods, properties or data)
12923       // by "this.[member]"
12924    }
12925    else
12926       thisClass = null;
12927
12928    if(id)
12929    {
12930       FreeSpecifier(id._class);
12931       id._class = null;
12932
12933       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12934       {
12935          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12936          id = GetDeclId(initDecl.declarator);
12937
12938          FreeSpecifier(id._class);
12939          id._class = null;
12940       }
12941    }
12942    if(function.body)
12943       topContext = function.body.compound.context;
12944    {
12945       FunctionDefinition oldFunction = curFunction;
12946       curFunction = function;
12947       if(function.body)
12948          ProcessStatement(function.body);
12949
12950       // If this is a property set and no firewatchers has been done yet, add one here
12951       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
12952       {
12953          Statement prevCompound = curCompound;
12954          Context prevContext = curContext;
12955
12956          Statement fireWatchers = MkFireWatchersStmt(null, null);
12957          if(!function.body.compound.statements) function.body.compound.statements = MkList();
12958          ListAdd(function.body.compound.statements, fireWatchers);
12959
12960          curCompound = function.body;
12961          curContext = function.body.compound.context;
12962
12963          ProcessStatement(fireWatchers);
12964
12965          curContext = prevContext;
12966          curCompound = prevCompound;
12967
12968       }
12969
12970       curFunction = oldFunction;
12971    }
12972
12973    if(function.declarator)
12974    {
12975       ProcessDeclarator(function.declarator);
12976    }
12977
12978    topContext = oldTopContext;
12979    thisClass = oldThisClass;
12980 }
12981
12982 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
12983 static void ProcessClass(OldList definitions, Symbol symbol)
12984 {
12985    ClassDef def;
12986    External external = curExternal;
12987    Class regClass = symbol ? symbol.registered : null;
12988
12989    // Process all functions
12990    for(def = definitions.first; def; def = def.next)
12991    {
12992       if(def.type == functionClassDef)
12993       {
12994          if(def.function.declarator)
12995             curExternal = def.function.declarator.symbol.pointerExternal;
12996          else
12997             curExternal = external;
12998
12999          ProcessFunction((FunctionDefinition)def.function);
13000       }
13001       else if(def.type == declarationClassDef)
13002       {
13003          if(def.decl.type == instDeclaration)
13004          {
13005             thisClass = regClass;
13006             ProcessInstantiationType(def.decl.inst);
13007             thisClass = null;
13008          }
13009          // Testing this
13010          else
13011          {
13012             Class backThisClass = thisClass;
13013             if(regClass) thisClass = regClass;
13014             ProcessDeclaration(def.decl);
13015             thisClass = backThisClass;
13016          }
13017       }
13018       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13019       {
13020          MemberInit defProperty;
13021
13022          // Add this to the context
13023          Symbol thisSymbol = Symbol
13024          {
13025             string = CopyString("this");
13026             type = regClass ? MkClassType(regClass.fullName) : null;
13027          };
13028          globalContext.symbols.Add((BTNode)thisSymbol);
13029
13030          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13031          {
13032             thisClass = regClass;
13033             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13034             thisClass = null;
13035          }
13036
13037          globalContext.symbols.Remove((BTNode)thisSymbol);
13038          FreeSymbol(thisSymbol);
13039       }
13040       else if(def.type == propertyClassDef && def.propertyDef)
13041       {
13042          PropertyDef prop = def.propertyDef;
13043
13044          // Add this to the context
13045          /*
13046          Symbol thisSymbol = Symbol { string = CopyString("this"), type = MkClassType(regClass.fullName) };
13047          globalContext.symbols.Add(thisSymbol);
13048          */
13049
13050          thisClass = regClass;
13051          if(prop.setStmt)
13052          {
13053             if(regClass)
13054             {
13055                Symbol thisSymbol
13056                {
13057                   string = CopyString("this");
13058                   type = MkClassType(regClass.fullName);
13059                };
13060                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13061             }
13062
13063             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13064             ProcessStatement(prop.setStmt);
13065          }
13066          if(prop.getStmt)
13067          {
13068             if(regClass)
13069             {
13070                Symbol thisSymbol
13071                {
13072                   string = CopyString("this");
13073                   type = MkClassType(regClass.fullName);
13074                };
13075                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13076             }
13077
13078             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13079             ProcessStatement(prop.getStmt);
13080          }
13081          if(prop.issetStmt)
13082          {
13083             if(regClass)
13084             {
13085                Symbol thisSymbol
13086                {
13087                   string = CopyString("this");
13088                   type = MkClassType(regClass.fullName);
13089                };
13090                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13091             }
13092
13093             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13094             ProcessStatement(prop.issetStmt);
13095          }
13096
13097          thisClass = null;
13098
13099          /*
13100          globalContext.symbols.Remove(thisSymbol);
13101          FreeSymbol(thisSymbol);
13102          */
13103       }
13104       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13105       {
13106          PropertyWatch propertyWatch = def.propertyWatch;
13107
13108          thisClass = regClass;
13109          if(propertyWatch.compound)
13110          {
13111             Symbol thisSymbol
13112             {
13113                string = CopyString("this");
13114                type = regClass ? MkClassType(regClass.fullName) : null;
13115             };
13116
13117             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13118
13119             curExternal = null;
13120             ProcessStatement(propertyWatch.compound);
13121          }
13122          thisClass = null;
13123       }
13124    }
13125 }
13126
13127 void DeclareFunctionUtil(const String s)
13128 {
13129    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13130    if(function)
13131    {
13132       char name[1024];
13133       name[0] = 0;
13134       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13135          strcpy(name, "__ecereFunction_");
13136       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13137       DeclareFunction(function, name);
13138    }
13139 }
13140
13141 void ComputeDataTypes()
13142 {
13143    External external;
13144    External temp { };
13145    External after = null;
13146
13147    currentClass = null;
13148
13149    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13150
13151    for(external = ast->first; external; external = external.next)
13152    {
13153       if(external.type == declarationExternal)
13154       {
13155          Declaration decl = external.declaration;
13156          if(decl)
13157          {
13158             OldList * decls = decl.declarators;
13159             if(decls)
13160             {
13161                InitDeclarator initDecl = decls->first;
13162                if(initDecl)
13163                {
13164                   Declarator declarator = initDecl.declarator;
13165                   if(declarator && declarator.type == identifierDeclarator)
13166                   {
13167                      Identifier id = declarator.identifier;
13168                      if(id && id.string)
13169                      {
13170                         if(!strcmp(id.string, "uintptr_t") || !strcmp(id.string, "intptr_t") || !strcmp(id.string, "size_t") || !strcmp(id.string, "ssize_t"))
13171                         {
13172                            external.symbol.id = -1001, external.symbol.idCode = -1001;
13173                            after = external;
13174                         }
13175                      }
13176                   }
13177                }
13178             }
13179          }
13180        }
13181    }
13182
13183    {
13184       // Workaround until we have proper toposort for declarations reordering
13185       External e = MkExternalDeclaration(MkDeclaration(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Instance"), null)), null));
13186       ast->Insert(after, e);
13187       after = e;
13188    }
13189
13190    temp.symbol = Symbol { id = -1000, idCode = -1000 };
13191    ast->Insert(after, temp);
13192    curExternal = temp;
13193
13194    DeclareFunctionUtil("eSystem_New");
13195    DeclareFunctionUtil("eSystem_New0");
13196    DeclareFunctionUtil("eSystem_Renew");
13197    DeclareFunctionUtil("eSystem_Renew0");
13198    DeclareFunctionUtil("eSystem_Delete");
13199    DeclareFunctionUtil("eClass_GetProperty");
13200    DeclareFunctionUtil("eClass_SetProperty");
13201    DeclareFunctionUtil("eInstance_FireSelfWatchers");
13202    DeclareFunctionUtil("eInstance_SetMethod");
13203    DeclareFunctionUtil("eInstance_IncRef");
13204    DeclareFunctionUtil("eInstance_StopWatching");
13205    DeclareFunctionUtil("eInstance_Watch");
13206    DeclareFunctionUtil("eInstance_FireWatchers");
13207
13208    DeclareStruct("ecere::com::Class", false);
13209    DeclareStruct("ecere::com::Instance", false);
13210    DeclareStruct("ecere::com::Property", false);
13211    DeclareStruct("ecere::com::DataMember", false);
13212    DeclareStruct("ecere::com::Method", false);
13213    DeclareStruct("ecere::com::SerialBuffer", false);
13214    DeclareStruct("ecere::com::ClassTemplateArgument", false);
13215
13216    ast->Remove(temp);
13217
13218    for(external = ast->first; external; external = external.next)
13219    {
13220       afterExternal = curExternal = external;
13221       if(external.type == functionExternal)
13222       {
13223          currentClass = external.function._class;
13224          ProcessFunction(external.function);
13225       }
13226       // There shouldn't be any _class member access here anyways...
13227       else if(external.type == declarationExternal)
13228       {
13229          currentClass = null;
13230          if(external.declaration)
13231             ProcessDeclaration(external.declaration);
13232       }
13233       else if(external.type == classExternal)
13234       {
13235          ClassDefinition _class = external._class;
13236          currentClass = external.symbol.registered;
13237          if(_class.definitions)
13238          {
13239             ProcessClass(_class.definitions, _class.symbol);
13240          }
13241          if(inCompiler)
13242          {
13243             // Free class data...
13244             ast->Remove(external);
13245             delete external;
13246          }
13247       }
13248       else if(external.type == nameSpaceExternal)
13249       {
13250          thisNameSpace = external.id.string;
13251       }
13252    }
13253    currentClass = null;
13254    thisNameSpace = null;
13255    curExternal = null;
13256
13257    delete temp.symbol;
13258    delete temp;
13259 }