compiler/libec; ecere: Support for checking platform as a compile time constant
[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             specifiers->Insert(null, MkSpecifier(STATIC));
1580
1581          ListAdd(specifiers, MkSpecifierName("Property"));
1582
1583          strcpy(propName, "__ecereProp_");
1584          FullClassNameCat(propName, prop._class.fullName, false);
1585          strcat(propName, "_");
1586          FullClassNameCat(propName, prop.name, true);
1587          // strcat(propName, prop.name);
1588          //MangleClassName(propName);
1589
1590          {
1591             OldList * list = MkList();
1592             ListAdd(list, MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null),
1593                   MkDeclaratorIdentifier(MkIdentifier(propName))), null));
1594
1595             if(!imported)
1596             {
1597                strcpy(propName, "__ecerePropM_");
1598                FullClassNameCat(propName, prop._class.fullName, false);
1599                strcat(propName, "_");
1600                // strcat(propName, prop.name);
1601                FullClassNameCat(propName, prop.name, true);
1602
1603                //MangleClassName(propName);
1604
1605                ListAdd(list, MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null),
1606                      MkDeclaratorIdentifier(MkIdentifier(propName))), null));
1607             }
1608             decl = MkDeclaration(specifiers, list);
1609          }
1610
1611          external = MkExternalDeclaration(decl);
1612          ast->Insert(curExternal.prev, external);
1613          external.symbol = symbol;
1614          symbol.externalPtr = external;
1615       }
1616       else
1617       {
1618          // Move declaration higher...
1619          ast->Move(symbol.externalPtr, curExternal.prev);
1620       }
1621
1622       symbol.id = curExternal.symbol.idCode;
1623    }
1624 }
1625
1626 // ***************** EXPRESSION PROCESSING ***************************
1627 public Type Dereference(Type source)
1628 {
1629    Type type = null;
1630    if(source)
1631    {
1632       if(source.kind == pointerType || source.kind == arrayType)
1633       {
1634          type = source.type;
1635          source.type.refCount++;
1636       }
1637       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1638       {
1639          type = Type
1640          {
1641             kind = charType;
1642             refCount = 1;
1643          };
1644       }
1645       // Support dereferencing of no head classes for now...
1646       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1647       {
1648          type = source;
1649          source.refCount++;
1650       }
1651       else
1652          Compiler_Error($"cannot dereference type\n");
1653    }
1654    return type;
1655 }
1656
1657 static Type Reference(Type source)
1658 {
1659    Type type = null;
1660    if(source)
1661    {
1662       type = Type
1663       {
1664          kind = pointerType;
1665          type = source;
1666          refCount = 1;
1667       };
1668       source.refCount++;
1669    }
1670    return type;
1671 }
1672
1673 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1674 {
1675    Identifier ident = member.identifiers ? member.identifiers->first : null;
1676    bool found = false;
1677    DataMember dataMember = null;
1678    Method method = null;
1679    bool freeType = false;
1680
1681    yylloc = member.loc;
1682
1683    if(!ident)
1684    {
1685       if(curMember)
1686       {
1687          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1688          if(*curMember)
1689          {
1690             found = true;
1691             dataMember = *curMember;
1692          }
1693       }
1694    }
1695    else
1696    {
1697       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1698       DataMember _subMemberStack[256];
1699       int _subMemberStackPos = 0;
1700
1701       // FILL MEMBER STACK
1702       if(!thisMember)
1703          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1704       if(thisMember)
1705       {
1706          dataMember = thisMember;
1707          if(curMember && thisMember.memberAccess == publicAccess)
1708          {
1709             *curMember = thisMember;
1710             *curClass = thisMember._class;
1711             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1712             *subMemberStackPos = _subMemberStackPos;
1713          }
1714          found = true;
1715       }
1716       else
1717       {
1718          // Setting a method
1719          method = eClass_FindMethod(_class, ident.string, privateModule);
1720          if(method && method.type == virtualMethod)
1721             found = true;
1722          else
1723             method = null;
1724       }
1725    }
1726
1727    if(found)
1728    {
1729       Type type = null;
1730       if(dataMember)
1731       {
1732          if(!dataMember.dataType && dataMember.dataTypeString)
1733          {
1734             //Context context = SetupTemplatesContext(dataMember._class);
1735             Context context = SetupTemplatesContext(_class);
1736             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1737             FinishTemplatesContext(context);
1738          }
1739          type = dataMember.dataType;
1740       }
1741       else if(method)
1742       {
1743          // This is for destination type...
1744          if(!method.dataType)
1745             ProcessMethodType(method);
1746          //DeclareMethod(method);
1747          // method.dataType = ((Symbol)method.symbol)->type;
1748          type = method.dataType;
1749       }
1750
1751       if(ident && ident.next)
1752       {
1753          for(ident = ident.next; ident && type; ident = ident.next)
1754          {
1755             if(type.kind == classType)
1756             {
1757                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1758                if(!dataMember)
1759                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1760                if(dataMember)
1761                   type = dataMember.dataType;
1762             }
1763             else if(type.kind == structType || type.kind == unionType)
1764             {
1765                Type memberType;
1766                for(memberType = type.members.first; memberType; memberType = memberType.next)
1767                {
1768                   if(!strcmp(memberType.name, ident.string))
1769                   {
1770                      type = memberType;
1771                      break;
1772                   }
1773                }
1774             }
1775          }
1776       }
1777
1778       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1779       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1780       {
1781          int id = 0;
1782          ClassTemplateParameter curParam = null;
1783          Class sClass;
1784          for(sClass = _class; sClass; sClass = sClass.base)
1785          {
1786             id = 0;
1787             if(sClass.templateClass) sClass = sClass.templateClass;
1788             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1789             {
1790                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1791                {
1792                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1793                   {
1794                      if(sClass.templateClass) sClass = sClass.templateClass;
1795                      id += sClass.templateParams.count;
1796                   }
1797                   break;
1798                }
1799                id++;
1800             }
1801             if(curParam) break;
1802          }
1803
1804          if(curParam)
1805          {
1806             ClassTemplateArgument arg = _class.templateArgs[id];
1807             if(arg.dataTypeString)
1808             {
1809                bool constant = type.constant;
1810                // FreeType(type);
1811                type = ProcessTypeString(arg.dataTypeString, false);
1812                if(type.kind == classType && constant) type.constant = true;
1813                else if(type.kind == pointerType)
1814                {
1815                   Type t = type.type;
1816                   while(t.kind == pointerType) t = t.type;
1817                   if(constant) t.constant = constant;
1818                }
1819                freeType = true;
1820                if(type && _class.templateClass)
1821                   type.passAsTemplate = true;
1822                if(type)
1823                {
1824                   // type.refCount++;
1825                   /*if(!exp.destType)
1826                   {
1827                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1828                      exp.destType.refCount++;
1829                   }*/
1830                }
1831             }
1832          }
1833       }
1834       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1835       {
1836          Class expClass = type._class.registered;
1837          Class cClass = null;
1838          int paramCount = 0;
1839          int lastParam = -1;
1840
1841          char templateString[1024];
1842          ClassTemplateParameter param;
1843          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1844          for(cClass = expClass; cClass; cClass = cClass.base)
1845          {
1846             int p = 0;
1847             if(cClass.templateClass) cClass = cClass.templateClass;
1848             for(param = cClass.templateParams.first; param; param = param.next)
1849             {
1850                int id = p;
1851                Class sClass;
1852                ClassTemplateArgument arg;
1853                for(sClass = cClass.base; sClass; sClass = sClass.base)
1854                {
1855                   if(sClass.templateClass) sClass = sClass.templateClass;
1856                   id += sClass.templateParams.count;
1857                }
1858                arg = expClass.templateArgs[id];
1859
1860                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1861                {
1862                   ClassTemplateParameter cParam;
1863                   //int p = numParams - sClass.templateParams.count;
1864                   int p = 0;
1865                   Class nextClass;
1866                   if(sClass.templateClass) sClass = sClass.templateClass;
1867
1868                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1869                   {
1870                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1871                      p += nextClass.templateParams.count;
1872                   }
1873
1874                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1875                   {
1876                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1877                      {
1878                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1879                         {
1880                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1881                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1882                            break;
1883                         }
1884                      }
1885                   }
1886                }
1887
1888                {
1889                   char argument[256];
1890                   argument[0] = '\0';
1891                   /*if(arg.name)
1892                   {
1893                      strcat(argument, arg.name.string);
1894                      strcat(argument, " = ");
1895                   }*/
1896                   switch(param.type)
1897                   {
1898                      case expression:
1899                      {
1900                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1901                         char expString[1024];
1902                         OldList * specs = MkList();
1903                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1904                         Expression exp;
1905                         char * string = PrintHexUInt64(arg.expression.ui64);
1906                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1907                         delete string;
1908
1909                         ProcessExpressionType(exp);
1910                         ComputeExpression(exp);
1911                         expString[0] = '\0';
1912                         PrintExpression(exp, expString);
1913                         strcat(argument, expString);
1914                         //delete exp;
1915                         FreeExpression(exp);
1916                         break;
1917                      }
1918                      case identifier:
1919                      {
1920                         strcat(argument, arg.member.name);
1921                         break;
1922                      }
1923                      case TemplateParameterType::type:
1924                      {
1925                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1926                            strcat(argument, arg.dataTypeString);
1927                         break;
1928                      }
1929                   }
1930                   if(argument[0])
1931                   {
1932                      if(paramCount) strcat(templateString, ", ");
1933                      if(lastParam != p - 1)
1934                      {
1935                         strcat(templateString, param.name);
1936                         strcat(templateString, " = ");
1937                      }
1938                      strcat(templateString, argument);
1939                      paramCount++;
1940                      lastParam = p;
1941                   }
1942                   p++;
1943                }
1944             }
1945          }
1946          {
1947             int len = strlen(templateString);
1948             if(templateString[len-1] == '<')
1949                len--;
1950             else
1951             {
1952                if(templateString[len-1] == '>')
1953                   templateString[len++] = ' ';
1954                templateString[len++] = '>';
1955             }
1956             templateString[len++] = '\0';
1957          }
1958          {
1959             Context context = SetupTemplatesContext(_class);
1960             if(freeType) FreeType(type);
1961             type = ProcessTypeString(templateString, false);
1962             freeType = true;
1963             FinishTemplatesContext(context);
1964          }
1965       }
1966
1967       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1968       {
1969          ProcessExpressionType(member.initializer.exp);
1970          if(!member.initializer.exp.expType)
1971          {
1972             if(inCompiler)
1973             {
1974                char expString[10240];
1975                expString[0] = '\0';
1976                PrintExpression(member.initializer.exp, expString);
1977                ChangeCh(expString, '\n', ' ');
1978                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1979             }
1980          }
1981          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1982          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
1983          {
1984             Compiler_Error($"incompatible instance method %s\n", ident.string);
1985          }
1986       }
1987       else if(member.initializer)
1988       {
1989          /*
1990          FreeType(member.exp.destType);
1991          member.exp.destType = type;
1992          if(member.exp.destType)
1993             member.exp.destType.refCount++;
1994          ProcessExpressionType(member.exp);
1995          */
1996
1997          ProcessInitializer(member.initializer, type);
1998       }
1999       if(freeType) FreeType(type);
2000    }
2001    else
2002    {
2003       if(_class && _class.type == unitClass)
2004       {
2005          if(member.initializer)
2006          {
2007             /*
2008             FreeType(member.exp.destType);
2009             member.exp.destType = MkClassType(_class.fullName);
2010             ProcessExpressionType(member.initializer, type);
2011             */
2012             Type type = MkClassType(_class.fullName);
2013             ProcessInitializer(member.initializer, type);
2014             FreeType(type);
2015          }
2016       }
2017       else
2018       {
2019          if(member.initializer)
2020          {
2021             //ProcessExpressionType(member.exp);
2022             ProcessInitializer(member.initializer, null);
2023          }
2024          if(ident)
2025          {
2026             if(method)
2027             {
2028                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2029             }
2030             else if(_class)
2031             {
2032                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2033                if(inCompiler)
2034                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2035             }
2036          }
2037          else if(_class)
2038             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2039       }
2040    }
2041 }
2042
2043 void ProcessInstantiationType(Instantiation inst)
2044 {
2045    yylloc = inst.loc;
2046    if(inst._class)
2047    {
2048       MembersInit members;
2049       Symbol classSym; // = inst._class.symbol; // FindClass(inst._class.name);
2050       Class _class;
2051
2052       /*if(!inst._class.symbol)
2053          inst._class.symbol = FindClass(inst._class.name);*/
2054       classSym = inst._class.symbol;
2055       _class = classSym ? classSym.registered : null;
2056
2057       // DANGER: Patch for mutex not declaring its struct when not needed
2058       if(!_class || _class.type != noHeadClass)
2059          DeclareStruct(inst._class.name, false); //_class && _class.type == noHeadClass);
2060
2061       afterExternal = afterExternal ? afterExternal : curExternal;
2062
2063       if(inst.exp)
2064          ProcessExpressionType(inst.exp);
2065
2066       inst.isConstant = true;
2067       if(inst.members)
2068       {
2069          DataMember curMember = null;
2070          Class curClass = null;
2071          DataMember subMemberStack[256];
2072          int subMemberStackPos = 0;
2073
2074          for(members = inst.members->first; members; members = members.next)
2075          {
2076             switch(members.type)
2077             {
2078                case methodMembersInit:
2079                {
2080                   char name[1024];
2081                   static uint instMethodID = 0;
2082                   External external = curExternal;
2083                   Context context = curContext;
2084                   Declarator declarator = members.function.declarator;
2085                   Identifier nameID = GetDeclId(declarator);
2086                   char * unmangled = nameID ? nameID.string : null;
2087                   Expression exp;
2088                   External createdExternal = null;
2089
2090                   if(inCompiler)
2091                   {
2092                      char number[16];
2093                      //members.function.dontMangle = true;
2094                      strcpy(name, "__ecereInstMeth_");
2095                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2096                      strcat(name, "_");
2097                      strcat(name, nameID.string);
2098                      strcat(name, "_");
2099                      sprintf(number, "_%08d", instMethodID++);
2100                      strcat(name, number);
2101                      nameID.string = CopyString(name);
2102                   }
2103
2104                   // Do modifications here...
2105                   if(declarator)
2106                   {
2107                      Symbol symbol = declarator.symbol;
2108                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2109
2110                      if(method && method.type == virtualMethod)
2111                      {
2112                         symbol.method = method;
2113                         ProcessMethodType(method);
2114
2115                         if(!symbol.type.thisClass)
2116                         {
2117                            if(method.dataType.thisClass && currentClass &&
2118                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2119                            {
2120                               if(!currentClass.symbol)
2121                                  currentClass.symbol = FindClass(currentClass.fullName);
2122                               symbol.type.thisClass = currentClass.symbol;
2123                            }
2124                            else
2125                            {
2126                               if(!_class.symbol)
2127                                  _class.symbol = FindClass(_class.fullName);
2128                               symbol.type.thisClass = _class.symbol;
2129                            }
2130                         }
2131                         // TESTING THIS HERE:
2132                         DeclareType(symbol.type, true, true);
2133
2134                      }
2135                      else if(classSym)
2136                      {
2137                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2138                            unmangled, classSym.string);
2139                      }
2140                   }
2141
2142                   //declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2143                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2144
2145                   if(nameID)
2146                   {
2147                      FreeSpecifier(nameID._class);
2148                      nameID._class = null;
2149                   }
2150
2151                   if(inCompiler)
2152                   {
2153                      //Type type = declarator.symbol.type;
2154                      External oldExternal = curExternal;
2155
2156                      // *** Commented this out... Any negative impact? Yes: makes double prototypes declarations... Why was it commented out?
2157                      // *** It was commented out for problems such as
2158                      /*
2159                            class VirtualDesktop : Window
2160                            {
2161                               clientSize = Size { };
2162                               Timer timer
2163                               {
2164                                  bool DelayExpired()
2165                                  {
2166                                     clientSize.w;
2167                                     return true;
2168                                  }
2169                               };
2170                            }
2171                      */
2172                      // Commented Out: Good for bet.ec in Poker (Otherwise: obj\bet.c:187: error: `currentBet' undeclared (first use in this function))
2173
2174                      declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2175
2176                      /*
2177                      if(strcmp(declarator.symbol.string, name))
2178                      {
2179                         printf("TOCHECK: Look out for this\n");
2180                         delete declarator.symbol.string;
2181                         declarator.symbol.string = CopyString(name);
2182                      }
2183
2184                      if(!declarator.symbol.parent && globalContext.symbols.root != (BTNode)declarator.symbol)
2185                      {
2186                         printf("TOCHECK: Will this ever be in a list? Yes.\n");
2187                         excludedSymbols->Remove(declarator.symbol);
2188                         globalContext.symbols.Add((BTNode)declarator.symbol);
2189                         if(strstr(declarator.symbol.string), "::")
2190                            globalContext.hasNameSpace = true;
2191
2192                      }
2193                      */
2194
2195                      //curExternal = curExternal.prev;
2196                      //afterExternal = afterExternal->next;
2197
2198                      //ProcessFunction(afterExternal->function);
2199
2200                      //curExternal = afterExternal;
2201                      {
2202                         External externalDecl;
2203                         externalDecl = MkExternalDeclaration(null);
2204                         ast->Insert(oldExternal.prev, externalDecl);
2205
2206                         // Which function does this process?
2207                         if(createdExternal.function)
2208                         {
2209                            ProcessFunction(createdExternal.function);
2210
2211                            //curExternal = oldExternal;
2212
2213                            {
2214                               //Declaration decl = MkDeclaration(members.function.specifiers, MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2215
2216                               Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
2217                                  MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2218
2219                               //externalDecl = MkExternalDeclaration(decl);
2220
2221                               //***** ast->Insert(external.prev, externalDecl);
2222                               //ast->Insert(curExternal.prev, externalDecl);
2223                               externalDecl.declaration = decl;
2224                               if(decl.symbol && !decl.symbol.pointerExternal)
2225                                  decl.symbol.pointerExternal = externalDecl;
2226
2227                               // Trying this out...
2228                               declarator.symbol.pointerExternal = externalDecl;
2229                            }
2230                         }
2231                      }
2232                   }
2233                   else if(declarator)
2234                   {
2235                      curExternal = declarator.symbol.pointerExternal;
2236                      ProcessFunction((FunctionDefinition)members.function);
2237                   }
2238                   curExternal = external;
2239                   curContext = context;
2240
2241                   if(inCompiler)
2242                   {
2243                      FreeClassFunction(members.function);
2244
2245                      // In this pass, turn this into a MemberInitData
2246                      exp = QMkExpId(name);
2247                      members.type = dataMembersInit;
2248                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2249
2250                      delete unmangled;
2251                   }
2252                   break;
2253                }
2254                case dataMembersInit:
2255                {
2256                   if(members.dataMembers && classSym)
2257                   {
2258                      MemberInit member;
2259                      Location oldyyloc = yylloc;
2260                      for(member = members.dataMembers->first; member; member = member.next)
2261                      {
2262                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2263                         if(member.initializer && !member.initializer.isConstant)
2264                            inst.isConstant = false;
2265                      }
2266                      yylloc = oldyyloc;
2267                   }
2268                   break;
2269                }
2270             }
2271          }
2272       }
2273    }
2274 }
2275
2276 static void DeclareType(Type type, bool declarePointers, bool declareParams)
2277 {
2278    // OPTIMIZATIONS: TESTING THIS...
2279    if(inCompiler)
2280    {
2281       if(type.kind == functionType)
2282       {
2283          Type param;
2284          if(declareParams)
2285          {
2286             for(param = type.params.first; param; param = param.next)
2287                DeclareType(param, declarePointers, true);
2288          }
2289          DeclareType(type.returnType, declarePointers, true);
2290       }
2291       else if(type.kind == pointerType && declarePointers)
2292          DeclareType(type.type, declarePointers, false);
2293       else if(type.kind == classType)
2294       {
2295          if(type._class.registered && (type._class.registered.type == structClass || type._class.registered.type == noHeadClass) && !type._class.declaring)
2296             DeclareStruct(type._class.registered.fullName, type._class.registered.type == noHeadClass);
2297       }
2298       else if(type.kind == structType || type.kind == unionType)
2299       {
2300          Type member;
2301          for(member = type.members.first; member; member = member.next)
2302             DeclareType(member, false, false);
2303       }
2304       else if(type.kind == arrayType)
2305          DeclareType(type.arrayType, declarePointers, false);
2306    }
2307 }
2308
2309 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2310 {
2311    ClassTemplateArgument * arg = null;
2312    int id = 0;
2313    ClassTemplateParameter curParam = null;
2314    Class sClass;
2315    for(sClass = _class; sClass; sClass = sClass.base)
2316    {
2317       id = 0;
2318       if(sClass.templateClass) sClass = sClass.templateClass;
2319       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2320       {
2321          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2322          {
2323             for(sClass = sClass.base; sClass; sClass = sClass.base)
2324             {
2325                if(sClass.templateClass) sClass = sClass.templateClass;
2326                id += sClass.templateParams.count;
2327             }
2328             break;
2329          }
2330          id++;
2331       }
2332       if(curParam) break;
2333    }
2334    if(curParam)
2335    {
2336       arg = &_class.templateArgs[id];
2337       if(arg && param.type == type)
2338          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2339    }
2340    return arg;
2341 }
2342
2343 public Context SetupTemplatesContext(Class _class)
2344 {
2345    Context context = PushContext();
2346    context.templateTypesOnly = true;
2347    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2348    {
2349       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2350       for(; param; param = param.next)
2351       {
2352          if(param.type == type && param.identifier)
2353          {
2354             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2355             curContext.templateTypes.Add((BTNode)type);
2356          }
2357       }
2358    }
2359    else if(_class)
2360    {
2361       Class sClass;
2362       for(sClass = _class; sClass; sClass = sClass.base)
2363       {
2364          ClassTemplateParameter p;
2365          for(p = sClass.templateParams.first; p; p = p.next)
2366          {
2367             //OldList * specs = MkList();
2368             //Declarator decl = null;
2369             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2370             if(p.type == type)
2371             {
2372                TemplateParameter param = p.param;
2373                TemplatedType type;
2374                if(!param)
2375                {
2376                   // ADD DATA TYPE HERE...
2377                   p.param = param = TemplateParameter
2378                   {
2379                      identifier = MkIdentifier(p.name), type = p.type,
2380                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2381                   };
2382                }
2383                type = TemplatedType { key = (uintptr)p.name, param = param };
2384                curContext.templateTypes.Add((BTNode)type);
2385             }
2386          }
2387       }
2388    }
2389    return context;
2390 }
2391
2392 public void FinishTemplatesContext(Context context)
2393 {
2394    PopContext(context);
2395    FreeContext(context);
2396    delete context;
2397 }
2398
2399 public void ProcessMethodType(Method method)
2400 {
2401    if(!method.dataType)
2402    {
2403       Context context = SetupTemplatesContext(method._class);
2404
2405       method.dataType = ProcessTypeString(method.dataTypeString, false);
2406
2407       FinishTemplatesContext(context);
2408
2409       if(method.type != virtualMethod && method.dataType)
2410       {
2411          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2412          {
2413             if(!method._class.symbol)
2414                method._class.symbol = FindClass(method._class.fullName);
2415             method.dataType.thisClass = method._class.symbol;
2416          }
2417       }
2418
2419       // Why was this commented out? Working fine without now...
2420
2421       /*
2422       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2423          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2424          */
2425    }
2426
2427    /*
2428    if(type)
2429    {
2430       char * par = strstr(type, "(");
2431       char * classOp = null;
2432       int classOpLen = 0;
2433       if(par)
2434       {
2435          int c;
2436          for(c = par-type-1; c >= 0; c++)
2437          {
2438             if(type[c] == ':' && type[c+1] == ':')
2439             {
2440                classOp = type + c - 1;
2441                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2442                {
2443                   classOp--;
2444                   classOpLen++;
2445                }
2446                break;
2447             }
2448             else if(!isspace(type[c]))
2449                break;
2450          }
2451       }
2452       if(classOp)
2453       {
2454          char temp[1024];
2455          int typeLen = strlen(type);
2456          memcpy(temp, classOp, classOpLen);
2457          temp[classOpLen] = '\0';
2458          if(temp[0])
2459             _class = eSystem_FindClass(module, temp);
2460          else
2461             _class = null;
2462          method.dataTypeString = new char[typeLen - classOpLen + 1];
2463          memcpy(method.dataTypeString, type, classOp - type);
2464          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2465       }
2466       else
2467          method.dataTypeString = type;
2468    }
2469    */
2470 }
2471
2472
2473 public void ProcessPropertyType(Property prop)
2474 {
2475    if(!prop.dataType)
2476    {
2477       Context context = SetupTemplatesContext(prop._class);
2478       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2479       FinishTemplatesContext(context);
2480    }
2481 }
2482
2483 public void DeclareMethod(Method method, const char * name)
2484 {
2485    Symbol symbol = method.symbol;
2486    if(!symbol || (!symbol.pointerExternal && method.type == virtualMethod) || symbol.id > (curExternal ? curExternal.symbol.idCode : -1))
2487    {
2488       //bool imported = false;
2489       bool dllImport = false;
2490
2491       if(!method.dataType)
2492          method.dataType = ProcessTypeString(method.dataTypeString, false);
2493
2494       if(!symbol || symbol._import || method.type == virtualMethod)
2495       {
2496          if(!symbol || method.type == virtualMethod)
2497          {
2498             Symbol classSym;
2499             if(!method._class.symbol)
2500                method._class.symbol = FindClass(method._class.fullName);
2501             classSym = method._class.symbol;
2502             if(!classSym._import)
2503             {
2504                ModuleImport module;
2505
2506                if(method._class.module && method._class.module.name)
2507                   module = FindModule(method._class.module);
2508                else
2509                   module = mainModule;
2510                classSym._import = ClassImport
2511                {
2512                   name = CopyString(method._class.fullName);
2513                   isRemote = method._class.isRemote;
2514                };
2515                module.classes.Add(classSym._import);
2516             }
2517             if(!symbol)
2518             {
2519                symbol = method.symbol = Symbol { };
2520             }
2521             if(!symbol._import)
2522             {
2523                symbol._import = (ClassImport)MethodImport
2524                {
2525                   name = CopyString(method.name);
2526                   isVirtual = method.type == virtualMethod;
2527                };
2528                classSym._import.methods.Add(symbol._import);
2529             }
2530             if(!symbol)
2531             {
2532                // Set the symbol type
2533                /*
2534                if(!type.thisClass)
2535                {
2536                   type.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2537                }
2538                else if(type.thisClass == (void *)-1)
2539                {
2540                   type.thisClass = null;
2541                }
2542                */
2543                // symbol.type = ProcessTypeString(method.dataTypeString, false);
2544                symbol.type = method.dataType;
2545                if(symbol.type) symbol.type.refCount++;
2546             }
2547             /*
2548             if(!method.thisClass || strcmp(method.thisClass, "void"))
2549                symbol.type.params.Insert(null,
2550                   MkClassType(method.thisClass ? method.thisClass : method._class.fullName));
2551             */
2552          }
2553          if(!method.dataType.dllExport)
2554          {
2555             //imported = true;
2556             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2557                dllImport = true;
2558          }
2559       }
2560
2561       /* MOVING THIS UP
2562       if(!method.dataType)
2563          method.dataType = ((Symbol)method.symbol).type;
2564          //ProcessMethodType(method);
2565       */
2566
2567       if(method.type != virtualMethod && method.dataType)
2568          DeclareType(method.dataType, true, true);
2569
2570       if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2571       {
2572          // We need a declaration here :)
2573          Declaration decl;
2574          OldList * specifiers, * declarators;
2575          Declarator d;
2576          Declarator funcDecl;
2577          External external;
2578
2579          specifiers = MkList();
2580          declarators = MkList();
2581
2582          //if(imported)
2583          if(dllImport)
2584             ListAdd(specifiers, MkSpecifier(EXTERN));
2585          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2586             ListAdd(specifiers, MkSpecifier(STATIC));
2587
2588          if(method.type == virtualMethod)
2589          {
2590             ListAdd(specifiers, MkSpecifier(INT));
2591             d = MkDeclaratorIdentifier(MkIdentifier(name));
2592          }
2593          else
2594          {
2595             d = MkDeclaratorIdentifier(MkIdentifier(name));
2596             //if(imported)
2597             if(dllImport)
2598                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2599             {
2600                Context context = SetupTemplatesContext(method._class);
2601                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2602                FinishTemplatesContext(context);
2603             }
2604             funcDecl = GetFuncDecl(d);
2605
2606             if(dllImport)
2607             {
2608                Specifier spec, next;
2609                for(spec = specifiers->first; spec; spec = next)
2610                {
2611                   next = spec.next;
2612                   if(spec.type == extendedSpecifier)
2613                   {
2614                      specifiers->Remove(spec);
2615                      FreeSpecifier(spec);
2616                   }
2617                }
2618             }
2619
2620             // Add this parameter if not a static method
2621             if(method.dataType && !method.dataType.staticMethod)
2622             {
2623                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2624                {
2625                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2626                   TypeName thisParam = MkTypeName(MkListOne(
2627                      MkSpecifierName/*MkClassName*/(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2628                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2629                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2630                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2631
2632                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2633                   {
2634                      TypeName param = funcDecl.function.parameters->first;
2635                      funcDecl.function.parameters->Remove(param);
2636                      FreeTypeName(param);
2637                   }
2638
2639                   if(!funcDecl.function.parameters)
2640                      funcDecl.function.parameters = MkList();
2641                   funcDecl.function.parameters->Insert(null, thisParam);
2642                }
2643             }
2644             // Make sure we don't have empty parameter declarations for static methods...
2645             /*
2646             else if(!funcDecl.function.parameters)
2647             {
2648                funcDecl.function.parameters = MkList();
2649                funcDecl.function.parameters->Insert(null,
2650                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2651             }*/
2652          }
2653          // TESTING THIS:
2654          ProcessDeclarator(d);
2655
2656          ListAdd(declarators, MkInitDeclarator(d, null));
2657
2658          decl = MkDeclaration(specifiers, declarators);
2659
2660          ReplaceThisClassSpecifiers(specifiers, method._class);
2661
2662          // Keep a different symbol for the function definition than the declaration...
2663          if(symbol.pointerExternal)
2664          {
2665             Symbol functionSymbol { };
2666
2667             // Copy symbol
2668             {
2669                *functionSymbol = *symbol;
2670                functionSymbol.string = CopyString(symbol.string);
2671                if(functionSymbol.type)
2672                   functionSymbol.type.refCount++;
2673             }
2674
2675             excludedSymbols->Add(functionSymbol);
2676             symbol.pointerExternal.symbol = functionSymbol;
2677          }
2678          external = MkExternalDeclaration(decl);
2679          if(curExternal)
2680             ast->Insert(curExternal ? curExternal.prev : null, external);
2681          external.symbol = symbol;
2682          symbol.pointerExternal = external;
2683       }
2684       else if(ast)
2685       {
2686          // Move declaration higher...
2687          ast->Move(symbol.pointerExternal, curExternal.prev);
2688       }
2689
2690       symbol.id = curExternal ? curExternal.symbol.idCode : MAXINT;
2691    }
2692 }
2693
2694 char * ReplaceThisClass(Class _class)
2695 {
2696    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2697    {
2698       bool first = true;
2699       int p = 0;
2700       ClassTemplateParameter param;
2701       int lastParam = -1;
2702
2703       char className[1024];
2704       strcpy(className, _class.fullName);
2705       for(param = _class.templateParams.first; param; param = param.next)
2706       {
2707          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2708          {
2709             if(first) strcat(className, "<");
2710             if(!first) strcat(className, ", ");
2711             if(lastParam + 1 != p)
2712             {
2713                strcat(className, param.name);
2714                strcat(className, " = ");
2715             }
2716             strcat(className, param.name);
2717             first = false;
2718             lastParam = p;
2719          }
2720          p++;
2721       }
2722       if(!first)
2723       {
2724          int len = strlen(className);
2725          if(className[len-1] == '>') className[len++] = ' ';
2726          className[len++] = '>';
2727          className[len++] = '\0';
2728       }
2729       return CopyString(className);
2730    }
2731    else
2732       return CopyString(_class.fullName);
2733 }
2734
2735 Type ReplaceThisClassType(Class _class)
2736 {
2737    Type type;
2738    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2739    {
2740       bool first = true;
2741       int p = 0;
2742       ClassTemplateParameter param;
2743       int lastParam = -1;
2744       char className[1024];
2745       strcpy(className, _class.fullName);
2746
2747       for(param = _class.templateParams.first; param; param = param.next)
2748       {
2749          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2750          {
2751             if(first) strcat(className, "<");
2752             if(!first) strcat(className, ", ");
2753             if(lastParam + 1 != p)
2754             {
2755                strcat(className, param.name);
2756                strcat(className, " = ");
2757             }
2758             strcat(className, param.name);
2759             first = false;
2760             lastParam = p;
2761          }
2762          p++;
2763       }
2764       if(!first)
2765       {
2766          int len = strlen(className);
2767          if(className[len-1] == '>') className[len++] = ' ';
2768          className[len++] = '>';
2769          className[len++] = '\0';
2770       }
2771       type = MkClassType(className);
2772       //type = ProcessTypeString(className, false);
2773    }
2774    else
2775    {
2776       type = MkClassType(_class.fullName);
2777       //type = ProcessTypeString(_class.fullName, false);
2778    }
2779    //type.wasThisClass = true;
2780    return type;
2781 }
2782
2783 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2784 {
2785    if(specs != null && _class)
2786    {
2787       Specifier spec;
2788       for(spec = specs.first; spec; spec = spec.next)
2789       {
2790          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2791          {
2792             spec.type = nameSpecifier;
2793             spec.name = ReplaceThisClass(_class);
2794             spec.symbol = FindClass(spec.name); //_class.symbol;
2795          }
2796       }
2797    }
2798 }
2799
2800 // Returns imported or not
2801 bool DeclareFunction(GlobalFunction function, char * name)
2802 {
2803    Symbol symbol = function.symbol;
2804    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2805    {
2806       bool imported = false;
2807       bool dllImport = false;
2808
2809       if(!function.dataType)
2810       {
2811          function.dataType = ProcessTypeString(function.dataTypeString, false);
2812          if(!function.dataType.thisClass)
2813             function.dataType.staticMethod = true;
2814       }
2815
2816       if(inCompiler)
2817       {
2818          if(!symbol)
2819          {
2820             ModuleImport module = FindModule(function.module);
2821             // WARNING: This is not added anywhere...
2822             symbol = function.symbol = Symbol {  };
2823
2824             if(module.name)
2825             {
2826                if(!function.dataType.dllExport)
2827                {
2828                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2829                   module.functions.Add(symbol._import);
2830                }
2831             }
2832             // Set the symbol type
2833             {
2834                symbol.type = ProcessTypeString(function.dataTypeString, false);
2835                if(!symbol.type.thisClass)
2836                   symbol.type.staticMethod = true;
2837             }
2838          }
2839          imported = symbol._import ? true : false;
2840          if(imported && function.module != privateModule && function.module.importType != staticImport)
2841             dllImport = true;
2842       }
2843
2844       DeclareType(function.dataType, true, true);
2845
2846       if(inCompiler)
2847       {
2848          if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2849          {
2850             // We need a declaration here :)
2851             Declaration decl;
2852             OldList * specifiers, * declarators;
2853             Declarator d;
2854             Declarator funcDecl;
2855             External external;
2856
2857             specifiers = MkList();
2858             declarators = MkList();
2859
2860             //if(imported)
2861                ListAdd(specifiers, MkSpecifier(EXTERN));
2862             /*
2863             else
2864                ListAdd(specifiers, MkSpecifier(STATIC));
2865             */
2866
2867             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2868             //if(imported)
2869             if(dllImport)
2870                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2871
2872             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2873             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2874             if(function.module.importType == staticImport)
2875             {
2876                Specifier spec;
2877                for(spec = specifiers->first; spec; spec = spec.next)
2878                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2879                   {
2880                      specifiers->Remove(spec);
2881                      FreeSpecifier(spec);
2882                      break;
2883                   }
2884             }
2885
2886             funcDecl = GetFuncDecl(d);
2887
2888             // Make sure we don't have empty parameter declarations for static methods...
2889             if(funcDecl && !funcDecl.function.parameters)
2890             {
2891                funcDecl.function.parameters = MkList();
2892                funcDecl.function.parameters->Insert(null,
2893                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2894             }
2895
2896             ListAdd(declarators, MkInitDeclarator(d, null));
2897
2898             {
2899                Context oldCtx = curContext;
2900                curContext = globalContext;
2901                decl = MkDeclaration(specifiers, declarators);
2902                curContext = oldCtx;
2903             }
2904
2905             // Keep a different symbol for the function definition than the declaration...
2906             if(symbol.pointerExternal)
2907             {
2908                Symbol functionSymbol { };
2909                // Copy symbol
2910                {
2911                   *functionSymbol = *symbol;
2912                   functionSymbol.string = CopyString(symbol.string);
2913                   if(functionSymbol.type)
2914                      functionSymbol.type.refCount++;
2915                }
2916
2917                excludedSymbols->Add(functionSymbol);
2918
2919                symbol.pointerExternal.symbol = functionSymbol;
2920             }
2921             external = MkExternalDeclaration(decl);
2922             if(curExternal)
2923                ast->Insert(curExternal.prev, external);
2924             external.symbol = symbol;
2925             symbol.pointerExternal = external;
2926          }
2927          else
2928          {
2929             // Move declaration higher...
2930             ast->Move(symbol.pointerExternal, curExternal.prev);
2931          }
2932
2933          if(curExternal)
2934             symbol.id = curExternal.symbol.idCode;
2935       }
2936    }
2937    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2938 }
2939
2940 void DeclareGlobalData(GlobalData data)
2941 {
2942    Symbol symbol = data.symbol;
2943    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2944    {
2945       if(inCompiler)
2946       {
2947          if(!symbol)
2948             symbol = data.symbol = Symbol { };
2949       }
2950       if(!data.dataType)
2951          data.dataType = ProcessTypeString(data.dataTypeString, false);
2952       DeclareType(data.dataType, true, true);
2953       if(inCompiler)
2954       {
2955          if(!symbol.pointerExternal)
2956          {
2957             // We need a declaration here :)
2958             Declaration decl;
2959             OldList * specifiers, * declarators;
2960             Declarator d;
2961             External external;
2962
2963             specifiers = MkList();
2964             declarators = MkList();
2965
2966             ListAdd(specifiers, MkSpecifier(EXTERN));
2967             d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2968             d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2969
2970             ListAdd(declarators, MkInitDeclarator(d, null));
2971
2972             decl = MkDeclaration(specifiers, declarators);
2973             external = MkExternalDeclaration(decl);
2974             if(curExternal)
2975                ast->Insert(curExternal.prev, external);
2976             external.symbol = symbol;
2977             symbol.pointerExternal = external;
2978          }
2979          else
2980          {
2981             // Move declaration higher...
2982             ast->Move(symbol.pointerExternal, curExternal.prev);
2983          }
2984
2985          if(curExternal)
2986             symbol.id = curExternal.symbol.idCode;
2987       }
2988    }
2989 }
2990
2991 class Conversion : struct
2992 {
2993    Conversion prev, next;
2994    Property convert;
2995    bool isGet;
2996    Type resultType;
2997 };
2998
2999 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
3000 {
3001    bool status = true;
3002    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
3003       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
3004    {
3005       Class sourceClass = source.kind == classType ? source._class.registered : null;
3006       Class destClass = dest.kind == classType ? dest._class.registered : null;
3007       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
3008          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
3009       {
3010          Type sourceType = source, destType = dest;
3011          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
3012          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
3013          if(!destType.constant && sourceType.constant)
3014          {
3015             status = false;
3016             if(warn)
3017                Compiler_Warning($"discarding const qualifier\n");
3018          }
3019       }
3020    }
3021    return status;
3022 }
3023
3024 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
3025                        bool isConversionExploration, bool warnConst)
3026 {
3027    if(source && dest)
3028    {
3029       if(warnConst)
3030          CheckConstCompatibility(source, dest, true);
3031       // Property convert;
3032
3033       if(source.kind == templateType && dest.kind != templateType)
3034       {
3035          Type type = ProcessTemplateParameterType(source.templateParameter);
3036          if(type) source = type;
3037       }
3038
3039       if(dest.kind == templateType && source.kind != templateType)
3040       {
3041          Type type = ProcessTemplateParameterType(dest.templateParameter);
3042          if(type) dest = type;
3043       }
3044
3045       if(dest.classObjectType == typedObject && dest.kind != functionType)
3046       {
3047          if(source.classObjectType != anyObject)
3048             return true;
3049          else
3050          {
3051             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
3052             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
3053             {
3054                return true;
3055             }
3056          }
3057       }
3058       else
3059       {
3060          if(source.kind != functionType && source.classObjectType == anyObject)
3061             return true;
3062          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
3063             return true;
3064       }
3065
3066       if((dest.kind == structType && source.kind == structType) ||
3067          (dest.kind == unionType && source.kind == unionType))
3068       {
3069          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
3070              (source.members.first && source.members.first == dest.members.first))
3071             return true;
3072       }
3073
3074       if(dest.kind == ellipsisType && source.kind != voidType)
3075          return true;
3076
3077       if(dest.kind == pointerType && dest.type.kind == voidType &&
3078          ((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))
3079          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
3080
3081          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
3082
3083          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
3084          return true;
3085       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
3086          ((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))
3087          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
3088          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
3089
3090          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
3091          return true;
3092
3093       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
3094       {
3095          if(source._class.registered && source._class.registered.type == unitClass)
3096          {
3097             if(conversions != null)
3098             {
3099                if(source._class.registered == dest._class.registered)
3100                   return true;
3101             }
3102             else
3103             {
3104                Class sourceBase, destBase;
3105                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
3106                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
3107                if(sourceBase == destBase)
3108                   return true;
3109             }
3110          }
3111          // Don't match enum inheriting from other enum if resolving enumeration values
3112          // TESTING: !dest.classObjectType
3113          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
3114             (enumBaseType ||
3115                (!source._class.registered || source._class.registered.type != enumClass) ||
3116                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
3117             return true;
3118          else
3119          {
3120             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
3121             if(enumBaseType &&
3122                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
3123                ((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)
3124             {
3125                if(eClass_IsDerived(dest._class.registered, source._class.registered))
3126                {
3127                   return true;
3128                }
3129             }
3130          }
3131       }
3132
3133       // JUST ADDED THIS...
3134       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
3135          return true;
3136
3137       if(doConversion)
3138       {
3139          // Just added this for Straight conversion of ColorAlpha => Color
3140          if(source.kind == classType)
3141          {
3142             Class _class;
3143             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3144             {
3145                Property convert;
3146                for(convert = _class.conversions.first; convert; convert = convert.next)
3147                {
3148                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3149                   {
3150                      Conversion after = (conversions != null) ? conversions.last : null;
3151
3152                      if(!convert.dataType)
3153                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3154                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
3155                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3156                         MatchTypes(convert.dataType, dest, conversions, null, null,
3157                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
3158                               convert.dataType.kind == classType, false, true, warnConst))
3159                      {
3160                         if(!conversions && !convert.Get)
3161                            return true;
3162                         else if(conversions != null)
3163                         {
3164                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3165                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3166                               (dest.kind != classType || dest._class.registered != _class.base))
3167                               return true;
3168                            else
3169                            {
3170                               Conversion conv { convert = convert, isGet = true };
3171                               // conversions.Add(conv);
3172                               conversions.Insert(after, conv);
3173
3174                               return true;
3175                            }
3176                         }
3177                      }
3178                   }
3179                }
3180             }
3181          }
3182
3183          // MOVING THIS??
3184
3185          if(dest.kind == classType)
3186          {
3187             Class _class;
3188             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3189             {
3190                Property convert;
3191                for(convert = _class.conversions.first; convert; convert = convert.next)
3192                {
3193                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3194                   {
3195                      Type constType = null;
3196                      bool success = false;
3197                      // Conversion after = (conversions != null) ? conversions.last : null;
3198
3199                      if(!convert.dataType)
3200                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3201
3202                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3203                      {
3204                         Type ptrType { };
3205                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3206                         CopyTypeInto(ptrType, convert.dataType.type);
3207                         ptrType.constant = true;
3208                      }
3209
3210                      // Just added this equality check to prevent recursion.... Make it safer?
3211                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3212                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3213                      {
3214                         if(!conversions && !convert.Set)
3215                            success = true;
3216                         else if(conversions != null)
3217                         {
3218                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3219                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3220                               (source.kind != classType || source._class.registered != _class.base))
3221                               success = true;
3222                            else
3223                            {
3224                               // *** Testing this! ***
3225                               Conversion conv { convert = convert };
3226                               conversions.Add(conv);
3227                               //conversions.Insert(after, conv);
3228                               success = true;
3229                            }
3230                         }
3231                      }
3232                      if(constType)
3233                         FreeType(constType);
3234                      if(success)
3235                         return true;
3236                   }
3237                }
3238             }
3239             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3240             {
3241                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3242                   (source.kind != classType || source._class.registered.type != structClass))
3243                   return true;
3244             }*/
3245
3246             // TESTING THIS... IS THIS OK??
3247             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3248             {
3249                if(!dest._class.registered.dataType)
3250                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3251                // Only support this for classes...
3252                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3253                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3254                {
3255                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3256                   {
3257                      return true;
3258                   }
3259                }
3260             }
3261          }
3262
3263          // Moved this lower
3264          if(source.kind == classType)
3265          {
3266             Class _class;
3267             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3268             {
3269                Property convert;
3270                for(convert = _class.conversions.first; convert; convert = convert.next)
3271                {
3272                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3273                   {
3274                      Conversion after = (conversions != null) ? conversions.last : null;
3275
3276                      if(!convert.dataType)
3277                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3278                      if(convert.dataType != source &&
3279                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3280                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3281                      {
3282                         if(!conversions && !convert.Get)
3283                            return true;
3284                         else if(conversions != null)
3285                         {
3286                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3287                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3288                               (dest.kind != classType || dest._class.registered != _class.base))
3289                               return true;
3290                            else
3291                            {
3292                               Conversion conv { convert = convert, isGet = true };
3293
3294                               // conversions.Add(conv);
3295                               conversions.Insert(after, conv);
3296                               return true;
3297                            }
3298                         }
3299                      }
3300                   }
3301                }
3302             }
3303
3304             // TESTING THIS... IS THIS OK??
3305             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3306             {
3307                if(!source._class.registered.dataType)
3308                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3309                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3310                {
3311                   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))
3312                      return true;
3313                   // For bool to be accepted by byte, short, etc.
3314                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3315                      return true;
3316                }
3317             }
3318          }
3319       }
3320
3321       if(source.kind == classType || source.kind == subClassType)
3322          ;
3323       else if(dest.kind == source.kind &&
3324          (dest.kind != structType && dest.kind != unionType &&
3325           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3326           return true;
3327       // RECENTLY ADDED THESE
3328       else if(dest.kind == doubleType && source.kind == floatType)
3329          return true;
3330       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3331          return true;
3332       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3333          return true;
3334       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3335          return true;
3336       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3337          return true;
3338       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3339          return true;
3340       else if(source.kind == enumType &&
3341          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3342           return true;
3343       else if(dest.kind == enumType && !isConversionExploration &&
3344          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3345           return true;
3346       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3347               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3348       {
3349          Type paramSource, paramDest;
3350
3351          if(dest.kind == methodType)
3352             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3353          if(source.kind == methodType)
3354             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3355
3356          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3357          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3358          if(dest.kind == methodType)
3359             dest = dest.method.dataType;
3360          if(source.kind == methodType)
3361             source = source.method.dataType;
3362
3363          paramSource = source.params.first;
3364          if(paramSource && paramSource.kind == voidType) paramSource = null;
3365          paramDest = dest.params.first;
3366          if(paramDest && paramDest.kind == voidType) paramDest = null;
3367
3368
3369          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3370             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3371          {
3372             // Source thisClass must be derived from destination thisClass
3373             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3374                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3375             {
3376                if(paramDest && paramDest.kind == classType)
3377                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3378                else
3379                   Compiler_Error($"method class should not take an object\n");
3380                return false;
3381             }
3382             paramDest = paramDest.next;
3383          }
3384          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3385          {
3386             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3387             {
3388                if(dest.thisClass)
3389                {
3390                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3391                   {
3392                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3393                      return false;
3394                   }
3395                }
3396                else
3397                {
3398                   // THIS WAS BACKWARDS:
3399                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3400                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3401                   {
3402                      if(owningClassDest)
3403                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3404                      else
3405                         Compiler_Error($"overriding class expected to be derived from method class\n");
3406                      return false;
3407                   }
3408                }
3409                paramSource = paramSource.next;
3410             }
3411             else
3412             {
3413                if(dest.thisClass)
3414                {
3415                   // Source thisClass must be derived from destination thisClass
3416                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3417                   {
3418                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3419                      return false;
3420                   }
3421                }
3422                else
3423                {
3424                   // THIS WAS BACKWARDS TOO??
3425                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3426                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3427                   {
3428                      //if(owningClass)
3429                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3430                      //else
3431                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3432                      return false;
3433                   }
3434                }
3435             }
3436          }
3437
3438
3439          // Source return type must be derived from destination return type
3440          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3441          {
3442             Compiler_Warning($"incompatible return type for function\n");
3443             return false;
3444          }
3445          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3446          else
3447             CheckConstCompatibility(dest.returnType, source.returnType, true);
3448
3449          // Check parameters
3450
3451          for(; paramDest; paramDest = paramDest.next)
3452          {
3453             if(!paramSource)
3454             {
3455                //Compiler_Warning($"not enough parameters\n");
3456                Compiler_Error($"not enough parameters\n");
3457                return false;
3458             }
3459             {
3460                Type paramDestType = paramDest;
3461                Type paramSourceType = paramSource;
3462                Type type = paramDestType;
3463
3464                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3465                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3466                   paramSource.kind != templateType)
3467                {
3468                   int id = 0;
3469                   ClassTemplateParameter curParam = null;
3470                   Class sClass;
3471                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3472                   {
3473                      id = 0;
3474                      if(sClass.templateClass) sClass = sClass.templateClass;
3475                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3476                      {
3477                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3478                         {
3479                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3480                            {
3481                               if(sClass.templateClass) sClass = sClass.templateClass;
3482                               id += sClass.templateParams.count;
3483                            }
3484                            break;
3485                         }
3486                         id++;
3487                      }
3488                      if(curParam) break;
3489                   }
3490
3491                   if(curParam)
3492                   {
3493                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3494                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3495                   }
3496                }
3497
3498                // paramDest must be derived from paramSource
3499                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3500                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3501                {
3502                   char type[1024];
3503                   type[0] = 0;
3504                   PrintType(paramDest, type, false, true);
3505                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3506
3507                   if(paramDestType != paramDest)
3508                      FreeType(paramDestType);
3509                   return false;
3510                }
3511                if(paramDestType != paramDest)
3512                   FreeType(paramDestType);
3513             }
3514
3515             paramSource = paramSource.next;
3516          }
3517          if(paramSource)
3518          {
3519             Compiler_Error($"too many parameters\n");
3520             return false;
3521          }
3522          return true;
3523       }
3524       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3525       {
3526          return true;
3527       }
3528       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3529          (source.kind == arrayType || source.kind == pointerType))
3530       {
3531          if(MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3532             return true;
3533       }
3534    }
3535    return false;
3536 }
3537
3538 static void FreeConvert(Conversion convert)
3539 {
3540    if(convert.resultType)
3541       FreeType(convert.resultType);
3542 }
3543
3544 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3545                               char * string, OldList conversions)
3546 {
3547    BTNamedLink link;
3548
3549    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3550    {
3551       Class _class = link.data;
3552       if(_class.type == enumClass)
3553       {
3554          OldList converts { };
3555          Type type { };
3556          type.kind = classType;
3557
3558          if(!_class.symbol)
3559             _class.symbol = FindClass(_class.fullName);
3560          type._class = _class.symbol;
3561
3562          if(MatchTypes(type, dest, &converts, null, null, true, false, false, false, false))
3563          {
3564             NamedLink64 value;
3565             Class enumClass = eSystem_FindClass(privateModule, "enum");
3566             if(enumClass)
3567             {
3568                Class baseClass;
3569                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3570                {
3571                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3572                   for(value = e.values.first; value; value = value.next)
3573                   {
3574                      if(!strcmp(value.name, string))
3575                         break;
3576                   }
3577                   if(value)
3578                   {
3579                      FreeExpContents(sourceExp);
3580                      FreeType(sourceExp.expType);
3581
3582                      sourceExp.isConstant = true;
3583                      sourceExp.expType = MkClassType(baseClass.fullName);
3584                      //if(inCompiler)
3585                      {
3586                         char constant[256];
3587                         sourceExp.type = constantExp;
3588                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3589                            sprintf(constant, FORMAT64D, value.data);
3590                         else
3591                            sprintf(constant, FORMAT64HEXLL, value.data);
3592                         sourceExp.constant = CopyString(constant);
3593                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3594                      }
3595
3596                      while(converts.first)
3597                      {
3598                         Conversion convert = converts.first;
3599                         converts.Remove(convert);
3600                         conversions.Add(convert);
3601                      }
3602                      delete type;
3603                      return true;
3604                   }
3605                }
3606             }
3607          }
3608          if(converts.first)
3609             converts.Free(FreeConvert);
3610          delete type;
3611       }
3612    }
3613    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3614       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3615          return true;
3616    return false;
3617 }
3618
3619 public bool ModuleVisibility(Module searchIn, Module searchFor)
3620 {
3621    SubModule subModule;
3622
3623    if(searchFor == searchIn)
3624       return true;
3625
3626    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3627    {
3628       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3629       {
3630          if(ModuleVisibility(subModule.module, searchFor))
3631             return true;
3632       }
3633    }
3634    return false;
3635 }
3636
3637 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3638 {
3639    Module module;
3640
3641    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3642       return true;
3643    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3644       return true;
3645    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3646       return true;
3647
3648    for(module = mainModule.application.allModules.first; module; module = module.next)
3649    {
3650       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3651          return true;
3652    }
3653    return false;
3654 }
3655
3656 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3657 {
3658    Type source;
3659    Type realDest = dest;
3660    Type backupSourceExpType = null;
3661    Expression computedExp = sourceExp;
3662    dest.refCount++;
3663
3664    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3665       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3666    {
3667       computedExp = CopyExpression(sourceExp);        // Keep the original expression, but compute for checking enum ranges
3668       ComputeExpression(computedExp /*sourceExp*/);
3669    }
3670
3671    source = sourceExp.expType;
3672
3673    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3674    {
3675       if(computedExp != sourceExp)
3676       {
3677          FreeExpression(computedExp);
3678          computedExp = sourceExp;
3679       }
3680       FreeType(dest);
3681       return true;
3682    }
3683
3684    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3685    {
3686        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3687        {
3688           Class sourceBase, destBase;
3689           for(sourceBase = source._class.registered;
3690               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3691               sourceBase = sourceBase.base);
3692           for(destBase = dest._class.registered;
3693               destBase && destBase.base && destBase.base.type != systemClass;
3694               destBase = destBase.base);
3695           //if(source._class.registered == dest._class.registered)
3696           if(sourceBase == destBase)
3697           {
3698             if(computedExp != sourceExp)
3699             {
3700                FreeExpression(computedExp);
3701                computedExp = sourceExp;
3702             }
3703             FreeType(dest);
3704             return true;
3705          }
3706       }
3707    }
3708
3709    if(source)
3710    {
3711       OldList * specs;
3712       bool flag = false;
3713       int64 value = MAXINT;
3714
3715       source.refCount++;
3716
3717       if(computedExp.type == constantExp)
3718       {
3719          if(source.isSigned)
3720             value = strtoll(computedExp.constant, null, 0);
3721          else
3722             value = strtoull(computedExp.constant, null, 0);
3723       }
3724       else if(computedExp.type == opExp && sourceExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3725       {
3726          if(source.isSigned)
3727             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3728          else
3729             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3730       }
3731       if(computedExp != sourceExp)
3732       {
3733          FreeExpression(computedExp);
3734          computedExp = sourceExp;
3735       }
3736
3737       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3738          !strcmp(source._class.registered.fullName, "ecere::com::unichar"))
3739       {
3740          FreeType(source);
3741          source = Type { kind = intType, isSigned = false, refCount = 1 };
3742       }
3743
3744       if(dest.kind == classType)
3745       {
3746          Class _class = dest._class ? dest._class.registered : null;
3747
3748          if(_class && _class.type == unitClass)
3749          {
3750             if(source.kind != classType)
3751             {
3752                Type tempType { };
3753                Type tempDest, tempSource;
3754
3755                for(; _class.base.type != systemClass; _class = _class.base);
3756                tempSource = dest;
3757                tempDest = tempType;
3758
3759                tempType.kind = classType;
3760                if(!_class.symbol)
3761                   _class.symbol = FindClass(_class.fullName);
3762
3763                tempType._class = _class.symbol;
3764                tempType.truth = dest.truth;
3765                if(tempType._class)
3766                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3767
3768                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3769                backupSourceExpType = sourceExp.expType;
3770                sourceExp.expType = dest; dest.refCount++;
3771                //sourceExp.expType = MkClassType(_class.fullName);
3772                flag = true;
3773
3774                delete tempType;
3775             }
3776          }
3777
3778
3779          // Why wasn't there something like this?
3780          if(_class && _class.type == bitClass && source.kind != classType)
3781          {
3782             if(!dest._class.registered.dataType)
3783                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3784             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3785             {
3786                FreeType(source);
3787                FreeType(sourceExp.expType);
3788                source = sourceExp.expType = MkClassType(dest._class.string);
3789                source.refCount++;
3790
3791                //source.kind = classType;
3792                //source._class = dest._class;
3793             }
3794          }
3795
3796          // Adding two enumerations
3797          /*
3798          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3799          {
3800             if(!source._class.registered.dataType)
3801                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3802             if(!dest._class.registered.dataType)
3803                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3804
3805             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3806             {
3807                FreeType(source);
3808                source = sourceExp.expType = MkClassType(dest._class.string);
3809                source.refCount++;
3810
3811                //source.kind = classType;
3812                //source._class = dest._class;
3813             }
3814          }*/
3815
3816          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3817          {
3818             OldList * specs = MkList();
3819             Declarator decl;
3820             char string[1024];
3821
3822             ReadString(string, sourceExp.string);
3823             decl = SpecDeclFromString(string, specs, null);
3824
3825             FreeExpContents(sourceExp);
3826             FreeType(sourceExp.expType);
3827
3828             sourceExp.type = classExp;
3829             sourceExp._classExp.specifiers = specs;
3830             sourceExp._classExp.decl = decl;
3831             sourceExp.expType = dest;
3832             dest.refCount++;
3833
3834             FreeType(source);
3835             FreeType(dest);
3836             if(backupSourceExpType) FreeType(backupSourceExpType);
3837             return true;
3838          }
3839       }
3840       else if(source.kind == classType)
3841       {
3842          Class _class = source._class ? source._class.registered : null;
3843
3844          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || /*_class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3845          {
3846             /*
3847             if(dest.kind != classType)
3848             {
3849                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3850                if(!source._class.registered.dataType)
3851                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3852
3853                FreeType(dest);
3854                dest = MkClassType(source._class.string);
3855                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3856                //   dest = MkClassType(source._class.string);
3857             }
3858             */
3859
3860             if(dest.kind != classType)
3861             {
3862                Type tempType { };
3863                Type tempDest, tempSource;
3864
3865                if(!source._class.registered.dataType)
3866                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3867
3868                for(; _class.base.type != systemClass; _class = _class.base);
3869                tempDest = source;
3870                tempSource = tempType;
3871                tempType.kind = classType;
3872                tempType._class = FindClass(_class.fullName);
3873                tempType.truth = source.truth;
3874                tempType.classObjectType = source.classObjectType;
3875
3876                if(tempType._class)
3877                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3878
3879                // PUT THIS BACK TESTING UNITS?
3880                if(conversions.last)
3881                {
3882                   ((Conversion)(conversions.last)).resultType = dest;
3883                   dest.refCount++;
3884                }
3885
3886                FreeType(sourceExp.expType);
3887                sourceExp.expType = MkClassType(_class.fullName);
3888                sourceExp.expType.truth = source.truth;
3889                sourceExp.expType.classObjectType = source.classObjectType;
3890
3891                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3892
3893                if(!sourceExp.destType)
3894                {
3895                   FreeType(sourceExp.destType);
3896                   sourceExp.destType = sourceExp.expType;
3897                   if(sourceExp.expType)
3898                      sourceExp.expType.refCount++;
3899                }
3900                //flag = true;
3901                //source = _class.dataType;
3902
3903
3904                // TOCHECK: TESTING THIS NEW CODE
3905                if(!_class.dataType)
3906                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3907                FreeType(dest);
3908                dest = MkClassType(source._class.string);
3909                dest.truth = source.truth;
3910                dest.classObjectType = source.classObjectType;
3911
3912                FreeType(source);
3913                source = _class.dataType;
3914                source.refCount++;
3915
3916                delete tempType;
3917             }
3918          }
3919       }
3920
3921       if(!flag)
3922       {
3923          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3924          {
3925             FreeType(source);
3926             FreeType(dest);
3927             return true;
3928          }
3929       }
3930
3931       // Implicit Casts
3932       /*
3933       if(source.kind == classType)
3934       {
3935          Class _class = source._class.registered;
3936          if(_class.type == unitClass)
3937          {
3938             if(!_class.dataType)
3939                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3940             source = _class.dataType;
3941          }
3942       }*/
3943
3944       if(dest.kind == classType)
3945       {
3946          Class _class = dest._class ? dest._class.registered : null;
3947          bool fittingValue = false;
3948          if(_class && _class.type == enumClass)
3949          {
3950             Class enumClass = eSystem_FindClass(privateModule, "enum");
3951             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3952             if(c && value >= 0 && value <= c.largest)
3953                fittingValue = true;
3954          }
3955
3956          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3957             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3958          {
3959             if(_class.type == normalClass || _class.type == noHeadClass)
3960             {
3961                Expression newExp { };
3962                *newExp = *sourceExp;
3963                if(sourceExp.destType) sourceExp.destType.refCount++;
3964                if(sourceExp.expType)  sourceExp.expType.refCount++;
3965                sourceExp.type = castExp;
3966                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3967                sourceExp.cast.exp = newExp;
3968                FreeType(sourceExp.expType);
3969                sourceExp.expType = null;
3970                ProcessExpressionType(sourceExp);
3971
3972                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3973                if(!inCompiler)
3974                {
3975                   FreeType(sourceExp.expType);
3976                   sourceExp.expType = dest;
3977                }
3978
3979                FreeType(source);
3980                if(inCompiler) FreeType(dest);
3981
3982                if(backupSourceExpType) FreeType(backupSourceExpType);
3983                return true;
3984             }
3985
3986             if(!_class.dataType)
3987                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3988             FreeType(dest);
3989             dest = _class.dataType;
3990             dest.refCount++;
3991          }
3992
3993          // Accept lower precision types for units, since we want to keep the unit type
3994          if(dest.kind == doubleType &&
3995             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3996              source.kind == charType || source.kind == _BoolType))
3997          {
3998             specs = MkListOne(MkSpecifier(DOUBLE));
3999          }
4000          else if(dest.kind == floatType &&
4001             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
4002             source.kind == _BoolType || source.kind == doubleType))
4003          {
4004             specs = MkListOne(MkSpecifier(FLOAT));
4005          }
4006          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
4007             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
4008          {
4009             specs = MkList();
4010             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4011             ListAdd(specs, MkSpecifier(INT64));
4012          }
4013          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
4014             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
4015          {
4016             specs = MkList();
4017             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4018             ListAdd(specs, MkSpecifier(INT));
4019          }
4020          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
4021             source.kind == floatType || source.kind == doubleType))
4022          {
4023             specs = MkList();
4024             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4025             ListAdd(specs, MkSpecifier(SHORT));
4026          }
4027          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
4028             source.kind == floatType || source.kind == doubleType))
4029          {
4030             specs = MkList();
4031             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4032             ListAdd(specs, MkSpecifier(CHAR));
4033          }
4034          else
4035          {
4036             FreeType(source);
4037             FreeType(dest);
4038             if(backupSourceExpType)
4039             {
4040                // Failed to convert: revert previous exp type
4041                if(sourceExp.expType) FreeType(sourceExp.expType);
4042                sourceExp.expType = backupSourceExpType;
4043             }
4044             return false;
4045          }
4046       }
4047       else if(dest.kind == doubleType &&
4048          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
4049           source.kind == _BoolType || source.kind == charType))
4050       {
4051          specs = MkListOne(MkSpecifier(DOUBLE));
4052       }
4053       else if(dest.kind == floatType &&
4054          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
4055       {
4056          specs = MkListOne(MkSpecifier(FLOAT));
4057       }
4058       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
4059          (value == 1 || value == 0))
4060       {
4061          specs = MkList();
4062          ListAdd(specs, MkSpecifier(BOOL));
4063       }
4064       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
4065          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
4066       {
4067          specs = MkList();
4068          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4069          ListAdd(specs, MkSpecifier(CHAR));
4070       }
4071       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
4072          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
4073       {
4074          specs = MkList();
4075          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4076          ListAdd(specs, MkSpecifier(SHORT));
4077       }
4078       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
4079       {
4080          specs = MkList();
4081          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4082          ListAdd(specs, MkSpecifier(INT));
4083       }
4084       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
4085       {
4086          specs = MkList();
4087          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4088          ListAdd(specs, MkSpecifier(INT64));
4089       }
4090       else if(dest.kind == enumType &&
4091          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
4092       {
4093          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
4094       }
4095       else
4096       {
4097          FreeType(source);
4098          FreeType(dest);
4099          if(backupSourceExpType)
4100          {
4101             // Failed to convert: revert previous exp type
4102             if(sourceExp.expType) FreeType(sourceExp.expType);
4103             sourceExp.expType = backupSourceExpType;
4104          }
4105          return false;
4106       }
4107
4108       if(!flag && !sourceExp.opDestType)
4109       {
4110          Expression newExp { };
4111          *newExp = *sourceExp;
4112          newExp.prev = null;
4113          newExp.next = null;
4114          if(sourceExp.destType) sourceExp.destType.refCount++;
4115          if(sourceExp.expType)  sourceExp.expType.refCount++;
4116
4117          sourceExp.type = castExp;
4118          if(realDest.kind == classType)
4119          {
4120             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
4121             FreeList(specs, FreeSpecifier);
4122          }
4123          else
4124             sourceExp.cast.typeName = MkTypeName(specs, null);
4125          if(newExp.type == opExp)
4126          {
4127             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
4128          }
4129          else
4130             sourceExp.cast.exp = newExp;
4131
4132          FreeType(sourceExp.expType);
4133          sourceExp.expType = null;
4134          ProcessExpressionType(sourceExp);
4135       }
4136       else
4137          FreeList(specs, FreeSpecifier);
4138
4139       FreeType(dest);
4140       FreeType(source);
4141       if(backupSourceExpType) FreeType(backupSourceExpType);
4142
4143       return true;
4144    }
4145    else
4146    {
4147       if(computedExp != sourceExp)
4148       {
4149          FreeExpression(computedExp);
4150          computedExp = sourceExp;
4151       }
4152
4153       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4154       if(sourceExp.type == identifierExp)
4155       {
4156          Identifier id = sourceExp.identifier;
4157          if(dest.kind == classType)
4158          {
4159             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4160             {
4161                Class _class = dest._class.registered;
4162                Class enumClass = eSystem_FindClass(privateModule, "enum");
4163                if(enumClass)
4164                {
4165                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4166                   {
4167                      NamedLink64 value;
4168                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4169                      for(value = e.values.first; value; value = value.next)
4170                      {
4171                         if(!strcmp(value.name, id.string))
4172                            break;
4173                      }
4174                      if(value)
4175                      {
4176                         FreeExpContents(sourceExp);
4177                         FreeType(sourceExp.expType);
4178
4179                         sourceExp.isConstant = true;
4180                         sourceExp.expType = MkClassType(_class.fullName);
4181                         //if(inCompiler)
4182                         {
4183                            sourceExp.type = constantExp;
4184                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4185                               sourceExp.constant = PrintInt64(value.data);
4186                            else
4187                               sourceExp.constant = PrintUInt64(value.data);
4188                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4189                         }
4190                         FreeType(dest);
4191                         return true;
4192                      }
4193                   }
4194                }
4195             }
4196          }
4197
4198          // Loop through all enum classes
4199          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4200          {
4201             FreeType(dest);
4202             return true;
4203          }
4204       }
4205       FreeType(dest);
4206    }
4207    return false;
4208 }
4209
4210 #define TERTIARY(o, name, m, t, p) \
4211    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4212    {                                                              \
4213       exp.type = constantExp;                                    \
4214       exp.string = p(op1.m ? op2.m : op3.m);                     \
4215       if(!exp.expType) \
4216          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4217       return true;                                                \
4218    }
4219
4220 #define BINARY(o, name, m, t, p) \
4221    static bool name(Expression exp, Operand op1, Operand op2)   \
4222    {                                                              \
4223       t value2 = op2.m;                                           \
4224       exp.type = constantExp;                                    \
4225       exp.string = p((t)(op1.m o value2));                     \
4226       if(!exp.expType) \
4227          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4228       return true;                                                \
4229    }
4230
4231 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4232    static bool name(Expression exp, Operand op1, Operand op2)   \
4233    {                                                              \
4234       t value2 = op2.m;                                           \
4235       exp.type = constantExp;                                    \
4236       exp.string = p(value2 ? (op1.m o value2) : 0);             \
4237       if(!exp.expType) \
4238          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4239       return true;                                                \
4240    }
4241
4242 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4243    static bool name(Expression exp, Operand op1, Operand op2)   \
4244    {                                                              \
4245       t value2 = op2.m;                                           \
4246       exp.type = constantExp;                                    \
4247       exp.string = p(op1.m o value2);             \
4248       if(!exp.expType) \
4249          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4250       return true;                                                \
4251    }
4252
4253 #define UNARY(o, name, m, t, p) \
4254    static bool name(Expression exp, Operand op1)                \
4255    {                                                              \
4256       exp.type = constantExp;                                    \
4257       exp.string = p((t)(o op1.m));                                   \
4258       if(!exp.expType) \
4259          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4260       return true;                                                \
4261    }
4262
4263 #define OPERATOR_ALL(macro, o, name) \
4264    macro(o, Int##name, i, int, PrintInt) \
4265    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4266    macro(o, Int64##name, i64, int64, PrintInt64) \
4267    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4268    macro(o, Short##name, s, short, PrintShort) \
4269    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4270    macro(o, Char##name, c, char, PrintChar) \
4271    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4272    macro(o, Float##name, f, float, PrintFloat) \
4273    macro(o, Double##name, d, double, PrintDouble)
4274
4275 #define OPERATOR_INTTYPES(macro, o, name) \
4276    macro(o, Int##name, i, int, PrintInt) \
4277    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4278    macro(o, Int64##name, i64, int64, PrintInt64) \
4279    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4280    macro(o, Short##name, s, short, PrintShort) \
4281    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4282    macro(o, Char##name, c, char, PrintChar) \
4283    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4284
4285 #define OPERATOR_REALTYPES(macro, o, name) \
4286    macro(o, Float##name, f, float, PrintFloat) \
4287    macro(o, Double##name, d, double, PrintDouble)
4288
4289 // binary arithmetic
4290 OPERATOR_ALL(BINARY, +, Add)
4291 OPERATOR_ALL(BINARY, -, Sub)
4292 OPERATOR_ALL(BINARY, *, Mul)
4293 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4294 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4295 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4296
4297 // unary arithmetic
4298 OPERATOR_ALL(UNARY, -, Neg)
4299
4300 // unary arithmetic increment and decrement
4301 OPERATOR_ALL(UNARY, ++, Inc)
4302 OPERATOR_ALL(UNARY, --, Dec)
4303
4304 // binary arithmetic assignment
4305 OPERATOR_ALL(BINARY, =, Asign)
4306 OPERATOR_ALL(BINARY, +=, AddAsign)
4307 OPERATOR_ALL(BINARY, -=, SubAsign)
4308 OPERATOR_ALL(BINARY, *=, MulAsign)
4309 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4310 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4311 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4312
4313 // binary bitwise
4314 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4315 OPERATOR_INTTYPES(BINARY, |, BitOr)
4316 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4317 OPERATOR_INTTYPES(BINARY, <<, LShift)
4318 OPERATOR_INTTYPES(BINARY, >>, RShift)
4319
4320 // unary bitwise
4321 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4322
4323 // binary bitwise assignment
4324 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4325 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4326 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4327 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4328 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4329
4330 // unary logical negation
4331 OPERATOR_INTTYPES(UNARY, !, Not)
4332
4333 // binary logical equality
4334 OPERATOR_ALL(BINARY, ==, Equ)
4335 OPERATOR_ALL(BINARY, !=, Nqu)
4336
4337 // binary logical
4338 OPERATOR_ALL(BINARY, &&, And)
4339 OPERATOR_ALL(BINARY, ||, Or)
4340
4341 // binary logical relational
4342 OPERATOR_ALL(BINARY, >, Grt)
4343 OPERATOR_ALL(BINARY, <, Sma)
4344 OPERATOR_ALL(BINARY, >=, GrtEqu)
4345 OPERATOR_ALL(BINARY, <=, SmaEqu)
4346
4347 // tertiary condition operator
4348 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4349
4350 //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
4351 #define OPERATOR_TABLE_ALL(name, type) \
4352     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4353                           type##Neg, \
4354                           type##Inc, type##Dec, \
4355                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4356                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4357                           type##BitNot, \
4358                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4359                           type##Not, \
4360                           type##Equ, type##Nqu, \
4361                           type##And, type##Or, \
4362                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4363                         }; \
4364
4365 #define OPERATOR_TABLE_INTTYPES(name, type) \
4366     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4367                           type##Neg, \
4368                           type##Inc, type##Dec, \
4369                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4370                           null, null, null, null, null, \
4371                           null, \
4372                           null, null, null, null, null, \
4373                           null, \
4374                           type##Equ, type##Nqu, \
4375                           type##And, type##Or, \
4376                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4377                         }; \
4378
4379 OPERATOR_TABLE_ALL(int, Int)
4380 OPERATOR_TABLE_ALL(uint, UInt)
4381 OPERATOR_TABLE_ALL(int64, Int64)
4382 OPERATOR_TABLE_ALL(uint64, UInt64)
4383 OPERATOR_TABLE_ALL(short, Short)
4384 OPERATOR_TABLE_ALL(ushort, UShort)
4385 OPERATOR_TABLE_INTTYPES(float, Float)
4386 OPERATOR_TABLE_INTTYPES(double, Double)
4387 OPERATOR_TABLE_ALL(char, Char)
4388 OPERATOR_TABLE_ALL(uchar, UChar)
4389
4390 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4391 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4392 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4393 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4394 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4395 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4396 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4397 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4398
4399 public void ReadString(char * output,  char * string)
4400 {
4401    int len = strlen(string);
4402    int c,d = 0;
4403    bool quoted = false, escaped = false;
4404    for(c = 0; c<len; c++)
4405    {
4406       char ch = string[c];
4407       if(escaped)
4408       {
4409          switch(ch)
4410          {
4411             case 'n': output[d] = '\n'; break;
4412             case 't': output[d] = '\t'; break;
4413             case 'a': output[d] = '\a'; break;
4414             case 'b': output[d] = '\b'; break;
4415             case 'f': output[d] = '\f'; break;
4416             case 'r': output[d] = '\r'; break;
4417             case 'v': output[d] = '\v'; break;
4418             case '\\': output[d] = '\\'; break;
4419             case '\"': output[d] = '\"'; break;
4420             case '\'': output[d] = '\''; break;
4421             default: output[d] = ch;
4422          }
4423          d++;
4424          escaped = false;
4425       }
4426       else
4427       {
4428          if(ch == '\"')
4429             quoted ^= true;
4430          else if(quoted)
4431          {
4432             if(ch == '\\')
4433                escaped = true;
4434             else
4435                output[d++] = ch;
4436          }
4437       }
4438    }
4439    output[d] = '\0';
4440 }
4441
4442 // String Unescape Copy
4443
4444 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4445 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4446 public int UnescapeString(char * d, char * s, int len)
4447 {
4448    int j = 0, k = 0;
4449    char ch;
4450    while(j < len && (ch = s[j]))
4451    {
4452       switch(ch)
4453       {
4454          case '\\':
4455             switch((ch = s[++j]))
4456             {
4457                case 'n': d[k] = '\n'; break;
4458                case 't': d[k] = '\t'; break;
4459                case 'a': d[k] = '\a'; break;
4460                case 'b': d[k] = '\b'; break;
4461                case 'f': d[k] = '\f'; break;
4462                case 'r': d[k] = '\r'; break;
4463                case 'v': d[k] = '\v'; break;
4464                case '\\': d[k] = '\\'; break;
4465                case '\"': d[k] = '\"'; break;
4466                case '\'': d[k] = '\''; break;
4467                default: d[k] = '\\'; d[k] = ch;
4468             }
4469             break;
4470          default:
4471             d[k] = ch;
4472       }
4473       j++, k++;
4474    }
4475    d[k] = '\0';
4476    return k;
4477 }
4478
4479 public char * OffsetEscapedString(char * s, int len, int offset)
4480 {
4481    char ch;
4482    int j = 0, k = 0;
4483    while(j < len && k < offset && (ch = s[j]))
4484    {
4485       if(ch == '\\') ++j;
4486       j++, k++;
4487    }
4488    return (k == offset) ? s + j : null;
4489 }
4490
4491 public Operand GetOperand(Expression exp)
4492 {
4493    Operand op { };
4494    Type type = exp.expType;
4495    if(type)
4496    {
4497       while(type.kind == classType &&
4498          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4499       {
4500          if(!type._class.registered.dataType)
4501             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4502          type = type._class.registered.dataType;
4503
4504       }
4505       if(exp.type == stringExp && op.kind == pointerType)
4506       {
4507          op.ui64 = (uint64)exp.string;
4508          op.kind = pointerType;
4509          op.ops = uint64Ops;
4510       }
4511       else if(exp.isConstant && exp.type == constantExp)
4512       {
4513          op.kind = type.kind;
4514          op.type = type;
4515
4516          switch(op.kind)
4517          {
4518             case _BoolType:
4519             case charType:
4520             {
4521                if(exp.constant[0] == '\'')
4522                {
4523                   op.c = exp.constant[1];
4524                   op.ops = charOps;
4525                }
4526                else if(type.isSigned)
4527                {
4528                   op.c = (char)strtol(exp.constant, null, 0);
4529                   op.ops = charOps;
4530                }
4531                else
4532                {
4533                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4534                   op.ops = ucharOps;
4535                }
4536                break;
4537             }
4538             case shortType:
4539                if(type.isSigned)
4540                {
4541                   op.s = (short)strtol(exp.constant, null, 0);
4542                   op.ops = shortOps;
4543                }
4544                else
4545                {
4546                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4547                   op.ops = ushortOps;
4548                }
4549                break;
4550             case intType:
4551             case longType:
4552                if(type.isSigned)
4553                {
4554                   op.i = (int)strtol(exp.constant, null, 0);
4555                   op.ops = intOps;
4556                }
4557                else
4558                {
4559                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4560                   op.ops = uintOps;
4561                }
4562                op.kind = intType;
4563                break;
4564             case int64Type:
4565                if(type.isSigned)
4566                {
4567                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4568                   op.ops = int64Ops;
4569                }
4570                else
4571                {
4572                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4573                   op.ops = uint64Ops;
4574                }
4575                op.kind = int64Type;
4576                break;
4577             case intPtrType:
4578                if(type.isSigned)
4579                {
4580                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4581                   op.ops = int64Ops;
4582                }
4583                else
4584                {
4585                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4586                   op.ops = uint64Ops;
4587                }
4588                op.kind = int64Type;
4589                break;
4590             case intSizeType:
4591                if(type.isSigned)
4592                {
4593                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4594                   op.ops = int64Ops;
4595                }
4596                else
4597                {
4598                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4599                   op.ops = uint64Ops;
4600                }
4601                op.kind = int64Type;
4602                break;
4603             case floatType:
4604                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4605                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4606                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4607                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4608                else
4609                   op.f = (float)strtod(exp.constant, null);
4610                op.ops = floatOps;
4611                break;
4612             case doubleType:
4613                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4614                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4615                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4616                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4617                else
4618                   op.d = (double)strtod(exp.constant, null);
4619                op.ops = doubleOps;
4620                break;
4621             //case classType:    For when we have operator overloading...
4622             // Pointer additions
4623             //case functionType:
4624             case arrayType:
4625             case pointerType:
4626             case classType:
4627                op.ui64 = _strtoui64(exp.constant, null, 0);
4628                op.kind = pointerType;
4629                op.ops = uint64Ops;
4630                // op.ptrSize =
4631                break;
4632          }
4633       }
4634    }
4635    return op;
4636 }
4637
4638 static int64 GetEnumValue(Class _class, void * ptr)
4639 {
4640    int64 v = 0;
4641    switch(_class.typeSize)
4642    {
4643       case 8:
4644          if(!strcmp(_class.dataTypeString, "uint64"))
4645             v = (int64)*(uint64 *)ptr;
4646          else
4647             v = (int64)*(int64 *)ptr;
4648          break;
4649       case 4:
4650          if(!strcmp(_class.dataTypeString, "uint"))
4651             v = (int64)*(uint *)ptr;
4652          else
4653             v = (int64)*(int *)ptr;
4654          break;
4655       case 2:
4656          if(!strcmp(_class.dataTypeString, "uint16"))
4657             v = (int64)*(uint16 *)ptr;
4658          else
4659             v = (int64)*(short *)ptr;
4660          break;
4661       case 1:
4662          if(!strcmp(_class.dataTypeString, "byte"))
4663             v = (int64)*(byte *)ptr;
4664          else
4665             v = (int64)*(char *)ptr;
4666          break;
4667    }
4668    return v;
4669 }
4670
4671 static __attribute__((unused)) void UnusedFunction()
4672 {
4673    int a;
4674    a.OnGetString(0,0,0);
4675 }
4676 default:
4677 extern int __ecereVMethodID_class_OnGetString;
4678 public:
4679
4680 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4681 {
4682    DataMember dataMember;
4683    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4684    {
4685       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4686          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4687       else
4688       {
4689          Expression exp { };
4690          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4691          Type type;
4692          void * ptr = inst.data + dataMember.offset + offset;
4693          char * result = null;
4694          exp.loc = member.loc = inst.loc;
4695          ((Identifier)member.identifiers->first).loc = inst.loc;
4696
4697          if(!dataMember.dataType)
4698             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4699          type = dataMember.dataType;
4700          if(type.kind == classType)
4701          {
4702             Class _class = type._class.registered;
4703             if(_class.type == enumClass)
4704             {
4705                Class enumClass = eSystem_FindClass(privateModule, "enum");
4706                if(enumClass)
4707                {
4708                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4709                   NamedLink64 item;
4710                   for(item = e.values.first; item; item = item.next)
4711                   {
4712                      if(item.data == GetEnumValue(_class, ptr))
4713                      {
4714                         result = item.name;
4715                         break;
4716                      }
4717                   }
4718                   if(result)
4719                   {
4720                      exp.identifier = MkIdentifier(result);
4721                      exp.type = identifierExp;
4722                      exp.destType = MkClassType(_class.fullName);
4723                      ProcessExpressionType(exp);
4724                   }
4725                }
4726             }
4727             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4728             {
4729                if(!_class.dataType)
4730                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4731                type = _class.dataType;
4732             }
4733          }
4734          if(!result)
4735          {
4736             switch(type.kind)
4737             {
4738                case floatType:
4739                {
4740                   FreeExpContents(exp);
4741
4742                   exp.constant = PrintFloat(*(float*)ptr);
4743                   exp.type = constantExp;
4744                   break;
4745                }
4746                case doubleType:
4747                {
4748                   FreeExpContents(exp);
4749
4750                   exp.constant = PrintDouble(*(double*)ptr);
4751                   exp.type = constantExp;
4752                   break;
4753                }
4754                case intType:
4755                {
4756                   FreeExpContents(exp);
4757
4758                   exp.constant = PrintInt(*(int*)ptr);
4759                   exp.type = constantExp;
4760                   break;
4761                }
4762                case int64Type:
4763                {
4764                   FreeExpContents(exp);
4765
4766                   exp.constant = PrintInt64(*(int64*)ptr);
4767                   exp.type = constantExp;
4768                   break;
4769                }
4770                case intPtrType:
4771                {
4772                   FreeExpContents(exp);
4773                   // TODO: This should probably use proper type
4774                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4775                   exp.type = constantExp;
4776                   break;
4777                }
4778                case intSizeType:
4779                {
4780                   FreeExpContents(exp);
4781                   // TODO: This should probably use proper type
4782                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4783                   exp.type = constantExp;
4784                   break;
4785                }
4786                default:
4787                   Compiler_Error($"Unhandled type populating instance\n");
4788             }
4789          }
4790          ListAdd(memberList, member);
4791       }
4792
4793       if(parentDataMember.type == unionMember)
4794          break;
4795    }
4796 }
4797
4798 void PopulateInstance(Instantiation inst)
4799 {
4800    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4801    Class _class = classSym.registered;
4802    DataMember dataMember;
4803    OldList * memberList = MkList();
4804    // Added this check and ->Add to prevent memory leaks on bad code
4805    if(!inst.members)
4806       inst.members = MkListOne(MkMembersInitList(memberList));
4807    else
4808       inst.members->Add(MkMembersInitList(memberList));
4809    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4810    {
4811       if(!dataMember.isProperty)
4812       {
4813          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4814             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4815          else
4816          {
4817             Expression exp { };
4818             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4819             Type type;
4820             void * ptr = inst.data + dataMember.offset;
4821             char * result = null;
4822
4823             exp.loc = member.loc = inst.loc;
4824             ((Identifier)member.identifiers->first).loc = inst.loc;
4825
4826             if(!dataMember.dataType)
4827                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4828             type = dataMember.dataType;
4829             if(type.kind == classType)
4830             {
4831                Class _class = type._class.registered;
4832                if(_class.type == enumClass)
4833                {
4834                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4835                   if(enumClass)
4836                   {
4837                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4838                      NamedLink64 item;
4839                      for(item = e.values.first; item; item = item.next)
4840                      {
4841                         if(item.data == GetEnumValue(_class, ptr))
4842                         {
4843                            result = item.name;
4844                            break;
4845                         }
4846                      }
4847                   }
4848                   if(result)
4849                   {
4850                      exp.identifier = MkIdentifier(result);
4851                      exp.type = identifierExp;
4852                      exp.destType = MkClassType(_class.fullName);
4853                      ProcessExpressionType(exp);
4854                   }
4855                }
4856                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4857                {
4858                   if(!_class.dataType)
4859                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4860                   type = _class.dataType;
4861                }
4862             }
4863             if(!result)
4864             {
4865                switch(type.kind)
4866                {
4867                   case floatType:
4868                   {
4869                      exp.constant = PrintFloat(*(float*)ptr);
4870                      exp.type = constantExp;
4871                      break;
4872                   }
4873                   case doubleType:
4874                   {
4875                      exp.constant = PrintDouble(*(double*)ptr);
4876                      exp.type = constantExp;
4877                      break;
4878                   }
4879                   case intType:
4880                   {
4881                      exp.constant = PrintInt(*(int*)ptr);
4882                      exp.type = constantExp;
4883                      break;
4884                   }
4885                   case int64Type:
4886                   {
4887                      exp.constant = PrintInt64(*(int64*)ptr);
4888                      exp.type = constantExp;
4889                      break;
4890                   }
4891                   case intPtrType:
4892                   {
4893                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4894                      exp.type = constantExp;
4895                      break;
4896                   }
4897                   default:
4898                      Compiler_Error($"Unhandled type populating instance\n");
4899                }
4900             }
4901             ListAdd(memberList, member);
4902          }
4903       }
4904    }
4905 }
4906
4907 void ComputeInstantiation(Expression exp)
4908 {
4909    Instantiation inst = exp.instance;
4910    MembersInit members;
4911    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4912    Class _class = classSym ? classSym.registered : null;
4913    DataMember curMember = null;
4914    Class curClass = null;
4915    DataMember subMemberStack[256];
4916    int subMemberStackPos = 0;
4917    uint64 bits = 0;
4918
4919    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4920    {
4921       // Don't recompute the instantiation...
4922       // Non Simple classes will have become constants by now
4923       if(inst.data)
4924          return;
4925
4926       if(_class.type == normalClass || _class.type == noHeadClass)
4927       {
4928          inst.data = (byte *)eInstance_New(_class);
4929          if(_class.type == normalClass)
4930             ((Instance)inst.data)._refCount++;
4931       }
4932       else
4933          inst.data = new0 byte[_class.structSize];
4934    }
4935
4936    if(inst.members)
4937    {
4938       for(members = inst.members->first; members; members = members.next)
4939       {
4940          switch(members.type)
4941          {
4942             case dataMembersInit:
4943             {
4944                if(members.dataMembers)
4945                {
4946                   MemberInit member;
4947                   for(member = members.dataMembers->first; member; member = member.next)
4948                   {
4949                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4950                      bool found = false;
4951
4952                      Property prop = null;
4953                      DataMember dataMember = null;
4954                      uint dataMemberOffset;
4955
4956                      if(!ident)
4957                      {
4958                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4959                         if(curMember)
4960                         {
4961                            if(curMember.isProperty)
4962                               prop = (Property)curMember;
4963                            else
4964                            {
4965                               dataMember = curMember;
4966
4967                               // CHANGED THIS HERE
4968                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4969
4970                               // 2013/17/29 -- It seems that this was missing here!
4971                               if(_class.type == normalClass)
4972                                  dataMemberOffset += _class.base.structSize;
4973                               // dataMemberOffset = dataMember.offset;
4974                            }
4975                            found = true;
4976                         }
4977                      }
4978                      else
4979                      {
4980                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4981                         if(prop)
4982                         {
4983                            found = true;
4984                            if(prop.memberAccess == publicAccess)
4985                            {
4986                               curMember = (DataMember)prop;
4987                               curClass = prop._class;
4988                            }
4989                         }
4990                         else
4991                         {
4992                            DataMember _subMemberStack[256];
4993                            int _subMemberStackPos = 0;
4994
4995                            // FILL MEMBER STACK
4996                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4997
4998                            if(dataMember)
4999                            {
5000                               found = true;
5001                               if(dataMember.memberAccess == publicAccess)
5002                               {
5003                                  curMember = dataMember;
5004                                  curClass = dataMember._class;
5005                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
5006                                  subMemberStackPos = _subMemberStackPos;
5007                               }
5008                            }
5009                         }
5010                      }
5011
5012                      if(found && member.initializer && member.initializer.type == expInitializer)
5013                      {
5014                         Expression value = member.initializer.exp;
5015                         Type type = null;
5016                         bool deepMember = false;
5017                         if(prop)
5018                         {
5019                            type = prop.dataType;
5020                         }
5021                         else if(dataMember)
5022                         {
5023                            if(!dataMember.dataType)
5024                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
5025
5026                            type = dataMember.dataType;
5027                         }
5028
5029                         if(ident && ident.next)
5030                         {
5031                            deepMember = true;
5032
5033                            // for(; ident && type; ident = ident.next)
5034                            for(ident = ident.next; ident && type; ident = ident.next)
5035                            {
5036                               if(type.kind == classType)
5037                               {
5038                                  prop = eClass_FindProperty(type._class.registered,
5039                                     ident.string, privateModule);
5040                                  if(prop)
5041                                     type = prop.dataType;
5042                                  else
5043                                  {
5044                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
5045                                        ident.string, &dataMemberOffset, privateModule, null, null);
5046                                     if(dataMember)
5047                                        type = dataMember.dataType;
5048                                  }
5049                               }
5050                               else if(type.kind == structType || type.kind == unionType)
5051                               {
5052                                  Type memberType;
5053                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
5054                                  {
5055                                     if(!strcmp(memberType.name, ident.string))
5056                                     {
5057                                        type = memberType;
5058                                        break;
5059                                     }
5060                                  }
5061                               }
5062                            }
5063                         }
5064                         if(value)
5065                         {
5066                            FreeType(value.destType);
5067                            value.destType = type;
5068                            if(type) type.refCount++;
5069                            ComputeExpression(value);
5070                         }
5071                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
5072                         {
5073                            if(type.kind == classType)
5074                            {
5075                               Class _class = type._class.registered;
5076                               if(_class.type == bitClass || _class.type == unitClass ||
5077                                  _class.type == enumClass)
5078                               {
5079                                  if(!_class.dataType)
5080                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5081                                  type = _class.dataType;
5082                               }
5083                            }
5084
5085                            if(dataMember)
5086                            {
5087                               void * ptr = inst.data + dataMemberOffset;
5088
5089                               if(value.type == constantExp)
5090                               {
5091                                  switch(type.kind)
5092                                  {
5093                                     case intType:
5094                                     {
5095                                        GetInt(value, (int*)ptr);
5096                                        break;
5097                                     }
5098                                     case int64Type:
5099                                     {
5100                                        GetInt64(value, (int64*)ptr);
5101                                        break;
5102                                     }
5103                                     case intPtrType:
5104                                     {
5105                                        GetIntPtr(value, (intptr*)ptr);
5106                                        break;
5107                                     }
5108                                     case intSizeType:
5109                                     {
5110                                        GetIntSize(value, (intsize*)ptr);
5111                                        break;
5112                                     }
5113                                     case floatType:
5114                                     {
5115                                        GetFloat(value, (float*)ptr);
5116                                        break;
5117                                     }
5118                                     case doubleType:
5119                                     {
5120                                        GetDouble(value, (double *)ptr);
5121                                        break;
5122                                     }
5123                                  }
5124                               }
5125                               else if(value.type == instanceExp)
5126                               {
5127                                  if(type.kind == classType)
5128                                  {
5129                                     Class _class = type._class.registered;
5130                                     if(_class.type == structClass)
5131                                     {
5132                                        ComputeTypeSize(type);
5133                                        if(value.instance.data)
5134                                           memcpy(ptr, value.instance.data, type.size);
5135                                     }
5136                                  }
5137                               }
5138                            }
5139                            else if(prop)
5140                            {
5141                               if(value.type == instanceExp && value.instance.data)
5142                               {
5143                                  if(type.kind == classType)
5144                                  {
5145                                     Class _class = type._class.registered;
5146                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5147                                     {
5148                                        void (*Set)(void *, void *) = (void *)prop.Set;
5149                                        Set(inst.data, value.instance.data);
5150                                        PopulateInstance(inst);
5151                                     }
5152                                  }
5153                               }
5154                               else if(value.type == constantExp)
5155                               {
5156                                  switch(type.kind)
5157                                  {
5158                                     case doubleType:
5159                                     {
5160                                        void (*Set)(void *, double) = (void *)prop.Set;
5161                                        Set(inst.data, strtod(value.constant, null) );
5162                                        break;
5163                                     }
5164                                     case floatType:
5165                                     {
5166                                        void (*Set)(void *, float) = (void *)prop.Set;
5167                                        Set(inst.data, (float)(strtod(value.constant, null)));
5168                                        break;
5169                                     }
5170                                     case intType:
5171                                     {
5172                                        void (*Set)(void *, int) = (void *)prop.Set;
5173                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5174                                        break;
5175                                     }
5176                                     case int64Type:
5177                                     {
5178                                        void (*Set)(void *, int64) = (void *)prop.Set;
5179                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5180                                        break;
5181                                     }
5182                                     case intPtrType:
5183                                     {
5184                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5185                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5186                                        break;
5187                                     }
5188                                     case intSizeType:
5189                                     {
5190                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5191                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5192                                        break;
5193                                     }
5194                                  }
5195                               }
5196                               else if(value.type == stringExp)
5197                               {
5198                                  char temp[1024];
5199                                  ReadString(temp, value.string);
5200                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5201                               }
5202                            }
5203                         }
5204                         else if(!deepMember && type && _class.type == unitClass)
5205                         {
5206                            if(prop)
5207                            {
5208                               // Only support converting units to units for now...
5209                               if(value.type == constantExp)
5210                               {
5211                                  if(type.kind == classType)
5212                                  {
5213                                     Class _class = type._class.registered;
5214                                     if(_class.type == unitClass)
5215                                     {
5216                                        if(!_class.dataType)
5217                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5218                                        type = _class.dataType;
5219                                     }
5220                                  }
5221                                  // TODO: Assuming same base type for units...
5222                                  switch(type.kind)
5223                                  {
5224                                     case floatType:
5225                                     {
5226                                        float fValue;
5227                                        float (*Set)(float) = (void *)prop.Set;
5228                                        GetFloat(member.initializer.exp, &fValue);
5229                                        exp.constant = PrintFloat(Set(fValue));
5230                                        exp.type = constantExp;
5231                                        break;
5232                                     }
5233                                     case doubleType:
5234                                     {
5235                                        double dValue;
5236                                        double (*Set)(double) = (void *)prop.Set;
5237                                        GetDouble(member.initializer.exp, &dValue);
5238                                        exp.constant = PrintDouble(Set(dValue));
5239                                        exp.type = constantExp;
5240                                        break;
5241                                     }
5242                                  }
5243                               }
5244                            }
5245                         }
5246                         else if(!deepMember && type && _class.type == bitClass)
5247                         {
5248                            if(prop)
5249                            {
5250                               if(value.type == instanceExp && value.instance.data)
5251                               {
5252                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5253                                  bits = Set(value.instance.data);
5254                               }
5255                               else if(value.type == constantExp)
5256                               {
5257                               }
5258                            }
5259                            else if(dataMember)
5260                            {
5261                               BitMember bitMember = (BitMember) dataMember;
5262                               Type type;
5263                               uint64 part = 0;
5264                               bits = (bits & ~bitMember.mask);
5265                               if(!bitMember.dataType)
5266                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5267                               type = bitMember.dataType;
5268                               if(type.kind == classType && type._class && type._class.registered)
5269                               {
5270                                  if(!type._class.registered.dataType)
5271                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5272                                  type = type._class.registered.dataType;
5273                               }
5274                               switch(type.kind)
5275                               {
5276                                  case _BoolType:
5277                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5278                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5279                                  case intType:
5280                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5281                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5282                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5283                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5284                               }
5285                               bits |= part << bitMember.pos;
5286                            }
5287                         }
5288                      }
5289                      else
5290                      {
5291                         if(_class && _class.type == unitClass)
5292                         {
5293                            ComputeExpression(member.initializer.exp);
5294                            exp.constant = member.initializer.exp.constant;
5295                            exp.type = constantExp;
5296
5297                            member.initializer.exp.constant = null;
5298                         }
5299                      }
5300                   }
5301                }
5302                break;
5303             }
5304          }
5305       }
5306    }
5307    if(_class && _class.type == bitClass)
5308    {
5309       exp.constant = PrintHexUInt(bits);
5310       exp.type = constantExp;
5311    }
5312    if(exp.type != instanceExp)
5313    {
5314       FreeInstance(inst);
5315    }
5316 }
5317
5318 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5319 {
5320    bool result = false;
5321    switch(kind)
5322    {
5323       case shortType:
5324          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5325             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5326          break;
5327       case intType:
5328       case longType:
5329          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5330             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5331          break;
5332       case int64Type:
5333          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5334             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5335             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5336          break;
5337       case floatType:
5338          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5339             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5340             result = GetOpFloat(op, &op.f);
5341          break;
5342       case doubleType:
5343          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5344             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5345             result = GetOpDouble(op, &op.d);
5346          break;
5347       case pointerType:
5348          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5349             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5350             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5351          break;
5352       case enumType:
5353          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5354             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5355             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5356          break;
5357       case intPtrType:
5358          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5359             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5360          break;
5361       case intSizeType:
5362          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5363             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5364          break;
5365    }
5366    return result;
5367 }
5368
5369 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5370 {
5371    if(exp.op.op == SIZEOF)
5372    {
5373       FreeExpContents(exp);
5374       exp.type = constantExp;
5375       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5376    }
5377    else
5378    {
5379       if(!exp.op.exp1)
5380       {
5381          switch(exp.op.op)
5382          {
5383             // unary arithmetic
5384             case '+':
5385             {
5386                // Provide default unary +
5387                Expression exp2 = exp.op.exp2;
5388                exp.op.exp2 = null;
5389                FreeExpContents(exp);
5390                FreeType(exp.expType);
5391                FreeType(exp.destType);
5392                *exp = *exp2;
5393                delete exp2;
5394                break;
5395             }
5396             case '-':
5397                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5398                break;
5399             // unary arithmetic increment and decrement
5400                   //OPERATOR_ALL(UNARY, ++, Inc)
5401                   //OPERATOR_ALL(UNARY, --, Dec)
5402             // unary bitwise
5403             case '~':
5404                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5405                break;
5406             // unary logical negation
5407             case '!':
5408                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5409                break;
5410          }
5411       }
5412       else
5413       {
5414          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5415          {
5416             if(Promote(op2, op1.kind, op1.type.isSigned))
5417                op2.kind = op1.kind, op2.ops = op1.ops;
5418             else if(Promote(op1, op2.kind, op2.type.isSigned))
5419                op1.kind = op2.kind, op1.ops = op2.ops;
5420          }
5421          switch(exp.op.op)
5422          {
5423             // binary arithmetic
5424             case '+':
5425                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5426                break;
5427             case '-':
5428                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5429                break;
5430             case '*':
5431                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5432                break;
5433             case '/':
5434                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5435                break;
5436             case '%':
5437                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5438                break;
5439             // binary arithmetic assignment
5440                   //OPERATOR_ALL(BINARY, =, Asign)
5441                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5442                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5443                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5444                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5445                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5446             // binary bitwise
5447             case '&':
5448                if(exp.op.exp2)
5449                {
5450                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5451                }
5452                break;
5453             case '|':
5454                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5455                break;
5456             case '^':
5457                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5458                break;
5459             case LEFT_OP:
5460                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5461                break;
5462             case RIGHT_OP:
5463                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5464                break;
5465             // binary bitwise assignment
5466                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5467                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5468                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5469                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5470                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5471             // binary logical equality
5472             case EQ_OP:
5473                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5474                break;
5475             case NE_OP:
5476                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5477                break;
5478             // binary logical
5479             case AND_OP:
5480                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5481                break;
5482             case OR_OP:
5483                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5484                break;
5485             // binary logical relational
5486             case '>':
5487                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5488                break;
5489             case '<':
5490                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5491                break;
5492             case GE_OP:
5493                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5494                break;
5495             case LE_OP:
5496                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5497                break;
5498          }
5499       }
5500    }
5501 }
5502
5503 void ComputeExpression(Expression exp)
5504 {
5505 #ifdef _DEBUG
5506    char expString[10240];
5507    expString[0] = '\0';
5508    PrintExpression(exp, expString);
5509 #endif
5510
5511    switch(exp.type)
5512    {
5513       case instanceExp:
5514       {
5515          ComputeInstantiation(exp);
5516          break;
5517       }
5518       /*
5519       case constantExp:
5520          break;
5521       */
5522       case opExp:
5523       {
5524          Expression exp1, exp2 = null;
5525          Operand op1 { };
5526          Operand op2 { };
5527
5528          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5529          if(exp.op.exp2)
5530          {
5531             Expression e = exp.op.exp2;
5532
5533             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5534             {
5535                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5536                {
5537                   if(e.type == extensionCompoundExp)
5538                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5539                   else
5540                      e = e.list->last;
5541                }
5542             }
5543             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5544             {
5545                if(e.type == stringExp && e.string)
5546                {
5547                   char * string = e.string;
5548                   int len = strlen(string);
5549                   char * tmp = new char[len-2+1];
5550                   len = UnescapeString(tmp, string + 1, len - 2);
5551                   delete tmp;
5552                   FreeExpContents(exp);
5553                   exp.type = constantExp;
5554                   exp.constant = PrintUInt(len + 1);
5555                }
5556                else
5557                {
5558                   Type type = e.expType;
5559                   type.refCount++;
5560                   FreeExpContents(exp);
5561                   exp.type = constantExp;
5562                   exp.constant = PrintUInt(ComputeTypeSize(type));
5563                   FreeType(type);
5564                }
5565                break;
5566             }
5567             else
5568                ComputeExpression(exp.op.exp2);
5569          }
5570          if(exp.op.exp1)
5571          {
5572             ComputeExpression(exp.op.exp1);
5573             exp1 = exp.op.exp1;
5574             exp2 = exp.op.exp2;
5575             op1 = GetOperand(exp1);
5576             if(op1.type) op1.type.refCount++;
5577             if(exp2)
5578             {
5579                op2 = GetOperand(exp2);
5580                if(op2.type) op2.type.refCount++;
5581             }
5582          }
5583          else
5584          {
5585             exp1 = exp.op.exp2;
5586             op1 = GetOperand(exp1);
5587             if(op1.type) op1.type.refCount++;
5588          }
5589
5590          CallOperator(exp, exp1, exp2, op1, op2);
5591          /*
5592          switch(exp.op.op)
5593          {
5594             // Unary operators
5595             case '&':
5596                // Also binary
5597                if(exp.op.exp1 && exp.op.exp2)
5598                {
5599                   // Binary And
5600                   if(op1.ops.BitAnd)
5601                   {
5602                      FreeExpContents(exp);
5603                      op1.ops.BitAnd(exp, op1, op2);
5604                   }
5605                }
5606                break;
5607             case '*':
5608                if(exp.op.exp1)
5609                {
5610                   if(op1.ops.Mul)
5611                   {
5612                      FreeExpContents(exp);
5613                      op1.ops.Mul(exp, op1, op2);
5614                   }
5615                }
5616                break;
5617             case '+':
5618                if(exp.op.exp1)
5619                {
5620                   if(op1.ops.Add)
5621                   {
5622                      FreeExpContents(exp);
5623                      op1.ops.Add(exp, op1, op2);
5624                   }
5625                }
5626                else
5627                {
5628                   // Provide default unary +
5629                   Expression exp2 = exp.op.exp2;
5630                   exp.op.exp2 = null;
5631                   FreeExpContents(exp);
5632                   FreeType(exp.expType);
5633                   FreeType(exp.destType);
5634
5635                   *exp = *exp2;
5636                   delete exp2;
5637                }
5638                break;
5639             case '-':
5640                if(exp.op.exp1)
5641                {
5642                   if(op1.ops.Sub)
5643                   {
5644                      FreeExpContents(exp);
5645                      op1.ops.Sub(exp, op1, op2);
5646                   }
5647                }
5648                else
5649                {
5650                   if(op1.ops.Neg)
5651                   {
5652                      FreeExpContents(exp);
5653                      op1.ops.Neg(exp, op1);
5654                   }
5655                }
5656                break;
5657             case '~':
5658                if(op1.ops.BitNot)
5659                {
5660                   FreeExpContents(exp);
5661                   op1.ops.BitNot(exp, op1);
5662                }
5663                break;
5664             case '!':
5665                if(op1.ops.Not)
5666                {
5667                   FreeExpContents(exp);
5668                   op1.ops.Not(exp, op1);
5669                }
5670                break;
5671             // Binary only operators
5672             case '/':
5673                if(op1.ops.Div)
5674                {
5675                   FreeExpContents(exp);
5676                   op1.ops.Div(exp, op1, op2);
5677                }
5678                break;
5679             case '%':
5680                if(op1.ops.Mod)
5681                {
5682                   FreeExpContents(exp);
5683                   op1.ops.Mod(exp, op1, op2);
5684                }
5685                break;
5686             case LEFT_OP:
5687                break;
5688             case RIGHT_OP:
5689                break;
5690             case '<':
5691                if(exp.op.exp1)
5692                {
5693                   if(op1.ops.Sma)
5694                   {
5695                      FreeExpContents(exp);
5696                      op1.ops.Sma(exp, op1, op2);
5697                   }
5698                }
5699                break;
5700             case '>':
5701                if(exp.op.exp1)
5702                {
5703                   if(op1.ops.Grt)
5704                   {
5705                      FreeExpContents(exp);
5706                      op1.ops.Grt(exp, op1, op2);
5707                   }
5708                }
5709                break;
5710             case LE_OP:
5711                if(exp.op.exp1)
5712                {
5713                   if(op1.ops.SmaEqu)
5714                   {
5715                      FreeExpContents(exp);
5716                      op1.ops.SmaEqu(exp, op1, op2);
5717                   }
5718                }
5719                break;
5720             case GE_OP:
5721                if(exp.op.exp1)
5722                {
5723                   if(op1.ops.GrtEqu)
5724                   {
5725                      FreeExpContents(exp);
5726                      op1.ops.GrtEqu(exp, op1, op2);
5727                   }
5728                }
5729                break;
5730             case EQ_OP:
5731                if(exp.op.exp1)
5732                {
5733                   if(op1.ops.Equ)
5734                   {
5735                      FreeExpContents(exp);
5736                      op1.ops.Equ(exp, op1, op2);
5737                   }
5738                }
5739                break;
5740             case NE_OP:
5741                if(exp.op.exp1)
5742                {
5743                   if(op1.ops.Nqu)
5744                   {
5745                      FreeExpContents(exp);
5746                      op1.ops.Nqu(exp, op1, op2);
5747                   }
5748                }
5749                break;
5750             case '|':
5751                if(op1.ops.BitOr)
5752                {
5753                   FreeExpContents(exp);
5754                   op1.ops.BitOr(exp, op1, op2);
5755                }
5756                break;
5757             case '^':
5758                if(op1.ops.BitXor)
5759                {
5760                   FreeExpContents(exp);
5761                   op1.ops.BitXor(exp, op1, op2);
5762                }
5763                break;
5764             case AND_OP:
5765                break;
5766             case OR_OP:
5767                break;
5768             case SIZEOF:
5769                FreeExpContents(exp);
5770                exp.type = constantExp;
5771                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5772                break;
5773          }
5774          */
5775          if(op1.type) FreeType(op1.type);
5776          if(op2.type) FreeType(op2.type);
5777          break;
5778       }
5779       case bracketsExp:
5780       case extensionExpressionExp:
5781       {
5782          Expression e, n;
5783          for(e = exp.list->first; e; e = n)
5784          {
5785             n = e.next;
5786             if(!n)
5787             {
5788                OldList * list = exp.list;
5789                Expression prev = exp.prev;
5790                Expression next = exp.next;
5791                ComputeExpression(e);
5792                //FreeExpContents(exp);
5793                FreeType(exp.expType);
5794                FreeType(exp.destType);
5795                *exp = *e;
5796                exp.prev = prev;
5797                exp.next = next;
5798                delete e;
5799                delete list;
5800             }
5801             else
5802             {
5803                FreeExpression(e);
5804             }
5805          }
5806          break;
5807       }
5808       /*
5809
5810       case ExpIndex:
5811       {
5812          Expression e;
5813          exp.isConstant = true;
5814
5815          ComputeExpression(exp.index.exp);
5816          if(!exp.index.exp.isConstant)
5817             exp.isConstant = false;
5818
5819          for(e = exp.index.index->first; e; e = e.next)
5820          {
5821             ComputeExpression(e);
5822             if(!e.next)
5823             {
5824                // Check if this type is int
5825             }
5826             if(!e.isConstant)
5827                exp.isConstant = false;
5828          }
5829          exp.expType = Dereference(exp.index.exp.expType);
5830          break;
5831       }
5832       */
5833       case memberExp:
5834       {
5835          Expression memberExp = exp.member.exp;
5836          Identifier memberID = exp.member.member;
5837
5838          Type type;
5839          ComputeExpression(exp.member.exp);
5840          type = exp.member.exp.expType;
5841          if(type)
5842          {
5843             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);
5844             Property prop = null;
5845             DataMember member = null;
5846             Class convertTo = null;
5847             if(type.kind == subClassType && exp.member.exp.type == classExp)
5848                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5849
5850             if(!_class)
5851             {
5852                char string[256];
5853                Symbol classSym;
5854                string[0] = '\0';
5855                PrintTypeNoConst(type, string, false, true);
5856                classSym = FindClass(string);
5857                _class = classSym ? classSym.registered : null;
5858             }
5859
5860             if(exp.member.member)
5861             {
5862                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5863                if(!prop)
5864                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5865             }
5866             if(!prop && !member && _class && exp.member.member)
5867             {
5868                Symbol classSym = FindClass(exp.member.member.string);
5869                convertTo = _class;
5870                _class = classSym ? classSym.registered : null;
5871                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5872             }
5873
5874             if(prop)
5875             {
5876                if(prop.compiled)
5877                {
5878                   Type type = prop.dataType;
5879                   // TODO: Assuming same base type for units...
5880                   if(_class.type == unitClass)
5881                   {
5882                      if(type.kind == classType)
5883                      {
5884                         Class _class = type._class.registered;
5885                         if(_class.type == unitClass)
5886                         {
5887                            if(!_class.dataType)
5888                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5889                            type = _class.dataType;
5890                         }
5891                      }
5892                      switch(type.kind)
5893                      {
5894                         case floatType:
5895                         {
5896                            float value;
5897                            float (*Get)(float) = (void *)prop.Get;
5898                            GetFloat(exp.member.exp, &value);
5899                            exp.constant = PrintFloat(Get ? Get(value) : value);
5900                            exp.type = constantExp;
5901                            break;
5902                         }
5903                         case doubleType:
5904                         {
5905                            double value;
5906                            double (*Get)(double);
5907                            GetDouble(exp.member.exp, &value);
5908
5909                            if(convertTo)
5910                               Get = (void *)prop.Set;
5911                            else
5912                               Get = (void *)prop.Get;
5913                            exp.constant = PrintDouble(Get ? Get(value) : value);
5914                            exp.type = constantExp;
5915                            break;
5916                         }
5917                      }
5918                   }
5919                   else
5920                   {
5921                      if(convertTo)
5922                      {
5923                         Expression value = exp.member.exp;
5924                         Type type;
5925                         if(!prop.dataType)
5926                            ProcessPropertyType(prop);
5927
5928                         type = prop.dataType;
5929                         if(!type)
5930                         {
5931                             // printf("Investigate this\n");
5932                         }
5933                         else if(_class.type == structClass)
5934                         {
5935                            switch(type.kind)
5936                            {
5937                               case classType:
5938                               {
5939                                  Class propertyClass = type._class.registered;
5940                                  if(propertyClass.type == structClass && value.type == instanceExp)
5941                                  {
5942                                     void (*Set)(void *, void *) = (void *)prop.Set;
5943                                     exp.instance = Instantiation { };
5944                                     exp.instance.data = new0 byte[_class.structSize];
5945                                     exp.instance._class = MkSpecifierName(_class.fullName);
5946                                     exp.instance.loc = exp.loc;
5947                                     exp.type = instanceExp;
5948                                     Set(exp.instance.data, value.instance.data);
5949                                     PopulateInstance(exp.instance);
5950                                  }
5951                                  break;
5952                               }
5953                               case intType:
5954                               {
5955                                  int intValue;
5956                                  void (*Set)(void *, int) = (void *)prop.Set;
5957
5958                                  exp.instance = Instantiation { };
5959                                  exp.instance.data = new0 byte[_class.structSize];
5960                                  exp.instance._class = MkSpecifierName(_class.fullName);
5961                                  exp.instance.loc = exp.loc;
5962                                  exp.type = instanceExp;
5963
5964                                  GetInt(value, &intValue);
5965
5966                                  Set(exp.instance.data, intValue);
5967                                  PopulateInstance(exp.instance);
5968                                  break;
5969                               }
5970                               case int64Type:
5971                               {
5972                                  int64 intValue;
5973                                  void (*Set)(void *, int64) = (void *)prop.Set;
5974
5975                                  exp.instance = Instantiation { };
5976                                  exp.instance.data = new0 byte[_class.structSize];
5977                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5978                                  exp.instance.loc = exp.loc;
5979                                  exp.type = instanceExp;
5980
5981                                  GetInt64(value, &intValue);
5982
5983                                  Set(exp.instance.data, intValue);
5984                                  PopulateInstance(exp.instance);
5985                                  break;
5986                               }
5987                               case intPtrType:
5988                               {
5989                                  // TOFIX:
5990                                  intptr intValue;
5991                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5992
5993                                  exp.instance = Instantiation { };
5994                                  exp.instance.data = new0 byte[_class.structSize];
5995                                  exp.instance._class = MkSpecifierName(_class.fullName);
5996                                  exp.instance.loc = exp.loc;
5997                                  exp.type = instanceExp;
5998
5999                                  GetIntPtr(value, &intValue);
6000
6001                                  Set(exp.instance.data, intValue);
6002                                  PopulateInstance(exp.instance);
6003                                  break;
6004                               }
6005                               case intSizeType:
6006                               {
6007                                  // TOFIX:
6008                                  intsize intValue;
6009                                  void (*Set)(void *, intsize) = (void *)prop.Set;
6010
6011                                  exp.instance = Instantiation { };
6012                                  exp.instance.data = new0 byte[_class.structSize];
6013                                  exp.instance._class = MkSpecifierName(_class.fullName);
6014                                  exp.instance.loc = exp.loc;
6015                                  exp.type = instanceExp;
6016
6017                                  GetIntSize(value, &intValue);
6018
6019                                  Set(exp.instance.data, intValue);
6020                                  PopulateInstance(exp.instance);
6021                                  break;
6022                               }
6023                               case floatType:
6024                               {
6025                                  float floatValue;
6026                                  void (*Set)(void *, float) = (void *)prop.Set;
6027
6028                                  exp.instance = Instantiation { };
6029                                  exp.instance.data = new0 byte[_class.structSize];
6030                                  exp.instance._class = MkSpecifierName(_class.fullName);
6031                                  exp.instance.loc = exp.loc;
6032                                  exp.type = instanceExp;
6033
6034                                  GetFloat(value, &floatValue);
6035
6036                                  Set(exp.instance.data, floatValue);
6037                                  PopulateInstance(exp.instance);
6038                                  break;
6039                               }
6040                               case doubleType:
6041                               {
6042                                  double doubleValue;
6043                                  void (*Set)(void *, double) = (void *)prop.Set;
6044
6045                                  exp.instance = Instantiation { };
6046                                  exp.instance.data = new0 byte[_class.structSize];
6047                                  exp.instance._class = MkSpecifierName(_class.fullName);
6048                                  exp.instance.loc = exp.loc;
6049                                  exp.type = instanceExp;
6050
6051                                  GetDouble(value, &doubleValue);
6052
6053                                  Set(exp.instance.data, doubleValue);
6054                                  PopulateInstance(exp.instance);
6055                                  break;
6056                               }
6057                            }
6058                         }
6059                         else if(_class.type == bitClass)
6060                         {
6061                            switch(type.kind)
6062                            {
6063                               case classType:
6064                               {
6065                                  Class propertyClass = type._class.registered;
6066                                  if(propertyClass.type == structClass && value.instance.data)
6067                                  {
6068                                     unsigned int (*Set)(void *) = (void *)prop.Set;
6069                                     unsigned int bits = Set(value.instance.data);
6070                                     exp.constant = PrintHexUInt(bits);
6071                                     exp.type = constantExp;
6072                                     break;
6073                                  }
6074                                  else if(_class.type == bitClass)
6075                                  {
6076                                     unsigned int value;
6077                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
6078                                     unsigned int bits;
6079
6080                                     GetUInt(exp.member.exp, &value);
6081                                     bits = Set(value);
6082                                     exp.constant = PrintHexUInt(bits);
6083                                     exp.type = constantExp;
6084                                  }
6085                               }
6086                            }
6087                         }
6088                      }
6089                      else
6090                      {
6091                         if(_class.type == bitClass)
6092                         {
6093                            unsigned int value;
6094                            GetUInt(exp.member.exp, &value);
6095
6096                            switch(type.kind)
6097                            {
6098                               case classType:
6099                               {
6100                                  Class _class = type._class.registered;
6101                                  if(_class.type == structClass)
6102                                  {
6103                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6104
6105                                     exp.instance = Instantiation { };
6106                                     exp.instance.data = new0 byte[_class.structSize];
6107                                     exp.instance._class = MkSpecifierName(_class.fullName);
6108                                     exp.instance.loc = exp.loc;
6109                                     //exp.instance.fullSet = true;
6110                                     exp.type = instanceExp;
6111                                     Get(value, exp.instance.data);
6112                                     PopulateInstance(exp.instance);
6113                                  }
6114                                  else if(_class.type == bitClass)
6115                                  {
6116                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6117                                     uint64 bits = Get(value);
6118                                     exp.constant = PrintHexUInt64(bits);
6119                                     exp.type = constantExp;
6120                                  }
6121                                  break;
6122                               }
6123                            }
6124                         }
6125                         else if(_class.type == structClass)
6126                         {
6127                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6128                            switch(type.kind)
6129                            {
6130                               case classType:
6131                               {
6132                                  Class _class = type._class.registered;
6133                                  if(_class.type == structClass && value)
6134                                  {
6135                                     void (*Get)(void *, void *) = (void *)prop.Get;
6136
6137                                     exp.instance = Instantiation { };
6138                                     exp.instance.data = new0 byte[_class.structSize];
6139                                     exp.instance._class = MkSpecifierName(_class.fullName);
6140                                     exp.instance.loc = exp.loc;
6141                                     //exp.instance.fullSet = true;
6142                                     exp.type = instanceExp;
6143                                     Get(value, exp.instance.data);
6144                                     PopulateInstance(exp.instance);
6145                                  }
6146                                  break;
6147                               }
6148                            }
6149                         }
6150                         /*else
6151                         {
6152                            char * value = exp.member.exp.instance.data;
6153                            switch(type.kind)
6154                            {
6155                               case classType:
6156                               {
6157                                  Class _class = type._class.registered;
6158                                  if(_class.type == normalClass)
6159                                  {
6160                                     void *(*Get)(void *) = (void *)prop.Get;
6161
6162                                     exp.instance = Instantiation { };
6163                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6164                                     exp.type = instanceExp;
6165                                     exp.instance.data = Get(value, exp.instance.data);
6166                                  }
6167                                  break;
6168                               }
6169                            }
6170                         }
6171                         */
6172                      }
6173                   }
6174                }
6175                else
6176                {
6177                   exp.isConstant = false;
6178                }
6179             }
6180             else if(member)
6181             {
6182             }
6183          }
6184
6185          if(exp.type != ExpressionType::memberExp)
6186          {
6187             FreeExpression(memberExp);
6188             FreeIdentifier(memberID);
6189          }
6190          break;
6191       }
6192       case typeSizeExp:
6193       {
6194          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6195          FreeExpContents(exp);
6196          exp.constant = PrintUInt(ComputeTypeSize(type));
6197          exp.type = constantExp;
6198          FreeType(type);
6199          break;
6200       }
6201       case classSizeExp:
6202       {
6203          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6204          if(classSym && classSym.registered)
6205          {
6206             if(classSym.registered.fixed)
6207             {
6208                FreeSpecifier(exp._class);
6209                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6210                exp.type = constantExp;
6211             }
6212             else
6213             {
6214                char className[1024];
6215                strcpy(className, "__ecereClass_");
6216                FullClassNameCat(className, classSym.string, true);
6217                //MangleClassName(className);
6218
6219                DeclareClass(classSym, className);
6220
6221                FreeExpContents(exp);
6222                exp.type = pointerExp;
6223                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6224                exp.member.member = MkIdentifier("structSize");
6225             }
6226          }
6227          break;
6228       }
6229       case castExp:
6230       //case constantExp:
6231       {
6232          Type type;
6233          Expression e = exp;
6234          if(exp.type == castExp)
6235          {
6236             if(exp.cast.exp)
6237                ComputeExpression(exp.cast.exp);
6238             e = exp.cast.exp;
6239          }
6240          if(e && exp.expType)
6241          {
6242             /*if(exp.destType)
6243                type = exp.destType;
6244             else*/
6245                type = exp.expType;
6246             if(type.kind == classType)
6247             {
6248                Class _class = type._class.registered;
6249                if(_class && (_class.type == unitClass || _class.type == bitClass))
6250                {
6251                   if(!_class.dataType)
6252                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6253                   type = _class.dataType;
6254                }
6255             }
6256
6257             switch(type.kind)
6258             {
6259                case _BoolType:
6260                case charType:
6261                   if(type.isSigned)
6262                   {
6263                      char value = 0;
6264                      if(GetChar(e, &value))
6265                      {
6266                         FreeExpContents(exp);
6267                         exp.constant = PrintChar(value);
6268                         exp.type = constantExp;
6269                      }
6270                   }
6271                   else
6272                   {
6273                      unsigned char value = 0;
6274                      if(GetUChar(e, &value))
6275                      {
6276                         FreeExpContents(exp);
6277                         exp.constant = PrintUChar(value);
6278                         exp.type = constantExp;
6279                      }
6280                   }
6281                   break;
6282                case shortType:
6283                   if(type.isSigned)
6284                   {
6285                      short value = 0;
6286                      if(GetShort(e, &value))
6287                      {
6288                         FreeExpContents(exp);
6289                         exp.constant = PrintShort(value);
6290                         exp.type = constantExp;
6291                      }
6292                   }
6293                   else
6294                   {
6295                      unsigned short value = 0;
6296                      if(GetUShort(e, &value))
6297                      {
6298                         FreeExpContents(exp);
6299                         exp.constant = PrintUShort(value);
6300                         exp.type = constantExp;
6301                      }
6302                   }
6303                   break;
6304                case intType:
6305                   if(type.isSigned)
6306                   {
6307                      int value = 0;
6308                      if(GetInt(e, &value))
6309                      {
6310                         FreeExpContents(exp);
6311                         exp.constant = PrintInt(value);
6312                         exp.type = constantExp;
6313                      }
6314                   }
6315                   else
6316                   {
6317                      unsigned int value = 0;
6318                      if(GetUInt(e, &value))
6319                      {
6320                         FreeExpContents(exp);
6321                         exp.constant = PrintUInt(value);
6322                         exp.type = constantExp;
6323                      }
6324                   }
6325                   break;
6326                case int64Type:
6327                   if(type.isSigned)
6328                   {
6329                      int64 value = 0;
6330                      if(GetInt64(e, &value))
6331                      {
6332                         FreeExpContents(exp);
6333                         exp.constant = PrintInt64(value);
6334                         exp.type = constantExp;
6335                      }
6336                   }
6337                   else
6338                   {
6339                      uint64 value = 0;
6340                      if(GetUInt64(e, &value))
6341                      {
6342                         FreeExpContents(exp);
6343                         exp.constant = PrintUInt64(value);
6344                         exp.type = constantExp;
6345                      }
6346                   }
6347                   break;
6348                case intPtrType:
6349                   if(type.isSigned)
6350                   {
6351                      intptr value = 0;
6352                      if(GetIntPtr(e, &value))
6353                      {
6354                         FreeExpContents(exp);
6355                         exp.constant = PrintInt64((int64)value);
6356                         exp.type = constantExp;
6357                      }
6358                   }
6359                   else
6360                   {
6361                      uintptr value = 0;
6362                      if(GetUIntPtr(e, &value))
6363                      {
6364                         FreeExpContents(exp);
6365                         exp.constant = PrintUInt64((uint64)value);
6366                         exp.type = constantExp;
6367                      }
6368                   }
6369                   break;
6370                case intSizeType:
6371                   if(type.isSigned)
6372                   {
6373                      intsize value = 0;
6374                      if(GetIntSize(e, &value))
6375                      {
6376                         FreeExpContents(exp);
6377                         exp.constant = PrintInt64((int64)value);
6378                         exp.type = constantExp;
6379                      }
6380                   }
6381                   else
6382                   {
6383                      uintsize value = 0;
6384                      if(GetUIntSize(e, &value))
6385                      {
6386                         FreeExpContents(exp);
6387                         exp.constant = PrintUInt64((uint64)value);
6388                         exp.type = constantExp;
6389                      }
6390                   }
6391                   break;
6392                case floatType:
6393                {
6394                   float value = 0;
6395                   if(GetFloat(e, &value))
6396                   {
6397                      FreeExpContents(exp);
6398                      exp.constant = PrintFloat(value);
6399                      exp.type = constantExp;
6400                   }
6401                   break;
6402                }
6403                case doubleType:
6404                {
6405                   double value = 0;
6406                   if(GetDouble(e, &value))
6407                   {
6408                      FreeExpContents(exp);
6409                      exp.constant = PrintDouble(value);
6410                      exp.type = constantExp;
6411                   }
6412                   break;
6413                }
6414             }
6415          }
6416          break;
6417       }
6418       case conditionExp:
6419       {
6420          Operand op1 { };
6421          Operand op2 { };
6422          Operand op3 { };
6423
6424          if(exp.cond.exp)
6425             // Caring only about last expression for now...
6426             ComputeExpression(exp.cond.exp->last);
6427          if(exp.cond.elseExp)
6428             ComputeExpression(exp.cond.elseExp);
6429          if(exp.cond.cond)
6430             ComputeExpression(exp.cond.cond);
6431
6432          op1 = GetOperand(exp.cond.cond);
6433          if(op1.type) op1.type.refCount++;
6434          op2 = GetOperand(exp.cond.exp->last);
6435          if(op2.type) op2.type.refCount++;
6436          op3 = GetOperand(exp.cond.elseExp);
6437          if(op3.type) op3.type.refCount++;
6438
6439          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6440          if(op1.type) FreeType(op1.type);
6441          if(op2.type) FreeType(op2.type);
6442          if(op3.type) FreeType(op3.type);
6443          break;
6444       }
6445    }
6446 }
6447
6448 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6449 {
6450    bool result = true;
6451    if(destType)
6452    {
6453       OldList converts { };
6454       Conversion convert;
6455
6456       if(destType.kind == voidType)
6457          return false;
6458
6459       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6460          result = false;
6461       if(converts.count)
6462       {
6463          // for(convert = converts.last; convert; convert = convert.prev)
6464          for(convert = converts.first; convert; convert = convert.next)
6465          {
6466             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6467             if(!empty)
6468             {
6469                Expression newExp { };
6470                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6471
6472                // TODO: Check this...
6473                *newExp = *exp;
6474                newExp.prev = null;
6475                newExp.next = null;
6476                newExp.destType = null;
6477
6478                if(convert.isGet)
6479                {
6480                   // [exp].ColorRGB
6481                   exp.type = memberExp;
6482                   exp.addedThis = true;
6483                   exp.member.exp = newExp;
6484                   FreeType(exp.member.exp.expType);
6485
6486                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6487                   exp.member.exp.expType.classObjectType = objectType;
6488                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6489                   exp.member.memberType = propertyMember;
6490                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6491                   // TESTING THIS... for (int)degrees
6492                   exp.needCast = true;
6493                   if(exp.expType) exp.expType.refCount++;
6494                   ApplyAnyObjectLogic(exp.member.exp);
6495                }
6496                else
6497                {
6498
6499                   /*if(exp.isConstant)
6500                   {
6501                      // Color { ColorRGB = [exp] };
6502                      exp.type = instanceExp;
6503                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6504                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6505                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6506                   }
6507                   else*/
6508                   {
6509                      // If not constant, don't turn it yet into an instantiation
6510                      // (Go through the deep members system first)
6511                      exp.type = memberExp;
6512                      exp.addedThis = true;
6513                      exp.member.exp = newExp;
6514
6515                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6516                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6517                         newExp.expType._class.registered.type == noHeadClass)
6518                      {
6519                         newExp.byReference = true;
6520                      }
6521
6522                      FreeType(exp.member.exp.expType);
6523                      /*exp.member.exp.expType = convert.convert.dataType;
6524                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6525                      exp.member.exp.expType = null;
6526                      if(convert.convert.dataType)
6527                      {
6528                         exp.member.exp.expType = { };
6529                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6530                         exp.member.exp.expType.refCount = 1;
6531                         exp.member.exp.expType.classObjectType = objectType;
6532                         ApplyAnyObjectLogic(exp.member.exp);
6533                      }
6534
6535                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6536                      exp.member.memberType = reverseConversionMember;
6537                      exp.expType = convert.resultType ? convert.resultType :
6538                         MkClassType(convert.convert._class.fullName);
6539                      exp.needCast = true;
6540                      if(convert.resultType) convert.resultType.refCount++;
6541                   }
6542                }
6543             }
6544             else
6545             {
6546                FreeType(exp.expType);
6547                if(convert.isGet)
6548                {
6549                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6550                   if(exp.destType.casted)
6551                      exp.needCast = true;
6552                   if(exp.expType) exp.expType.refCount++;
6553                }
6554                else
6555                {
6556                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6557                   if(exp.destType.casted)
6558                      exp.needCast = true;
6559                   if(convert.resultType)
6560                      convert.resultType.refCount++;
6561                }
6562             }
6563          }
6564          if(exp.isConstant && inCompiler)
6565             ComputeExpression(exp);
6566
6567          converts.Free(FreeConvert);
6568       }
6569
6570       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6571       {
6572          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6573       }
6574       if(!result && exp.expType && exp.destType)
6575       {
6576          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6577              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6578             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6579             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6580             result = true;
6581       }
6582    }
6583    // if(result) CheckTemplateTypes(exp);
6584    return result;
6585 }
6586
6587 void CheckTemplateTypes(Expression exp)
6588 {
6589    Expression nbExp = GetNonBracketsExp(exp);
6590    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6591       (nbExp == exp || nbExp.type != castExp))
6592    {
6593       Expression newExp { };
6594       Context context;
6595       *newExp = *exp;
6596       if(exp.destType) exp.destType.refCount++;
6597       if(exp.expType)  exp.expType.refCount++;
6598       newExp.prev = null;
6599       newExp.next = null;
6600
6601       switch(exp.expType.kind)
6602       {
6603          case doubleType:
6604             if(exp.destType.classObjectType)
6605             {
6606                // We need to pass the address, just pass it along (Undo what was done above)
6607                if(exp.destType) exp.destType.refCount--;
6608                if(exp.expType)  exp.expType.refCount--;
6609                delete newExp;
6610             }
6611             else
6612             {
6613                // If we're looking for value:
6614                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6615                OldList * specs;
6616                OldList * unionDefs = MkList();
6617                OldList * statements = MkList();
6618                context = PushContext();
6619                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6620                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6621                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6622                exp.type = extensionCompoundExp;
6623                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6624                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6625                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6626                exp.compound.compound.context = context;
6627                PopContext(context);
6628             }
6629             break;
6630          default:
6631             exp.type = castExp;
6632             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6633             exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6634             exp.needCast = true;
6635             break;
6636       }
6637    }
6638    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6639    {
6640       Expression newExp { };
6641       Context context;
6642       *newExp = *exp;
6643       if(exp.destType) exp.destType.refCount++;
6644       if(exp.expType)  exp.expType.refCount++;
6645       newExp.prev = null;
6646       newExp.next = null;
6647
6648       switch(exp.expType.kind)
6649       {
6650          case doubleType:
6651             if(exp.destType.classObjectType)
6652             {
6653                // We need to pass the address, just pass it along (Undo what was done above)
6654                if(exp.destType) exp.destType.refCount--;
6655                if(exp.expType)  exp.expType.refCount--;
6656                delete newExp;
6657             }
6658             else
6659             {
6660                // If we're looking for value:
6661                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6662                OldList * specs;
6663                OldList * unionDefs = MkList();
6664                OldList * statements = MkList();
6665                context = PushContext();
6666                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6667                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6668                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6669                exp.type = extensionCompoundExp;
6670                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6671                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6672                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6673                exp.compound.compound.context = context;
6674                PopContext(context);
6675             }
6676             break;
6677          case classType:
6678          {
6679             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6680             {
6681                exp.type = bracketsExp;
6682                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6683                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6684                ProcessExpressionType(exp.list->first);
6685                break;
6686             }
6687             else
6688             {
6689                exp.type = bracketsExp;
6690                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6691                exp.needTemplateCast = 2;
6692                newExp.needCast = true;
6693                newExp.needTemplateCast = 2;
6694                ProcessExpressionType(exp.list->first);
6695                break;
6696             }
6697          }
6698          default:
6699          {
6700             if(exp.expType.kind == templateType)
6701             {
6702                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6703                if(type)
6704                {
6705                   FreeType(exp.destType);
6706                   FreeType(exp.expType);
6707                   delete newExp;
6708                   break;
6709                }
6710             }
6711             if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6712             {
6713                exp.type = opExp;
6714                exp.op.op = '*';
6715                exp.op.exp1 = null;
6716                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6717                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6718             }
6719             else
6720             {
6721                char typeString[1024];
6722                Declarator decl;
6723                OldList * specs = MkList();
6724                typeString[0] = '\0';
6725                PrintType(exp.expType, typeString, false, false);
6726                decl = SpecDeclFromString(typeString, specs, null);
6727
6728                exp.type = castExp;
6729                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6730                exp.cast.typeName = MkTypeName(specs, decl);
6731                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6732                exp.cast.exp.needCast = true;
6733             }
6734             break;
6735          }
6736       }
6737    }
6738 }
6739 // TODO: The Symbol tree should be reorganized by namespaces
6740 // Name Space:
6741 //    - Tree of all symbols within (stored without namespace)
6742 //    - Tree of sub-namespaces
6743
6744 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6745 {
6746    int nsLen = strlen(nameSpace);
6747    Symbol symbol;
6748    // Start at the name space prefix
6749    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6750    {
6751       char * s = symbol.string;
6752       if(!strncmp(s, nameSpace, nsLen))
6753       {
6754          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6755          int c;
6756          char * namePart;
6757          for(c = strlen(s)-1; c >= 0; c--)
6758             if(s[c] == ':')
6759                break;
6760
6761          namePart = s+c+1;
6762          if(!strcmp(namePart, name))
6763          {
6764             // TODO: Error on ambiguity
6765             return symbol;
6766          }
6767       }
6768       else
6769          break;
6770    }
6771    return null;
6772 }
6773
6774 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6775 {
6776    int c;
6777    char nameSpace[1024];
6778    const char * namePart;
6779    bool gotColon = false;
6780
6781    nameSpace[0] = '\0';
6782    for(c = strlen(name)-1; c >= 0; c--)
6783       if(name[c] == ':')
6784       {
6785          gotColon = true;
6786          break;
6787       }
6788
6789    namePart = name+c+1;
6790    while(c >= 0 && name[c] == ':') c--;
6791    if(c >= 0)
6792    {
6793       // Try an exact match first
6794       Symbol symbol = (Symbol)tree.FindString(name);
6795       if(symbol)
6796          return symbol;
6797
6798       // Namespace specified
6799       memcpy(nameSpace, name, c + 1);
6800       nameSpace[c+1] = 0;
6801
6802       return ScanWithNameSpace(tree, nameSpace, namePart);
6803    }
6804    else if(gotColon)
6805    {
6806       // Looking for a global symbol, e.g. ::Sleep()
6807       Symbol symbol = (Symbol)tree.FindString(namePart);
6808       return symbol;
6809    }
6810    else
6811    {
6812       // Name only (no namespace specified)
6813       Symbol symbol = (Symbol)tree.FindString(namePart);
6814       if(symbol)
6815          return symbol;
6816       return ScanWithNameSpace(tree, "", namePart);
6817    }
6818    return null;
6819 }
6820
6821 static void ProcessDeclaration(Declaration decl);
6822
6823 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6824 {
6825 #ifdef _DEBUG
6826    //Time startTime = GetTime();
6827 #endif
6828    // Optimize this later? Do this before/less?
6829    Context ctx;
6830    Symbol symbol = null;
6831    // First, check if the identifier is declared inside the function
6832    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6833
6834    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6835    {
6836       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6837       {
6838          symbol = null;
6839          if(thisNameSpace)
6840          {
6841             char curName[1024];
6842             strcpy(curName, thisNameSpace);
6843             strcat(curName, "::");
6844             strcat(curName, name);
6845             // Try to resolve in current namespace first
6846             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6847          }
6848          if(!symbol)
6849             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6850       }
6851       else
6852          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6853
6854       if(symbol || ctx == endContext) break;
6855    }
6856    if(inCompiler && curExternal && symbol && ctx == globalContext && curExternal.symbol && symbol.id > curExternal.symbol.idCode && symbol.pointerExternal)
6857    {
6858       if(symbol.pointerExternal.type == functionExternal)
6859       {
6860          FunctionDefinition function = symbol.pointerExternal.function;
6861
6862          // Modified this recently...
6863          Context tmpContext = curContext;
6864          curContext = null;
6865          symbol.pointerExternal = MkExternalDeclaration(MkDeclaration(CopyList(function.specifiers, CopySpecifier), MkListOne(MkInitDeclarator(CopyDeclarator(function.declarator), null))));
6866          curContext = tmpContext;
6867
6868          symbol.pointerExternal.symbol = symbol;
6869
6870          // TESTING THIS:
6871          DeclareType(symbol.type, true, true);
6872
6873          ast->Insert(curExternal.prev, symbol.pointerExternal);
6874
6875          symbol.id = curExternal.symbol.idCode;
6876
6877       }
6878       else if(symbol.pointerExternal.type == declarationExternal && curExternal.symbol.idCode < symbol.pointerExternal.symbol.id) // Added id comparison because Global Function prototypes were broken
6879       {
6880          ast->Move(symbol.pointerExternal, curExternal.prev);
6881          symbol.id = curExternal.symbol.idCode;
6882       }
6883    }
6884 #ifdef _DEBUG
6885    //findSymbolTotalTime += GetTime() - startTime;
6886 #endif
6887    return symbol;
6888 }
6889
6890 static void GetTypeSpecs(Type type, OldList * specs)
6891 {
6892    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6893    switch(type.kind)
6894    {
6895       case classType:
6896       {
6897          if(type._class.registered)
6898          {
6899             if(!type._class.registered.dataType)
6900                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6901             GetTypeSpecs(type._class.registered.dataType, specs);
6902          }
6903          break;
6904       }
6905       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6906       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6907       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6908       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6909       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6910       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6911       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6912       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6913       case intType:
6914       default:
6915          ListAdd(specs, MkSpecifier(INT)); break;
6916    }
6917 }
6918
6919 static void PrintArraySize(Type arrayType, char * string)
6920 {
6921    char size[256];
6922    size[0] = '\0';
6923    strcat(size, "[");
6924    if(arrayType.enumClass)
6925       strcat(size, arrayType.enumClass.string);
6926    else if(arrayType.arraySizeExp)
6927       PrintExpression(arrayType.arraySizeExp, size);
6928    strcat(size, "]");
6929    strcat(string, size);
6930 }
6931
6932 // WARNING : This function expects a null terminated string since it recursively concatenate...
6933 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6934 {
6935    if(type)
6936    {
6937       if(printConst && type.constant)
6938          strcat(string, "const ");
6939       switch(type.kind)
6940       {
6941          case classType:
6942          {
6943             Symbol c = type._class;
6944             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6945             //       look into merging with thisclass ?
6946             if(type.classObjectType == typedObject)
6947                strcat(string, "typed_object");
6948             else if(type.classObjectType == anyObject)
6949                strcat(string, "any_object");
6950             else
6951             {
6952                if(c && c.string)
6953                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6954             }
6955             if(type.byReference)
6956                strcat(string, " &");
6957             break;
6958          }
6959          case voidType: strcat(string, "void"); break;
6960          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6961          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6962          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6963          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6964          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6965          case _BoolType: strcat(string, "_Bool"); break;
6966          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6967          case floatType: strcat(string, "float"); break;
6968          case doubleType: strcat(string, "double"); break;
6969          case structType:
6970             if(type.enumName)
6971             {
6972                strcat(string, "struct ");
6973                strcat(string, type.enumName);
6974             }
6975             else if(type.typeName)
6976                strcat(string, type.typeName);
6977             else
6978             {
6979                Type member;
6980                strcat(string, "struct { ");
6981                for(member = type.members.first; member; member = member.next)
6982                {
6983                   PrintType(member, string, true, fullName);
6984                   strcat(string,"; ");
6985                }
6986                strcat(string,"}");
6987             }
6988             break;
6989          case unionType:
6990             if(type.enumName)
6991             {
6992                strcat(string, "union ");
6993                strcat(string, type.enumName);
6994             }
6995             else if(type.typeName)
6996                strcat(string, type.typeName);
6997             else
6998             {
6999                strcat(string, "union ");
7000                strcat(string,"(unnamed)");
7001             }
7002             break;
7003          case enumType:
7004             if(type.enumName)
7005             {
7006                strcat(string, "enum ");
7007                strcat(string, type.enumName);
7008             }
7009             else if(type.typeName)
7010                strcat(string, type.typeName);
7011             else
7012                strcat(string, "int"); // "enum");
7013             break;
7014          case ellipsisType:
7015             strcat(string, "...");
7016             break;
7017          case subClassType:
7018             strcat(string, "subclass(");
7019             strcat(string, type._class ? type._class.string : "int");
7020             strcat(string, ")");
7021             break;
7022          case templateType:
7023             strcat(string, type.templateParameter.identifier.string);
7024             break;
7025          case thisClassType:
7026             strcat(string, "thisclass");
7027             break;
7028          case vaListType:
7029             strcat(string, "__builtin_va_list");
7030             break;
7031       }
7032    }
7033 }
7034
7035 static void PrintName(Type type, char * string, bool fullName)
7036 {
7037    if(type.name && type.name[0])
7038    {
7039       if(fullName)
7040          strcat(string, type.name);
7041       else
7042       {
7043          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
7044          if(name) name += 2; else name = type.name;
7045          strcat(string, name);
7046       }
7047    }
7048 }
7049
7050 static void PrintAttribs(Type type, char * string)
7051 {
7052    if(type)
7053    {
7054       if(type.dllExport)   strcat(string, "dllexport ");
7055       if(type.attrStdcall) strcat(string, "stdcall ");
7056    }
7057 }
7058
7059 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
7060 {
7061    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7062    {
7063       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
7064          PrintAttribs(type, string);
7065       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
7066          strcat(string, " const");
7067       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
7068       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7069          strcat(string, " (");
7070       if(type.kind == pointerType)
7071       {
7072          if(type.type.kind == functionType || type.type.kind == methodType)
7073             PrintAttribs(type.type, string);
7074       }
7075       if(type.kind == pointerType)
7076       {
7077          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7078             strcat(string, "*");
7079          else
7080             strcat(string, " *");
7081       }
7082       if(printConst && type.constant && type.kind == pointerType)
7083          strcat(string, " const");
7084    }
7085    else
7086       PrintTypeSpecs(type, string, fullName, printConst);
7087 }
7088
7089 static void PostPrintType(Type type, char * string, bool fullName)
7090 {
7091    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7092       strcat(string, ")");
7093    if(type.kind == arrayType)
7094       PrintArraySize(type, string);
7095    else if(type.kind == functionType)
7096    {
7097       Type param;
7098       strcat(string, "(");
7099       for(param = type.params.first; param; param = param.next)
7100       {
7101          PrintType(param, string, true, fullName);
7102          if(param.next) strcat(string, ", ");
7103       }
7104       strcat(string, ")");
7105    }
7106    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7107       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7108 }
7109
7110 // *****
7111 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7112 // *****
7113 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7114 {
7115    PrePrintType(type, string, fullName, null, printConst);
7116
7117    if(type.thisClass || (printName && type.name && type.name[0]))
7118       strcat(string, " ");
7119    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7120    {
7121       Symbol _class = type.thisClass;
7122       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7123       {
7124          if(type.classObjectType == classPointer)
7125             strcat(string, "class");
7126          else
7127             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7128       }
7129       else if(_class && _class.string)
7130       {
7131          String s = _class.string;
7132          if(fullName)
7133             strcat(string, s);
7134          else
7135          {
7136             char * name = RSearchString(s, "::", strlen(s), true, false);
7137             if(name) name += 2; else name = s;
7138             strcat(string, name);
7139          }
7140       }
7141       strcat(string, "::");
7142    }
7143
7144    if(printName && type.name)
7145       PrintName(type, string, fullName);
7146    PostPrintType(type, string, fullName);
7147    if(type.bitFieldCount)
7148    {
7149       char count[100];
7150       sprintf(count, ":%d", type.bitFieldCount);
7151       strcat(string, count);
7152    }
7153 }
7154
7155 void PrintType(Type type, char * string, bool printName, bool fullName)
7156 {
7157    _PrintType(type, string, printName, fullName, true);
7158 }
7159
7160 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7161 {
7162    _PrintType(type, string, printName, fullName, false);
7163 }
7164
7165 static Type FindMember(Type type, char * string)
7166 {
7167    Type memberType;
7168    for(memberType = type.members.first; memberType; memberType = memberType.next)
7169    {
7170       if(!memberType.name)
7171       {
7172          Type subType = FindMember(memberType, string);
7173          if(subType)
7174             return subType;
7175       }
7176       else if(!strcmp(memberType.name, string))
7177          return memberType;
7178    }
7179    return null;
7180 }
7181
7182 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7183 {
7184    Type memberType;
7185    for(memberType = type.members.first; memberType; memberType = memberType.next)
7186    {
7187       if(!memberType.name)
7188       {
7189          Type subType = FindMember(memberType, string);
7190          if(subType)
7191          {
7192             *offset += memberType.offset;
7193             return subType;
7194          }
7195       }
7196       else if(!strcmp(memberType.name, string))
7197       {
7198          *offset += memberType.offset;
7199          return memberType;
7200       }
7201    }
7202    return null;
7203 }
7204
7205 public bool GetParseError() { return parseError; }
7206
7207 Expression ParseExpressionString(char * expression)
7208 {
7209    parseError = false;
7210
7211    fileInput = TempFile { };
7212    fileInput.Write(expression, 1, strlen(expression));
7213    fileInput.Seek(0, start);
7214
7215    echoOn = false;
7216    parsedExpression = null;
7217    resetScanner();
7218    expression_yyparse();
7219    delete fileInput;
7220
7221    return parsedExpression;
7222 }
7223
7224 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7225 {
7226    Identifier id = exp.identifier;
7227    Method method = null;
7228    Property prop = null;
7229    DataMember member = null;
7230    ClassProperty classProp = null;
7231
7232    if(_class && _class.type == enumClass)
7233    {
7234       NamedLink64 value = null;
7235       Class enumClass = eSystem_FindClass(privateModule, "enum");
7236       if(enumClass)
7237       {
7238          Class baseClass;
7239          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7240          {
7241             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7242             for(value = e.values.first; value; value = value.next)
7243             {
7244                if(!strcmp(value.name, id.string))
7245                   break;
7246             }
7247             if(value)
7248             {
7249                char constant[256];
7250
7251                FreeExpContents(exp);
7252
7253                exp.type = constantExp;
7254                exp.isConstant = true;
7255                if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7256                   sprintf(constant, FORMAT64D, value.data);
7257                else
7258                   sprintf(constant, FORMAT64HEX, value.data);
7259                exp.constant = CopyString(constant);
7260                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7261                exp.expType = MkClassType(baseClass.fullName);
7262                break;
7263             }
7264          }
7265       }
7266       if(value)
7267          return true;
7268    }
7269    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7270    {
7271       ProcessMethodType(method);
7272       exp.expType = Type
7273       {
7274          refCount = 1;
7275          kind = methodType;
7276          method = method;
7277          // Crash here?
7278          // TOCHECK: Put it back to what it was...
7279          // methodClass = _class;
7280          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7281       };
7282       //id._class = null;
7283       return true;
7284    }
7285    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7286    {
7287       if(!prop.dataType)
7288          ProcessPropertyType(prop);
7289       exp.expType = prop.dataType;
7290       if(prop.dataType) prop.dataType.refCount++;
7291       return true;
7292    }
7293    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7294    {
7295       if(!member.dataType)
7296          member.dataType = ProcessTypeString(member.dataTypeString, false);
7297       exp.expType = member.dataType;
7298       if(member.dataType) member.dataType.refCount++;
7299       return true;
7300    }
7301    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7302    {
7303       if(!classProp.dataType)
7304          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7305
7306       if(classProp.constant)
7307       {
7308          FreeExpContents(exp);
7309
7310          exp.isConstant = true;
7311          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7312          {
7313             //char constant[256];
7314             exp.type = stringExp;
7315             exp.constant = QMkString((char *)classProp.Get(_class));
7316          }
7317          else
7318          {
7319             char constant[256];
7320             exp.type = constantExp;
7321             sprintf(constant, "%d", (int)classProp.Get(_class));
7322             exp.constant = CopyString(constant);
7323          }
7324       }
7325       else
7326       {
7327          // TO IMPLEMENT...
7328       }
7329
7330       exp.expType = classProp.dataType;
7331       if(classProp.dataType) classProp.dataType.refCount++;
7332       return true;
7333    }
7334    return false;
7335 }
7336
7337 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7338 {
7339    BinaryTree * tree = &nameSpace.functions;
7340    GlobalData data = (GlobalData)tree->FindString(name);
7341    NameSpace * child;
7342    if(!data)
7343    {
7344       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7345       {
7346          data = ScanGlobalData(child, name);
7347          if(data)
7348             break;
7349       }
7350    }
7351    return data;
7352 }
7353
7354 static GlobalData FindGlobalData(char * name)
7355 {
7356    int start = 0, c;
7357    NameSpace * nameSpace;
7358    nameSpace = globalData;
7359    for(c = 0; name[c]; c++)
7360    {
7361       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7362       {
7363          NameSpace * newSpace;
7364          char * spaceName = new char[c - start + 1];
7365          strncpy(spaceName, name + start, c - start);
7366          spaceName[c-start] = '\0';
7367          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7368          delete spaceName;
7369          if(!newSpace)
7370             return null;
7371          nameSpace = newSpace;
7372          if(name[c] == ':') c++;
7373          start = c+1;
7374       }
7375    }
7376    if(c - start)
7377    {
7378       return ScanGlobalData(nameSpace, name + start);
7379    }
7380    return null;
7381 }
7382
7383 static int definedExpStackPos;
7384 static void * definedExpStack[512];
7385
7386 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7387 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7388 {
7389    Expression prev = checkedExp.prev, next = checkedExp.next;
7390
7391    FreeExpContents(checkedExp);
7392    FreeType(checkedExp.expType);
7393    FreeType(checkedExp.destType);
7394
7395    *checkedExp = *newExp;
7396
7397    delete newExp;
7398
7399    checkedExp.prev = prev;
7400    checkedExp.next = next;
7401 }
7402
7403 void ApplyAnyObjectLogic(Expression e)
7404 {
7405    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7406 #ifdef _DEBUG
7407    char debugExpString[4096];
7408    debugExpString[0] = '\0';
7409    PrintExpression(e, debugExpString);
7410 #endif
7411
7412    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7413    {
7414       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7415       //ellipsisDestType = destType;
7416       if(e && e.expType)
7417       {
7418          Type type = e.expType;
7419          Class _class = null;
7420          //Type destType = e.destType;
7421
7422          if(type.kind == classType && type._class && type._class.registered)
7423          {
7424             _class = type._class.registered;
7425          }
7426          else if(type.kind == subClassType)
7427          {
7428             _class = FindClass("ecere::com::Class").registered;
7429          }
7430          else
7431          {
7432             char string[1024] = "";
7433             Symbol classSym;
7434
7435             PrintTypeNoConst(type, string, false, true);
7436             classSym = FindClass(string);
7437             if(classSym) _class = classSym.registered;
7438          }
7439
7440          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...
7441             (!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))) ||
7442             destType.byReference)))
7443          {
7444             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7445             {
7446                Expression checkedExp = e, newExp;
7447
7448                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7449                {
7450                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7451                   {
7452                      if(checkedExp.type == extensionCompoundExp)
7453                      {
7454                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7455                      }
7456                      else
7457                         checkedExp = checkedExp.list->last;
7458                   }
7459                   else if(checkedExp.type == castExp)
7460                      checkedExp = checkedExp.cast.exp;
7461                }
7462
7463                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7464                {
7465                   newExp = checkedExp.op.exp2;
7466                   checkedExp.op.exp2 = null;
7467                   FreeExpContents(checkedExp);
7468
7469                   if(e.expType && e.expType.passAsTemplate)
7470                   {
7471                      char size[100];
7472                      ComputeTypeSize(e.expType);
7473                      sprintf(size, "%d", e.expType.size);
7474                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7475                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7476                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7477                   }
7478
7479                   ReplaceExpContents(checkedExp, newExp);
7480                   e.byReference = true;
7481                }
7482                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7483                {
7484                   Expression checkedExp; //, newExp;
7485
7486                   {
7487                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7488                      bool hasAddress =
7489                         e.type == identifierExp ||
7490                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7491                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7492                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7493                         e.type == indexExp;
7494
7495                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7496                      {
7497                         Context context = PushContext();
7498                         Declarator decl;
7499                         OldList * specs = MkList();
7500                         char typeString[1024];
7501                         Expression newExp { };
7502
7503                         typeString[0] = '\0';
7504                         *newExp = *e;
7505
7506                         //if(e.destType) e.destType.refCount++;
7507                         // if(exp.expType) exp.expType.refCount++;
7508                         newExp.prev = null;
7509                         newExp.next = null;
7510                         newExp.expType = null;
7511
7512                         PrintTypeNoConst(e.expType, typeString, false, true);
7513                         decl = SpecDeclFromString(typeString, specs, null);
7514                         newExp.destType = ProcessType(specs, decl);
7515
7516                         curContext = context;
7517
7518                         // We need a current compound for this
7519                         if(curCompound)
7520                         {
7521                            char name[100];
7522                            OldList * stmts = MkList();
7523                            e.type = extensionCompoundExp;
7524                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7525                            if(!curCompound.compound.declarations)
7526                               curCompound.compound.declarations = MkList();
7527                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7528                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7529                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7530                            e.compound = MkCompoundStmt(null, stmts);
7531                         }
7532                         else
7533                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7534
7535                         /*
7536                         e.compound = MkCompoundStmt(
7537                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7538                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7539
7540                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7541                         */
7542
7543                         {
7544                            Type type = e.destType;
7545                            e.destType = { };
7546                            CopyTypeInto(e.destType, type);
7547                            e.destType.refCount = 1;
7548                            e.destType.classObjectType = none;
7549                            FreeType(type);
7550                         }
7551
7552                         e.compound.compound.context = context;
7553                         PopContext(context);
7554                         curContext = context.parent;
7555                      }
7556                   }
7557
7558                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7559                   checkedExp = e;
7560                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7561                   {
7562                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7563                      {
7564                         if(checkedExp.type == extensionCompoundExp)
7565                         {
7566                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7567                         }
7568                         else
7569                            checkedExp = checkedExp.list->last;
7570                      }
7571                      else if(checkedExp.type == castExp)
7572                         checkedExp = checkedExp.cast.exp;
7573                   }
7574                   {
7575                      Expression operand { };
7576                      operand = *checkedExp;
7577                      checkedExp.Clear();
7578                      checkedExp.destType = ProcessTypeString("void *", false);
7579                      checkedExp.expType = checkedExp.destType;
7580                      checkedExp.destType.refCount++;
7581
7582                      checkedExp.type = opExp;
7583                      checkedExp.op.op = '&';
7584                      checkedExp.op.exp1 = null;
7585                      checkedExp.op.exp2 = operand;
7586
7587                      //newExp = MkExpOp(null, '&', checkedExp);
7588                   }
7589                   //ReplaceExpContents(checkedExp, newExp);
7590                }
7591             }
7592          }
7593       }
7594    }
7595    {
7596       // If expression type is a simple class, make it an address
7597       // FixReference(e, true);
7598    }
7599 //#if 0
7600    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7601       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7602          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7603    {
7604       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"))
7605       {
7606          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7607       }
7608       else
7609       {
7610          Expression thisExp { };
7611
7612          *thisExp = *e;
7613          thisExp.prev = null;
7614          thisExp.next = null;
7615          e.Clear();
7616
7617          e.type = bracketsExp;
7618          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7619          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7620             ((Expression)e.list->first).byReference = true;
7621
7622          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7623          {
7624             e.expType = thisExp.expType;
7625             e.expType.refCount++;
7626          }
7627          else*/
7628          {
7629             e.expType = { };
7630             CopyTypeInto(e.expType, thisExp.expType);
7631             e.expType.byReference = false;
7632             e.expType.refCount = 1;
7633
7634             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7635                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7636             {
7637                e.expType.classObjectType = none;
7638             }
7639          }
7640       }
7641    }
7642 // TOFIX: Try this for a nice IDE crash!
7643 //#endif
7644    // The other way around
7645    else
7646 //#endif
7647    if(destType && e.expType &&
7648          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7649          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7650          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7651    {
7652       if(destType.kind == ellipsisType)
7653       {
7654          Compiler_Error($"Unspecified type\n");
7655       }
7656       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7657       {
7658          bool byReference = e.expType.byReference;
7659          Expression thisExp { };
7660          Declarator decl;
7661          OldList * specs = MkList();
7662          char typeString[1024]; // Watch buffer overruns
7663          Type type;
7664          ClassObjectType backupClassObjectType;
7665          bool backupByReference;
7666
7667          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7668             type = e.expType;
7669          else
7670             type = destType;
7671
7672          backupClassObjectType = type.classObjectType;
7673          backupByReference = type.byReference;
7674
7675          type.classObjectType = none;
7676          type.byReference = false;
7677
7678          typeString[0] = '\0';
7679          PrintType(type, typeString, false, true);
7680          decl = SpecDeclFromString(typeString, specs, null);
7681
7682          type.classObjectType = backupClassObjectType;
7683          type.byReference = backupByReference;
7684
7685          *thisExp = *e;
7686          thisExp.prev = null;
7687          thisExp.next = null;
7688          e.Clear();
7689
7690          if( ( type.kind == classType && type._class && type._class.registered &&
7691                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7692                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7693              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7694              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7695          {
7696             e.type = opExp;
7697             e.op.op = '*';
7698             e.op.exp1 = null;
7699             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7700
7701             e.expType = { };
7702             CopyTypeInto(e.expType, type);
7703             e.expType.byReference = false;
7704             e.expType.refCount = 1;
7705          }
7706          else
7707          {
7708             e.type = castExp;
7709             e.cast.typeName = MkTypeName(specs, decl);
7710             e.cast.exp = thisExp;
7711             e.byReference = true;
7712             e.expType = type;
7713             type.refCount++;
7714          }
7715          e.destType = destType;
7716          destType.refCount++;
7717       }
7718    }
7719 }
7720
7721 void ApplyLocation(Expression exp, Location loc)
7722 {
7723    exp.loc = loc;
7724    switch(exp.type)
7725    {
7726       case opExp:
7727          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7728          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7729          break;
7730       case bracketsExp:
7731          if(exp.list)
7732          {
7733             Expression e;
7734             for(e = exp.list->first; e; e = e.next)
7735                ApplyLocation(e, loc);
7736          }
7737          break;
7738       case indexExp:
7739          if(exp.index.index)
7740          {
7741             Expression e;
7742             for(e = exp.index.index->first; e; e = e.next)
7743                ApplyLocation(e, loc);
7744          }
7745          if(exp.index.exp)
7746             ApplyLocation(exp.index.exp, loc);
7747          break;
7748       case callExp:
7749          if(exp.call.arguments)
7750          {
7751             Expression arg;
7752             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7753                ApplyLocation(arg, loc);
7754          }
7755          if(exp.call.exp)
7756             ApplyLocation(exp.call.exp, loc);
7757          break;
7758       case memberExp:
7759       case pointerExp:
7760          if(exp.member.exp)
7761             ApplyLocation(exp.member.exp, loc);
7762          break;
7763       case castExp:
7764          if(exp.cast.exp)
7765             ApplyLocation(exp.cast.exp, loc);
7766          break;
7767       case conditionExp:
7768          if(exp.cond.exp)
7769          {
7770             Expression e;
7771             for(e = exp.cond.exp->first; e; e = e.next)
7772                ApplyLocation(e, loc);
7773          }
7774          if(exp.cond.cond)
7775             ApplyLocation(exp.cond.cond, loc);
7776          if(exp.cond.elseExp)
7777             ApplyLocation(exp.cond.elseExp, loc);
7778          break;
7779       case vaArgExp:
7780          if(exp.vaArg.exp)
7781             ApplyLocation(exp.vaArg.exp, loc);
7782          break;
7783       default:
7784          break;
7785    }
7786 }
7787
7788 void ProcessExpressionType(Expression exp)
7789 {
7790    bool unresolved = false;
7791    Location oldyylloc = yylloc;
7792    bool notByReference = false;
7793 #ifdef _DEBUG
7794    char debugExpString[4096];
7795    debugExpString[0] = '\0';
7796    PrintExpression(exp, debugExpString);
7797 #endif
7798    if(!exp || exp.expType)
7799       return;
7800
7801    //eSystem_Logf("%s\n", expString);
7802
7803    // Testing this here
7804    yylloc = exp.loc;
7805    switch(exp.type)
7806    {
7807       case identifierExp:
7808       {
7809          Identifier id = exp.identifier;
7810          if(!id || !topContext) return;
7811
7812          // DOING THIS LATER NOW...
7813          if(id._class && id._class.name)
7814          {
7815             id.classSym = id._class.symbol; // FindClass(id._class.name);
7816             /* TODO: Name Space Fix ups
7817             if(!id.classSym)
7818                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7819             */
7820          }
7821
7822          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7823          {
7824             exp.expType = ProcessTypeString("Module", true);
7825             break;
7826          }
7827          else */
7828          if(!strcmp(id.string, "__runtimePlatform"))
7829          {
7830             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7831             break;
7832          }
7833          else if(strstr(id.string, "__ecereClass") == id.string)
7834          {
7835             exp.expType = ProcessTypeString("ecere::com::Class", true);
7836             break;
7837          }
7838          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7839          {
7840             // Added this here as well
7841             ReplaceClassMembers(exp, thisClass);
7842             if(exp.type != identifierExp)
7843             {
7844                ProcessExpressionType(exp);
7845                break;
7846             }
7847
7848             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7849                break;
7850          }
7851          else
7852          {
7853             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7854             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7855             if(!symbol/* && exp.destType*/)
7856             {
7857                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7858                   break;
7859                else
7860                {
7861                   if(thisClass)
7862                   {
7863                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7864                      if(exp.type != identifierExp)
7865                      {
7866                         ProcessExpressionType(exp);
7867                         break;
7868                      }
7869                   }
7870                   // Static methods called from inside the _class
7871                   else if(currentClass && !id._class)
7872                   {
7873                      if(ResolveIdWithClass(exp, currentClass, true))
7874                         break;
7875                   }
7876                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7877                }
7878             }
7879
7880             // If we manage to resolve this symbol
7881             if(symbol)
7882             {
7883                Type type = symbol.type;
7884                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7885
7886                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7887                {
7888                   Context context = SetupTemplatesContext(_class);
7889                   type = ReplaceThisClassType(_class);
7890                   FinishTemplatesContext(context);
7891                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7892                }
7893
7894                FreeSpecifier(id._class);
7895                id._class = null;
7896                delete id.string;
7897                id.string = CopyString(symbol.string);
7898
7899                id.classSym = null;
7900                exp.expType = type;
7901                if(type)
7902                   type.refCount++;
7903
7904                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7905                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7906                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7907                   // Add missing cases here... enum Classes...
7908                   exp.isConstant = true;
7909
7910                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7911                if(symbol.isParam || !strcmp(id.string, "this"))
7912                {
7913                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7914                      exp.byReference = true;
7915
7916                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7917                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7918                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7919                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7920                   {
7921                      Identifier id = exp.identifier;
7922                      exp.type = bracketsExp;
7923                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7924                   }*/
7925                }
7926
7927                if(symbol.isIterator)
7928                {
7929                   if(symbol.isIterator == 3)
7930                   {
7931                      exp.type = bracketsExp;
7932                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7933                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7934                      exp.expType = null;
7935                      ProcessExpressionType(exp);
7936                   }
7937                   else if(symbol.isIterator != 4)
7938                   {
7939                      exp.type = memberExp;
7940                      exp.member.exp = MkExpIdentifier(exp.identifier);
7941                      exp.member.exp.expType = exp.expType;
7942                      /*if(symbol.isIterator == 6)
7943                         exp.member.member = MkIdentifier("key");
7944                      else*/
7945                         exp.member.member = MkIdentifier("data");
7946                      exp.expType = null;
7947                      ProcessExpressionType(exp);
7948                   }
7949                }
7950                break;
7951             }
7952             else
7953             {
7954                DefinedExpression definedExp = null;
7955                if(thisNameSpace && !(id._class && !id._class.name))
7956                {
7957                   char name[1024];
7958                   strcpy(name, thisNameSpace);
7959                   strcat(name, "::");
7960                   strcat(name, id.string);
7961                   definedExp = eSystem_FindDefine(privateModule, name);
7962                }
7963                if(!definedExp)
7964                   definedExp = eSystem_FindDefine(privateModule, id.string);
7965                if(definedExp)
7966                {
7967                   int c;
7968                   for(c = 0; c<definedExpStackPos; c++)
7969                      if(definedExpStack[c] == definedExp)
7970                         break;
7971                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7972                   {
7973                      Location backupYylloc = yylloc;
7974                      File backInput = fileInput;
7975                      definedExpStack[definedExpStackPos++] = definedExp;
7976
7977                      fileInput = TempFile { };
7978                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7979                      fileInput.Seek(0, start);
7980
7981                      echoOn = false;
7982                      parsedExpression = null;
7983                      resetScanner();
7984                      expression_yyparse();
7985                      delete fileInput;
7986                      if(backInput)
7987                         fileInput = backInput;
7988
7989                      yylloc = backupYylloc;
7990
7991                      if(parsedExpression)
7992                      {
7993                         FreeIdentifier(id);
7994                         exp.type = bracketsExp;
7995                         exp.list = MkListOne(parsedExpression);
7996                         ApplyLocation(parsedExpression, yylloc);
7997                         ProcessExpressionType(exp);
7998                         definedExpStackPos--;
7999                         return;
8000                      }
8001                      definedExpStackPos--;
8002                   }
8003                   else
8004                   {
8005                      if(inCompiler)
8006                      {
8007                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
8008                      }
8009                   }
8010                }
8011                else
8012                {
8013                   GlobalData data = null;
8014                   if(thisNameSpace && !(id._class && !id._class.name))
8015                   {
8016                      char name[1024];
8017                      strcpy(name, thisNameSpace);
8018                      strcat(name, "::");
8019                      strcat(name, id.string);
8020                      data = FindGlobalData(name);
8021                   }
8022                   if(!data)
8023                      data = FindGlobalData(id.string);
8024                   if(data)
8025                   {
8026                      DeclareGlobalData(data);
8027                      exp.expType = data.dataType;
8028                      if(data.dataType) data.dataType.refCount++;
8029
8030                      delete id.string;
8031                      id.string = CopyString(data.fullName);
8032                      FreeSpecifier(id._class);
8033                      id._class = null;
8034
8035                      break;
8036                   }
8037                   else
8038                   {
8039                      GlobalFunction function = null;
8040                      if(thisNameSpace && !(id._class && !id._class.name))
8041                      {
8042                         char name[1024];
8043                         strcpy(name, thisNameSpace);
8044                         strcat(name, "::");
8045                         strcat(name, id.string);
8046                         function = eSystem_FindFunction(privateModule, name);
8047                      }
8048                      if(!function)
8049                         function = eSystem_FindFunction(privateModule, id.string);
8050                      if(function)
8051                      {
8052                         char name[1024];
8053                         delete id.string;
8054                         id.string = CopyString(function.name);
8055                         name[0] = 0;
8056
8057                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8058                            strcpy(name, "__ecereFunction_");
8059                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8060                         if(DeclareFunction(function, name))
8061                         {
8062                            delete id.string;
8063                            id.string = CopyString(name);
8064                         }
8065                         exp.expType = function.dataType;
8066                         if(function.dataType) function.dataType.refCount++;
8067
8068                         FreeSpecifier(id._class);
8069                         id._class = null;
8070
8071                         break;
8072                      }
8073                   }
8074                }
8075             }
8076          }
8077          unresolved = true;
8078          break;
8079       }
8080       case instanceExp:
8081       {
8082          // Class _class;
8083          // Symbol classSym;
8084
8085          if(!exp.instance._class)
8086          {
8087             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8088             {
8089                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8090             }
8091          }
8092
8093          //classSym = FindClass(exp.instance._class.fullName);
8094          //_class = classSym ? classSym.registered : null;
8095
8096          ProcessInstantiationType(exp.instance);
8097
8098          exp.isConstant = exp.instance.isConstant;
8099
8100          /*
8101          if(_class.type == unitClass && _class.base.type != systemClass)
8102          {
8103             {
8104                Type destType = exp.destType;
8105
8106                exp.destType = MkClassType(_class.base.fullName);
8107                exp.expType = MkClassType(_class.fullName);
8108                CheckExpressionType(exp, exp.destType, true);
8109
8110                exp.destType = destType;
8111             }
8112             exp.expType = MkClassType(_class.fullName);
8113          }
8114          else*/
8115          if(exp.instance._class)
8116          {
8117             exp.expType = MkClassType(exp.instance._class.name);
8118             /*if(exp.expType._class && exp.expType._class.registered &&
8119                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8120                exp.expType.byReference = true;*/
8121          }
8122          break;
8123       }
8124       case constantExp:
8125       {
8126          if(!exp.expType)
8127          {
8128             char * constant = exp.constant;
8129             Type type
8130             {
8131                refCount = 1;
8132                constant = true;
8133             };
8134             exp.expType = type;
8135
8136             if(constant[0] == '\'')
8137             {
8138                if((int)((byte *)constant)[1] > 127)
8139                {
8140                   int nb;
8141                   unichar ch = UTF8GetChar(constant + 1, &nb);
8142                   if(nb < 2) ch = constant[1];
8143                   delete constant;
8144                   exp.constant = PrintUInt(ch);
8145                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8146                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8147                   type._class = FindClass("unichar");
8148
8149                   type.isSigned = false;
8150                }
8151                else
8152                {
8153                   type.kind = charType;
8154                   type.isSigned = true;
8155                }
8156             }
8157             else
8158             {
8159                char * dot = strchr(constant, '.');
8160                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8161                char * exponent;
8162                if(isHex)
8163                {
8164                   exponent = strchr(constant, 'p');
8165                   if(!exponent) exponent = strchr(constant, 'P');
8166                }
8167                else
8168                {
8169                   exponent = strchr(constant, 'e');
8170                   if(!exponent) exponent = strchr(constant, 'E');
8171                }
8172
8173                if(dot || exponent)
8174                {
8175                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8176                      type.kind = floatType;
8177                   else
8178                      type.kind = doubleType;
8179                   type.isSigned = true;
8180                }
8181                else
8182                {
8183                   bool isSigned = constant[0] == '-';
8184                   char * endP = null;
8185                   int64 i64 = strtoll(constant, &endP, 0);
8186                   uint64 ui64 = strtoull(constant, &endP, 0);
8187                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll"));
8188                   if(isSigned)
8189                   {
8190                      if(i64 < MININT)
8191                         is64Bit = true;
8192                   }
8193                   else
8194                   {
8195                      if(ui64 > MAXINT)
8196                      {
8197                         if(ui64 > MAXDWORD)
8198                         {
8199                            is64Bit = true;
8200                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8201                               isSigned = true;
8202                         }
8203                      }
8204                      else if(constant[0] != '0' || !constant[1])
8205                         isSigned = true;
8206                   }
8207                   type.kind = is64Bit ? int64Type : intType;
8208                   type.isSigned = isSigned;
8209                }
8210             }
8211             exp.isConstant = true;
8212             if(exp.destType && exp.destType.kind == doubleType)
8213                type.kind = doubleType;
8214             else if(exp.destType && exp.destType.kind == floatType)
8215                type.kind = floatType;
8216             else if(exp.destType && exp.destType.kind == int64Type)
8217                type.kind = int64Type;
8218          }
8219          break;
8220       }
8221       case stringExp:
8222       {
8223          exp.isConstant = true;      // Why wasn't this constant?
8224          exp.expType = Type
8225          {
8226             refCount = 1;
8227             kind = pointerType;
8228             type = Type
8229             {
8230                refCount = 1;
8231                kind = charType;
8232                constant = true;
8233                isSigned = true;
8234             }
8235          };
8236          break;
8237       }
8238       case newExp:
8239       case new0Exp:
8240          ProcessExpressionType(exp._new.size);
8241          exp.expType = Type
8242          {
8243             refCount = 1;
8244             kind = pointerType;
8245             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8246          };
8247          DeclareType(exp.expType.type, false, false);
8248          break;
8249       case renewExp:
8250       case renew0Exp:
8251          ProcessExpressionType(exp._renew.size);
8252          ProcessExpressionType(exp._renew.exp);
8253          exp.expType = Type
8254          {
8255             refCount = 1;
8256             kind = pointerType;
8257             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8258          };
8259          DeclareType(exp.expType.type, false, false);
8260          break;
8261       case opExp:
8262       {
8263          bool assign = false, boolResult = false, boolOps = false;
8264          Type type1 = null, type2 = null;
8265          bool useDestType = false, useSideType = false;
8266          Location oldyylloc = yylloc;
8267          bool useSideUnit = false;
8268          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8269
8270          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8271          Type dummy
8272          {
8273             count = 1;
8274             refCount = 1;
8275          };
8276
8277          switch(exp.op.op)
8278          {
8279             // Assignment Operators
8280             case '=':
8281             case MUL_ASSIGN:
8282             case DIV_ASSIGN:
8283             case MOD_ASSIGN:
8284             case ADD_ASSIGN:
8285             case SUB_ASSIGN:
8286             case LEFT_ASSIGN:
8287             case RIGHT_ASSIGN:
8288             case AND_ASSIGN:
8289             case XOR_ASSIGN:
8290             case OR_ASSIGN:
8291                assign = true;
8292                break;
8293             // boolean Operators
8294             case '!':
8295                // Expect boolean operators
8296                //boolOps = true;
8297                //boolResult = true;
8298                break;
8299             case AND_OP:
8300             case OR_OP:
8301                // Expect boolean operands
8302                boolOps = true;
8303                boolResult = true;
8304                break;
8305             // Comparisons
8306             case EQ_OP:
8307             case '<':
8308             case '>':
8309             case LE_OP:
8310             case GE_OP:
8311             case NE_OP:
8312                // Gives boolean result
8313                boolResult = true;
8314                useSideType = true;
8315                break;
8316             case '+':
8317             case '-':
8318                useSideUnit = true;
8319                useSideType = true;
8320                useDestType = true;
8321                break;
8322
8323             case LEFT_OP:
8324             case RIGHT_OP:
8325                useSideType = true;
8326                useDestType = true;
8327                break;
8328
8329             case '|':
8330             case '^':
8331                useSideType = true;
8332                useDestType = true;
8333                break;
8334
8335             case '/':
8336             case '%':
8337                useSideType = true;
8338                useDestType = true;
8339                break;
8340             case '&':
8341             case '*':
8342                if(exp.op.exp1)
8343                {
8344                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8345                   useSideType = true;
8346                   useDestType = true;
8347                }
8348                break;
8349
8350             /*// Implement speed etc.
8351             case '*':
8352             case '/':
8353                break;
8354             */
8355          }
8356          if(exp.op.op == '&')
8357          {
8358             // Added this here earlier for Iterator address as key
8359             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8360             {
8361                Identifier id = exp.op.exp2.identifier;
8362                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8363                if(symbol && symbol.isIterator == 2)
8364                {
8365                   exp.type = memberExp;
8366                   exp.member.exp = exp.op.exp2;
8367                   exp.member.member = MkIdentifier("key");
8368                   exp.expType = null;
8369                   exp.op.exp2.expType = symbol.type;
8370                   symbol.type.refCount++;
8371                   ProcessExpressionType(exp);
8372                   FreeType(dummy);
8373                   break;
8374                }
8375                // exp.op.exp2.usage.usageRef = true;
8376             }
8377          }
8378
8379          //dummy.kind = TypeDummy;
8380          if(exp.op.exp1)
8381          {
8382             // Added this check here to use the dest type only for units derived from the base unit
8383             // So that untyped units will use the side unit as opposed to the untyped destination unit
8384             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8385             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8386                useDestType = false;
8387
8388             if(destClass && useDestType &&
8389               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8390
8391               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8392             {
8393                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8394                exp.op.exp1.destType = exp.destType;
8395                exp.op.exp1.opDestType = true;
8396                if(exp.destType)
8397                   exp.destType.refCount++;
8398             }
8399             else if(!assign)
8400             {
8401                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8402                exp.op.exp1.destType = dummy;
8403                dummy.refCount++;
8404             }
8405
8406             // TESTING THIS HERE...
8407             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8408                ProcessExpressionType(exp.op.exp1);
8409             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8410
8411             exp.op.exp1.opDestType = false;
8412
8413             // Fix for unit and ++ / --
8414             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8415                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8416             {
8417                exp.op.exp2 = MkExpConstant("1");
8418                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8419                assign = true;
8420             }
8421
8422             if(exp.op.exp1.destType == dummy)
8423             {
8424                FreeType(dummy);
8425                exp.op.exp1.destType = null;
8426             }
8427             type1 = exp.op.exp1.expType;
8428          }
8429
8430          if(exp.op.exp2)
8431          {
8432             char expString[10240];
8433             expString[0] = '\0';
8434             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8435             {
8436                if(exp.op.exp1)
8437                {
8438                   exp.op.exp2.destType = exp.op.exp1.expType;
8439                   if(exp.op.exp1.expType)
8440                      exp.op.exp1.expType.refCount++;
8441                }
8442                else
8443                {
8444                   exp.op.exp2.destType = exp.destType;
8445                   if(!exp.op.exp1 || exp.op.op != '&')
8446                      exp.op.exp2.opDestType = true;
8447                   if(exp.destType)
8448                      exp.destType.refCount++;
8449                }
8450
8451                if(type1) type1.refCount++;
8452                exp.expType = type1;
8453             }
8454             else if(assign)
8455             {
8456                if(inCompiler)
8457                   PrintExpression(exp.op.exp2, expString);
8458
8459                if(type1 && type1.kind == pointerType)
8460                {
8461                   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 ||
8462                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8463                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8464                   else if(exp.op.op == '=')
8465                   {
8466                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8467                      exp.op.exp2.destType = type1;
8468                      if(type1)
8469                         type1.refCount++;
8470                   }
8471                }
8472                else
8473                {
8474                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8475                   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/* ||
8476                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8477                   else
8478                   {
8479                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8480                      exp.op.exp2.destType = type1;
8481                      if(type1)
8482                         type1.refCount++;
8483                   }
8484                }
8485                if(type1) type1.refCount++;
8486                exp.expType = type1;
8487             }
8488             else if(destClass &&
8489                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8490                   (destClass.type == enumClass && useDestType)))
8491             {
8492                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8493                exp.op.exp2.destType = exp.destType;
8494                if(exp.op.op != '&')
8495                   exp.op.exp2.opDestType = true;
8496                if(exp.destType)
8497                   exp.destType.refCount++;
8498             }
8499             else
8500             {
8501                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8502                exp.op.exp2.destType = dummy;
8503                dummy.refCount++;
8504             }
8505
8506             // TESTING THIS HERE... (DANGEROUS)
8507             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8508                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8509             {
8510                FreeType(exp.op.exp2.destType);
8511                exp.op.exp2.destType = type1;
8512                type1.refCount++;
8513             }
8514             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8515             // Cannot lose the cast on a sizeof
8516             if(exp.op.op == SIZEOF)
8517             {
8518                Expression e = exp.op.exp2;
8519                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8520                {
8521                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8522                   {
8523                      if(e.type == extensionCompoundExp)
8524                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8525                      else
8526                         e = e.list->last;
8527                   }
8528                }
8529                if(e.type == castExp && e.cast.exp)
8530                   e.cast.exp.needCast = true;
8531             }
8532             ProcessExpressionType(exp.op.exp2);
8533             exp.op.exp2.opDestType = false;
8534             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8535
8536             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8537             {
8538                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)
8539                {
8540                   if(exp.op.op != '=' && type1.type.kind == voidType)
8541                      Compiler_Error($"void *: unknown size\n");
8542                }
8543                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||
8544                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8545                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8546                               exp.op.exp2.expType._class.registered.type == structClass ||
8547                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8548                {
8549                   if(exp.op.op == ADD_ASSIGN)
8550                      Compiler_Error($"cannot add two pointers\n");
8551                }
8552                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8553                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8554                {
8555                   if(exp.op.op == ADD_ASSIGN)
8556                      Compiler_Error($"cannot add two pointers\n");
8557                }
8558                else if(inCompiler)
8559                {
8560                   char type1String[1024];
8561                   char type2String[1024];
8562                   type1String[0] = '\0';
8563                   type2String[0] = '\0';
8564
8565                   PrintType(exp.op.exp2.expType, type1String, false, true);
8566                   PrintType(type1, type2String, false, true);
8567                   ChangeCh(expString, '\n', ' ');
8568                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8569                }
8570             }
8571
8572             if(exp.op.exp2.destType == dummy)
8573             {
8574                FreeType(dummy);
8575                exp.op.exp2.destType = null;
8576             }
8577
8578             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8579             {
8580                type2 = { };
8581                type2.refCount = 1;
8582                CopyTypeInto(type2, exp.op.exp2.expType);
8583                type2.isSigned = true;
8584             }
8585             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8586             {
8587                type2 = { kind = intType };
8588                type2.refCount = 1;
8589                type2.isSigned = true;
8590             }
8591             else
8592             {
8593                type2 = exp.op.exp2.expType;
8594                if(type2) type2.refCount++;
8595             }
8596          }
8597
8598          dummy.kind = voidType;
8599
8600          if(exp.op.op == SIZEOF)
8601          {
8602             exp.expType = Type
8603             {
8604                refCount = 1;
8605                kind = intSizeType;
8606             };
8607             exp.isConstant = true;
8608          }
8609          // Get type of dereferenced pointer
8610          else if(exp.op.op == '*' && !exp.op.exp1)
8611          {
8612             exp.expType = Dereference(type2);
8613             if(type2 && type2.kind == classType)
8614                notByReference = true;
8615          }
8616          else if(exp.op.op == '&' && !exp.op.exp1)
8617             exp.expType = Reference(type2);
8618          else if(!assign)
8619          {
8620             if(boolOps)
8621             {
8622                if(exp.op.exp1)
8623                {
8624                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8625                   exp.op.exp1.destType = MkClassType("bool");
8626                   exp.op.exp1.destType.truth = true;
8627                   if(!exp.op.exp1.expType)
8628                      ProcessExpressionType(exp.op.exp1);
8629                   else
8630                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8631                   FreeType(exp.op.exp1.expType);
8632                   exp.op.exp1.expType = MkClassType("bool");
8633                   exp.op.exp1.expType.truth = true;
8634                }
8635                if(exp.op.exp2)
8636                {
8637                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8638                   exp.op.exp2.destType = MkClassType("bool");
8639                   exp.op.exp2.destType.truth = true;
8640                   if(!exp.op.exp2.expType)
8641                      ProcessExpressionType(exp.op.exp2);
8642                   else
8643                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8644                   FreeType(exp.op.exp2.expType);
8645                   exp.op.exp2.expType = MkClassType("bool");
8646                   exp.op.exp2.expType.truth = true;
8647                }
8648             }
8649             else if(exp.op.exp1 && exp.op.exp2 &&
8650                ((useSideType /*&&
8651                      (useSideUnit ||
8652                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8653                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8654                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8655                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8656             {
8657                if(type1 && type2 &&
8658                   // If either both are class or both are not class
8659                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8660                {
8661                   // Added this check for enum subtraction to result in an int type:
8662                   if(exp.op.op == '-' &&
8663                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8664                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8665                   {
8666                      Type intType;
8667                      if(!type1._class.registered.dataType)
8668                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8669                      if(!type2._class.registered.dataType)
8670                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8671
8672                      intType = ProcessTypeString(
8673                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8674
8675                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8676                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8677                      exp.op.exp1.destType = intType;
8678                      exp.op.exp2.destType = intType;
8679                      intType.refCount++;
8680                   }
8681                   else
8682                   {
8683                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8684                      exp.op.exp2.destType = type1;
8685                      type1.refCount++;
8686                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8687                      exp.op.exp1.destType = type2;
8688                      type2.refCount++;
8689                   }
8690
8691                   // Warning here for adding Radians + Degrees with no destination type
8692                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8693                      type1._class.registered && type1._class.registered.type == unitClass &&
8694                      type2._class.registered && type2._class.registered.type == unitClass &&
8695                      type1._class.registered != type2._class.registered)
8696                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8697                         type1._class.string, type2._class.string, type1._class.string);
8698
8699                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8700                   {
8701                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8702                      if(argExp)
8703                      {
8704                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8705
8706                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8707                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8708                            exp.op.exp1)));
8709
8710                         ProcessExpressionType(exp.op.exp1);
8711
8712                         if(type2.kind != pointerType)
8713                         {
8714                            ProcessExpressionType(classExp);
8715
8716                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8717
8718                            if(!exp.op.exp2.expType)
8719                            {
8720                               if(type2)
8721                                  FreeType(type2);
8722                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8723                               type2.refCount++;
8724                            }
8725
8726                            ProcessExpressionType(exp.op.exp2);
8727                         }
8728                      }
8729                   }
8730
8731                   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)))
8732                   {
8733                      if(type1.kind != classType && type1.type.kind == voidType)
8734                         Compiler_Error($"void *: unknown size\n");
8735                      exp.expType = type1;
8736                      if(type1) type1.refCount++;
8737                   }
8738                   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)))
8739                   {
8740                      if(type2.kind != classType && type2.type.kind == voidType)
8741                         Compiler_Error($"void *: unknown size\n");
8742                      exp.expType = type2;
8743                      if(type2) type2.refCount++;
8744                   }
8745                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8746                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8747                   {
8748                      Compiler_Warning($"different levels of indirection\n");
8749                   }
8750                   else
8751                   {
8752                      bool success = false;
8753                      if(type1.kind == pointerType && type2.kind == pointerType)
8754                      {
8755                         if(exp.op.op == '+')
8756                            Compiler_Error($"cannot add two pointers\n");
8757                         else if(exp.op.op == '-')
8758                         {
8759                            // Pointer Subtraction gives integer
8760                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8761                            {
8762                               exp.expType = Type
8763                               {
8764                                  kind = intType;
8765                                  refCount = 1;
8766                               };
8767                               success = true;
8768
8769                               if(type1.type.kind == templateType)
8770                               {
8771                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8772                                  if(argExp)
8773                                  {
8774                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8775
8776                                     ProcessExpressionType(classExp);
8777
8778                                     exp.type = bracketsExp;
8779                                     exp.list = MkListOne(MkExpOp(
8780                                        MkExpBrackets(MkListOne(MkExpOp(
8781                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8782                                              , exp.op.op,
8783                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8784                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8785
8786                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8787                                     FreeType(dummy);
8788                                     return;
8789                                  }
8790                               }
8791                            }
8792                         }
8793                      }
8794
8795                      if(!success && exp.op.exp1.type == constantExp)
8796                      {
8797                         // If first expression is constant, try to match that first
8798                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8799                         {
8800                            if(exp.expType) FreeType(exp.expType);
8801                            exp.expType = exp.op.exp1.destType;
8802                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8803                            success = true;
8804                         }
8805                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8806                         {
8807                            if(exp.expType) FreeType(exp.expType);
8808                            exp.expType = exp.op.exp2.destType;
8809                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8810                            success = true;
8811                         }
8812                      }
8813                      else if(!success)
8814                      {
8815                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8816                         {
8817                            if(exp.expType) FreeType(exp.expType);
8818                            exp.expType = exp.op.exp2.destType;
8819                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8820                            success = true;
8821                         }
8822                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8823                         {
8824                            if(exp.expType) FreeType(exp.expType);
8825                            exp.expType = exp.op.exp1.destType;
8826                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8827                            success = true;
8828                         }
8829                      }
8830                      if(!success)
8831                      {
8832                         char expString1[10240];
8833                         char expString2[10240];
8834                         char type1[1024];
8835                         char type2[1024];
8836                         expString1[0] = '\0';
8837                         expString2[0] = '\0';
8838                         type1[0] = '\0';
8839                         type2[0] = '\0';
8840                         if(inCompiler)
8841                         {
8842                            PrintExpression(exp.op.exp1, expString1);
8843                            ChangeCh(expString1, '\n', ' ');
8844                            PrintExpression(exp.op.exp2, expString2);
8845                            ChangeCh(expString2, '\n', ' ');
8846                            PrintType(exp.op.exp1.expType, type1, false, true);
8847                            PrintType(exp.op.exp2.expType, type2, false, true);
8848                         }
8849
8850                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8851                      }
8852                   }
8853                }
8854                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8855                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8856                {
8857                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8858                   // Convert e.g. / 4 into / 4.0
8859                   exp.op.exp1.destType = type2._class.registered.dataType;
8860                   if(type2._class.registered.dataType)
8861                      type2._class.registered.dataType.refCount++;
8862                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8863                   exp.expType = type2;
8864                   if(type2) type2.refCount++;
8865                }
8866                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8867                {
8868                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8869                   // Convert e.g. / 4 into / 4.0
8870                   exp.op.exp2.destType = type1._class.registered.dataType;
8871                   if(type1._class.registered.dataType)
8872                      type1._class.registered.dataType.refCount++;
8873                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8874                   exp.expType = type1;
8875                   if(type1) type1.refCount++;
8876                }
8877                else if(type1)
8878                {
8879                   bool valid = false;
8880
8881                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8882                   {
8883                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8884
8885                      if(!type1._class.registered.dataType)
8886                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8887                      exp.op.exp2.destType = type1._class.registered.dataType;
8888                      exp.op.exp2.destType.refCount++;
8889
8890                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8891                      if(type2)
8892                         FreeType(type2);
8893                      type2 = exp.op.exp2.destType;
8894                      if(type2) type2.refCount++;
8895
8896                      exp.expType = type2;
8897                      type2.refCount++;
8898                   }
8899
8900                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8901                   {
8902                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8903
8904                      if(!type2._class.registered.dataType)
8905                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8906                      exp.op.exp1.destType = type2._class.registered.dataType;
8907                      exp.op.exp1.destType.refCount++;
8908
8909                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8910                      type1 = exp.op.exp1.destType;
8911                      exp.expType = type1;
8912                      type1.refCount++;
8913                   }
8914
8915                   // TESTING THIS NEW CODE
8916                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8917                   {
8918                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8919                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8920                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8921                      {
8922                         // Convert the enum to an int instead for these operators
8923                         if(op1IsEnum && exp.op.exp2.expType)
8924                         {
8925                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8926                            {
8927                               if(exp.expType) FreeType(exp.expType);
8928                               exp.expType = exp.op.exp2.expType;
8929                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8930                               valid = true;
8931                            }
8932                         }
8933                         else if(op2IsEnum && exp.op.exp1.expType)
8934                         {
8935                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8936                            {
8937                               if(exp.expType) FreeType(exp.expType);
8938                               exp.expType = exp.op.exp1.expType;
8939                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8940                               valid = true;
8941                            }
8942                         }
8943                      }
8944                      else
8945                      {
8946                         if(op1IsEnum && exp.op.exp2.expType)
8947                         {
8948                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8949                            {
8950                               if(exp.expType) FreeType(exp.expType);
8951                               exp.expType = exp.op.exp1.expType;
8952                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8953                               valid = true;
8954                            }
8955                         }
8956                         else if(op2IsEnum && exp.op.exp1.expType)
8957                         {
8958                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8959                            {
8960                               if(exp.expType) FreeType(exp.expType);
8961                               exp.expType = exp.op.exp2.expType;
8962                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8963                               valid = true;
8964                            }
8965                         }
8966                      }
8967                   }
8968
8969                   if(!valid)
8970                   {
8971                      // 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
8972                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8973                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8974                      {
8975                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8976                         exp.op.exp1.destType = type2;
8977                         type2.refCount++;
8978
8979                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8980                         {
8981                            if(exp.expType) FreeType(exp.expType);
8982                            exp.expType = exp.op.exp1.destType;
8983                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8984                         }
8985                      }
8986                      else
8987                      {
8988                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8989                         exp.op.exp2.destType = type1;
8990                         type1.refCount++;
8991
8992                      /*
8993                      // Maybe this was meant to be an enum...
8994                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8995                      {
8996                         Type oldType = exp.op.exp2.expType;
8997                         exp.op.exp2.expType = null;
8998                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8999                            FreeType(oldType);
9000                         else
9001                            exp.op.exp2.expType = oldType;
9002                      }
9003                      */
9004
9005                      /*
9006                      // TESTING THIS HERE... LATEST ADDITION
9007                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9008                      {
9009                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9010                         exp.op.exp2.destType = type2._class.registered.dataType;
9011                         if(type2._class.registered.dataType)
9012                            type2._class.registered.dataType.refCount++;
9013                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9014
9015                         //exp.expType = type2._class.registered.dataType; //type2;
9016                         //if(type2) type2.refCount++;
9017                      }
9018
9019                      // TESTING THIS HERE... LATEST ADDITION
9020                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9021                      {
9022                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9023                         exp.op.exp1.destType = type1._class.registered.dataType;
9024                         if(type1._class.registered.dataType)
9025                            type1._class.registered.dataType.refCount++;
9026                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9027                         exp.expType = type1._class.registered.dataType; //type1;
9028                         if(type1) type1.refCount++;
9029                      }
9030                      */
9031
9032                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9033                         {
9034                            if(exp.expType) FreeType(exp.expType);
9035                            exp.expType = exp.op.exp2.destType;
9036                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9037                         }
9038                         else if(type1 && type2)
9039                         {
9040                            char expString1[10240];
9041                            char expString2[10240];
9042                            char type1String[1024];
9043                            char type2String[1024];
9044                            expString1[0] = '\0';
9045                            expString2[0] = '\0';
9046                            type1String[0] = '\0';
9047                            type2String[0] = '\0';
9048                            if(inCompiler)
9049                            {
9050                               PrintExpression(exp.op.exp1, expString1);
9051                               ChangeCh(expString1, '\n', ' ');
9052                               PrintExpression(exp.op.exp2, expString2);
9053                               ChangeCh(expString2, '\n', ' ');
9054                               PrintType(exp.op.exp1.expType, type1String, false, true);
9055                               PrintType(exp.op.exp2.expType, type2String, false, true);
9056                            }
9057
9058                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9059
9060                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9061                            {
9062                               exp.expType = exp.op.exp1.expType;
9063                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9064                            }
9065                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9066                            {
9067                               exp.expType = exp.op.exp2.expType;
9068                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9069                            }
9070                         }
9071                      }
9072                   }
9073                }
9074                else if(type2)
9075                {
9076                   // Maybe this was meant to be an enum...
9077                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9078                   {
9079                      Type oldType = exp.op.exp1.expType;
9080                      exp.op.exp1.expType = null;
9081                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9082                         FreeType(oldType);
9083                      else
9084                         exp.op.exp1.expType = oldType;
9085                   }
9086
9087                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9088                   exp.op.exp1.destType = type2;
9089                   type2.refCount++;
9090                   /*
9091                   // TESTING THIS HERE... LATEST ADDITION
9092                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9093                   {
9094                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9095                      exp.op.exp1.destType = type1._class.registered.dataType;
9096                      if(type1._class.registered.dataType)
9097                         type1._class.registered.dataType.refCount++;
9098                   }
9099
9100                   // TESTING THIS HERE... LATEST ADDITION
9101                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9102                   {
9103                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9104                      exp.op.exp2.destType = type2._class.registered.dataType;
9105                      if(type2._class.registered.dataType)
9106                         type2._class.registered.dataType.refCount++;
9107                   }
9108                   */
9109
9110                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9111                   {
9112                      if(exp.expType) FreeType(exp.expType);
9113                      exp.expType = exp.op.exp1.destType;
9114                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9115                   }
9116                }
9117             }
9118             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9119             {
9120                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9121                {
9122                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9123                   // Convert e.g. / 4 into / 4.0
9124                   exp.op.exp1.destType = type2._class.registered.dataType;
9125                   if(type2._class.registered.dataType)
9126                      type2._class.registered.dataType.refCount++;
9127                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9128                }
9129                if(exp.op.op == '!')
9130                {
9131                   exp.expType = MkClassType("bool");
9132                   exp.expType.truth = true;
9133                }
9134                else
9135                {
9136                   exp.expType = type2;
9137                   if(type2) type2.refCount++;
9138                }
9139             }
9140             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9141             {
9142                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9143                {
9144                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9145                   // Convert e.g. / 4 into / 4.0
9146                   exp.op.exp2.destType = type1._class.registered.dataType;
9147                   if(type1._class.registered.dataType)
9148                      type1._class.registered.dataType.refCount++;
9149                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9150                }
9151                exp.expType = type1;
9152                if(type1) type1.refCount++;
9153             }
9154          }
9155
9156          yylloc = exp.loc;
9157          if(exp.op.exp1 && !exp.op.exp1.expType)
9158          {
9159             char expString[10000];
9160             expString[0] = '\0';
9161             if(inCompiler)
9162             {
9163                PrintExpression(exp.op.exp1, expString);
9164                ChangeCh(expString, '\n', ' ');
9165             }
9166             if(expString[0])
9167                Compiler_Error($"couldn't determine type of %s\n", expString);
9168          }
9169          if(exp.op.exp2 && !exp.op.exp2.expType)
9170          {
9171             char expString[10240];
9172             expString[0] = '\0';
9173             if(inCompiler)
9174             {
9175                PrintExpression(exp.op.exp2, expString);
9176                ChangeCh(expString, '\n', ' ');
9177             }
9178             if(expString[0])
9179                Compiler_Error($"couldn't determine type of %s\n", expString);
9180          }
9181
9182          if(boolResult)
9183          {
9184             FreeType(exp.expType);
9185             exp.expType = MkClassType("bool");
9186             exp.expType.truth = true;
9187          }
9188
9189          if(exp.op.op != SIZEOF)
9190             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9191                (!exp.op.exp2 || exp.op.exp2.isConstant);
9192
9193          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9194          {
9195             DeclareType(exp.op.exp2.expType, false, false);
9196          }
9197
9198          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9199             Compiler_Warning($"deleting const qualified object\n");
9200
9201          yylloc = oldyylloc;
9202
9203          FreeType(dummy);
9204          if(type2)
9205             FreeType(type2);
9206          break;
9207       }
9208       case bracketsExp:
9209       case extensionExpressionExp:
9210       {
9211          Expression e;
9212          exp.isConstant = true;
9213          for(e = exp.list->first; e; e = e.next)
9214          {
9215             bool inced = false;
9216             if(!e.next)
9217             {
9218                FreeType(e.destType);
9219                e.opDestType = exp.opDestType;
9220                e.destType = exp.destType;
9221                if(e.destType) { exp.destType.refCount++; e.destType.count++; inced = true; }
9222             }
9223             ProcessExpressionType(e);
9224             if(inced)
9225                exp.destType.count--;
9226             if(!exp.expType && !e.next)
9227             {
9228                exp.expType = e.expType;
9229                if(e.expType) e.expType.refCount++;
9230             }
9231             if(!e.isConstant)
9232                exp.isConstant = false;
9233          }
9234
9235          // In case a cast became a member...
9236          e = exp.list->first;
9237          if(!e.next && e.type == memberExp)
9238          {
9239             // Preserve prev, next
9240             Expression next = exp.next, prev = exp.prev;
9241
9242
9243             FreeType(exp.expType);
9244             FreeType(exp.destType);
9245             delete exp.list;
9246
9247             *exp = *e;
9248
9249             exp.prev = prev;
9250             exp.next = next;
9251
9252             delete e;
9253
9254             ProcessExpressionType(exp);
9255          }
9256          break;
9257       }
9258       case indexExp:
9259       {
9260          Expression e;
9261          exp.isConstant = true;
9262
9263          ProcessExpressionType(exp.index.exp);
9264          if(!exp.index.exp.isConstant)
9265             exp.isConstant = false;
9266
9267          if(exp.index.exp.expType)
9268          {
9269             Type source = exp.index.exp.expType;
9270             if(source.kind == classType && source._class && source._class.registered)
9271             {
9272                Class _class = source._class.registered;
9273                Class c = _class.templateClass ? _class.templateClass : _class;
9274                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9275                {
9276                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9277
9278                   if(exp.index.index && exp.index.index->last)
9279                   {
9280                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9281
9282                      if(type.kind == classType) type.constant = true;
9283                      else if(type.kind == pointerType)
9284                      {
9285                         Type t = type;
9286                         while(t.kind == pointerType) t = t.type;
9287                         t.constant = true;
9288                      }
9289
9290                      ((Expression)exp.index.index->last).destType = type;
9291                   }
9292                }
9293             }
9294          }
9295
9296          for(e = exp.index.index->first; e; e = e.next)
9297          {
9298             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9299             {
9300                if(e.destType) FreeType(e.destType);
9301                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9302             }
9303             ProcessExpressionType(e);
9304             if(!e.next)
9305             {
9306                // Check if this type is int
9307             }
9308             if(!e.isConstant)
9309                exp.isConstant = false;
9310          }
9311
9312          if(!exp.expType)
9313             exp.expType = Dereference(exp.index.exp.expType);
9314          if(exp.expType)
9315             DeclareType(exp.expType, false, false);
9316          break;
9317       }
9318       case callExp:
9319       {
9320          Expression e;
9321          Type functionType;
9322          Type methodType = null;
9323          char name[1024];
9324          name[0] = '\0';
9325
9326          if(inCompiler)
9327          {
9328             PrintExpression(exp.call.exp,  name);
9329             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9330             {
9331                //exp.call.exp.expType = null;
9332                PrintExpression(exp.call.exp,  name);
9333             }
9334          }
9335          if(exp.call.exp.type == identifierExp)
9336          {
9337             Expression idExp = exp.call.exp;
9338             Identifier id = idExp.identifier;
9339             if(!strcmp(id.string, "__builtin_frame_address"))
9340             {
9341                exp.expType = ProcessTypeString("void *", true);
9342                if(exp.call.arguments && exp.call.arguments->first)
9343                   ProcessExpressionType(exp.call.arguments->first);
9344                break;
9345             }
9346             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9347             {
9348                exp.expType = ProcessTypeString("int", true);
9349                if(exp.call.arguments && exp.call.arguments->first)
9350                   ProcessExpressionType(exp.call.arguments->first);
9351                break;
9352             }
9353             else if(!strcmp(id.string, "Max") ||
9354                !strcmp(id.string, "Min") ||
9355                !strcmp(id.string, "Sgn") ||
9356                !strcmp(id.string, "Abs"))
9357             {
9358                Expression a = null;
9359                Expression b = null;
9360                Expression tempExp1 = null, tempExp2 = null;
9361                if((!strcmp(id.string, "Max") ||
9362                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9363                {
9364                   a = exp.call.arguments->first;
9365                   b = exp.call.arguments->last;
9366                   tempExp1 = a;
9367                   tempExp2 = b;
9368                }
9369                else if(exp.call.arguments->count == 1)
9370                {
9371                   a = exp.call.arguments->first;
9372                   tempExp1 = a;
9373                }
9374
9375                if(a)
9376                {
9377                   exp.call.arguments->Clear();
9378                   idExp.identifier = null;
9379
9380                   FreeExpContents(exp);
9381
9382                   ProcessExpressionType(a);
9383                   if(b)
9384                      ProcessExpressionType(b);
9385
9386                   exp.type = bracketsExp;
9387                   exp.list = MkList();
9388
9389                   if(a.expType && (!b || b.expType))
9390                   {
9391                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9392                      {
9393                         // Use the simpleStruct name/ids for now...
9394                         if(inCompiler)
9395                         {
9396                            OldList * specs = MkList();
9397                            OldList * decls = MkList();
9398                            Declaration decl;
9399                            char temp1[1024], temp2[1024];
9400
9401                            GetTypeSpecs(a.expType, specs);
9402
9403                            if(a && !a.isConstant && a.type != identifierExp)
9404                            {
9405                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9406                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9407                               tempExp1 = QMkExpId(temp1);
9408                               tempExp1.expType = a.expType;
9409                               if(a.expType)
9410                                  a.expType.refCount++;
9411                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9412                            }
9413                            if(b && !b.isConstant && b.type != identifierExp)
9414                            {
9415                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9416                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9417                               tempExp2 = QMkExpId(temp2);
9418                               tempExp2.expType = b.expType;
9419                               if(b.expType)
9420                                  b.expType.refCount++;
9421                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9422                            }
9423
9424                            decl = MkDeclaration(specs, decls);
9425                            if(!curCompound.compound.declarations)
9426                               curCompound.compound.declarations = MkList();
9427                            curCompound.compound.declarations->Insert(null, decl);
9428                         }
9429                      }
9430                   }
9431
9432                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9433                   {
9434                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9435                      ListAdd(exp.list,
9436                         MkExpCondition(MkExpBrackets(MkListOne(
9437                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9438                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9439                      exp.expType = a.expType;
9440                      if(a.expType)
9441                         a.expType.refCount++;
9442                   }
9443                   else if(!strcmp(id.string, "Abs"))
9444                   {
9445                      ListAdd(exp.list,
9446                         MkExpCondition(MkExpBrackets(MkListOne(
9447                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9448                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9449                      exp.expType = a.expType;
9450                      if(a.expType)
9451                         a.expType.refCount++;
9452                   }
9453                   else if(!strcmp(id.string, "Sgn"))
9454                   {
9455                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9456                      ListAdd(exp.list,
9457                         MkExpCondition(MkExpBrackets(MkListOne(
9458                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9459                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9460                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9461                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9462                      exp.expType = ProcessTypeString("int", false);
9463                   }
9464
9465                   FreeExpression(tempExp1);
9466                   if(tempExp2) FreeExpression(tempExp2);
9467
9468                   FreeIdentifier(id);
9469                   break;
9470                }
9471             }
9472          }
9473
9474          {
9475             Type dummy
9476             {
9477                count = 1;
9478                refCount = 1;
9479             };
9480             if(!exp.call.exp.destType)
9481             {
9482                exp.call.exp.destType = dummy;
9483                dummy.refCount++;
9484             }
9485             ProcessExpressionType(exp.call.exp);
9486             if(exp.call.exp.destType == dummy)
9487             {
9488                FreeType(dummy);
9489                exp.call.exp.destType = null;
9490             }
9491             FreeType(dummy);
9492          }
9493
9494          // Check argument types against parameter types
9495          functionType = exp.call.exp.expType;
9496
9497          if(functionType && functionType.kind == TypeKind::methodType)
9498          {
9499             methodType = functionType;
9500             functionType = methodType.method.dataType;
9501
9502             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9503             // TOCHECK: Instead of doing this here could this be done per param?
9504             if(exp.call.exp.expType.usedClass)
9505             {
9506                char typeString[1024];
9507                typeString[0] = '\0';
9508                {
9509                   Symbol back = functionType.thisClass;
9510                   // Do not output class specifier here (thisclass was added to this)
9511                   functionType.thisClass = null;
9512                   PrintType(functionType, typeString, true, true);
9513                   functionType.thisClass = back;
9514                }
9515                if(strstr(typeString, "thisclass"))
9516                {
9517                   OldList * specs = MkList();
9518                   Declarator decl;
9519                   {
9520                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9521
9522                      decl = SpecDeclFromString(typeString, specs, null);
9523
9524                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9525                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9526                         exp.call.exp.expType.usedClass))
9527                         thisClassParams = false;
9528
9529                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9530                      {
9531                         Class backupThisClass = thisClass;
9532                         thisClass = exp.call.exp.expType.usedClass;
9533                         ProcessDeclarator(decl);
9534                         thisClass = backupThisClass;
9535                      }
9536
9537                      thisClassParams = true;
9538
9539                      functionType = ProcessType(specs, decl);
9540                      functionType.refCount = 0;
9541                      FinishTemplatesContext(context);
9542
9543                      // Mark parameters that were 'thisclass'
9544                      /*{
9545                         Type p, op;
9546                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9547                            p.wasThisClass = op.kind == thisClassType;
9548                      }*/
9549                   }
9550
9551                   FreeList(specs, FreeSpecifier);
9552                   FreeDeclarator(decl);
9553                 }
9554             }
9555          }
9556          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9557          {
9558             Type type = functionType.type;
9559             if(!functionType.refCount)
9560             {
9561                functionType.type = null;
9562                FreeType(functionType);
9563             }
9564             //methodType = functionType;
9565             functionType = type;
9566          }
9567          if(functionType && functionType.kind != TypeKind::functionType)
9568          {
9569             Compiler_Error($"called object %s is not a function\n", name);
9570          }
9571          else if(functionType)
9572          {
9573             bool emptyParams = false, noParams = false;
9574             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9575             Type type = functionType.params.first;
9576             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9577             int extra = 0;
9578             Location oldyylloc = yylloc;
9579
9580             if(!type) emptyParams = true;
9581
9582             // WORKING ON THIS:
9583             if(functionType.extraParam && e && functionType.thisClass)
9584             {
9585                e.destType = MkClassType(functionType.thisClass.string);
9586                e = e.next;
9587             }
9588
9589             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9590             // Fixed #141 by adding '&& !functionType.extraParam'
9591             if(!functionType.staticMethod && !functionType.extraParam)
9592             {
9593                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9594                   memberExp.member.exp.expType._class)
9595                {
9596                   type = MkClassType(memberExp.member.exp.expType._class.string);
9597                   if(e)
9598                   {
9599                      e.destType = type;
9600                      e = e.next;
9601                      type = functionType.params.first;
9602                   }
9603                   else
9604                      type.refCount = 0;
9605                }
9606                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9607                {
9608                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9609                   type.byReference = functionType.byReference;
9610                   type.typedByReference = functionType.typedByReference;
9611                   if(e)
9612                   {
9613                      // Allow manually passing a class for typed object
9614                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9615                         e = e.next;
9616                      e.destType = type;
9617                      e = e.next;
9618                      type = functionType.params.first;
9619                   }
9620                   else
9621                      type.refCount = 0;
9622                   //extra = 1;
9623                }
9624             }
9625
9626             if(type && type.kind == voidType)
9627             {
9628                noParams = true;
9629                if(!type.refCount) FreeType(type);
9630                type = null;
9631             }
9632
9633             for( ; e; e = e.next)
9634             {
9635                if(!type && !emptyParams)
9636                {
9637                   yylloc = e.loc;
9638                   if(methodType && methodType.methodClass)
9639                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9640                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9641                         noParams ? 0 : functionType.params.count);
9642                   else
9643                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9644                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9645                         noParams ? 0 : functionType.params.count);
9646                   break;
9647                }
9648
9649                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9650                {
9651                   Type templatedType = null;
9652                   Class _class = methodType.usedClass;
9653                   ClassTemplateParameter curParam = null;
9654                   int id = 0;
9655                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9656                   {
9657                      Class sClass;
9658                      for(sClass = _class; sClass; sClass = sClass.base)
9659                      {
9660                         if(sClass.templateClass) sClass = sClass.templateClass;
9661                         id = 0;
9662                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9663                         {
9664                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9665                            {
9666                               Class nextClass;
9667                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9668                               {
9669                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9670                                  id += nextClass.templateParams.count;
9671                               }
9672                               break;
9673                            }
9674                            id++;
9675                         }
9676                         if(curParam) break;
9677                      }
9678                   }
9679                   if(curParam && _class.templateArgs[id].dataTypeString)
9680                   {
9681                      bool constant = type.constant;
9682                      ClassTemplateArgument arg = _class.templateArgs[id];
9683                      {
9684                         Context context = SetupTemplatesContext(_class);
9685
9686                         /*if(!arg.dataType)
9687                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9688                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9689                         FinishTemplatesContext(context);
9690                      }
9691
9692                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9693                      else if(templatedType.kind == pointerType)
9694                      {
9695                         Type t = templatedType.type;
9696                         while(t.kind == pointerType) t = t.type;
9697                         if(constant) t.constant = constant;
9698                      }
9699
9700                      e.destType = templatedType;
9701                      if(templatedType)
9702                      {
9703                         templatedType.passAsTemplate = true;
9704                         // templatedType.refCount++;
9705                      }
9706                   }
9707                   else
9708                   {
9709                      e.destType = type;
9710                      if(type) type.refCount++;
9711                   }
9712                }
9713                else
9714                {
9715                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9716                   {
9717                      e.destType = type.prev;
9718                      e.destType.refCount++;
9719                   }
9720                   else
9721                   {
9722                      e.destType = type;
9723                      if(type) type.refCount++;
9724                   }
9725                }
9726                // Don't reach the end for the ellipsis
9727                if(type && type.kind != ellipsisType)
9728                {
9729                   Type next = type.next;
9730                   if(!type.refCount) FreeType(type);
9731                   type = next;
9732                }
9733             }
9734
9735             if(type && type.kind != ellipsisType)
9736             {
9737                if(methodType && methodType.methodClass)
9738                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9739                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9740                      functionType.params.count + extra);
9741                else
9742                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9743                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9744                      functionType.params.count + extra);
9745             }
9746             yylloc = oldyylloc;
9747             if(type && !type.refCount) FreeType(type);
9748          }
9749          else
9750          {
9751             functionType = Type
9752             {
9753                refCount = 0;
9754                kind = TypeKind::functionType;
9755             };
9756
9757             if(exp.call.exp.type == identifierExp)
9758             {
9759                char * string = exp.call.exp.identifier.string;
9760                if(inCompiler)
9761                {
9762                   Symbol symbol;
9763                   Location oldyylloc = yylloc;
9764
9765                   yylloc = exp.call.exp.identifier.loc;
9766                   if(strstr(string, "__builtin_") == string)
9767                   {
9768                      if(exp.destType)
9769                      {
9770                         functionType.returnType = exp.destType;
9771                         exp.destType.refCount++;
9772                      }
9773                   }
9774                   else
9775                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9776                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9777                   globalContext.symbols.Add((BTNode)symbol);
9778                   if(strstr(symbol.string, "::"))
9779                      globalContext.hasNameSpace = true;
9780
9781                   yylloc = oldyylloc;
9782                }
9783             }
9784             else if(exp.call.exp.type == memberExp)
9785             {
9786                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9787                   exp.call.exp.member.member.string);*/
9788             }
9789             else
9790                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9791
9792             if(!functionType.returnType)
9793             {
9794                functionType.returnType = Type
9795                {
9796                   refCount = 1;
9797                   kind = intType;
9798                };
9799             }
9800          }
9801          if(functionType && functionType.kind == TypeKind::functionType)
9802          {
9803             exp.expType = functionType.returnType;
9804
9805             if(functionType.returnType)
9806                functionType.returnType.refCount++;
9807
9808             if(!functionType.refCount)
9809                FreeType(functionType);
9810          }
9811
9812          if(exp.call.arguments)
9813          {
9814             for(e = exp.call.arguments->first; e; e = e.next)
9815                ProcessExpressionType(e);
9816          }
9817          break;
9818       }
9819       case memberExp:
9820       {
9821          Type type;
9822          Location oldyylloc = yylloc;
9823          bool thisPtr;
9824          Expression checkExp = exp.member.exp;
9825          while(checkExp)
9826          {
9827             if(checkExp.type == castExp)
9828                checkExp = checkExp.cast.exp;
9829             else if(checkExp.type == bracketsExp)
9830                checkExp = checkExp.list ? checkExp.list->first : null;
9831             else
9832                break;
9833          }
9834
9835          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9836          exp.thisPtr = thisPtr;
9837
9838          // DOING THIS LATER NOW...
9839          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9840          {
9841             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9842             /* TODO: Name Space Fix ups
9843             if(!exp.member.member.classSym)
9844                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9845             */
9846          }
9847
9848          ProcessExpressionType(exp.member.exp);
9849          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9850             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9851          {
9852             exp.isConstant = false;
9853          }
9854          else
9855             exp.isConstant = exp.member.exp.isConstant;
9856          type = exp.member.exp.expType;
9857
9858          yylloc = exp.loc;
9859
9860          if(type && (type.kind == templateType))
9861          {
9862             Class _class = thisClass ? thisClass : currentClass;
9863             ClassTemplateParameter param = null;
9864             if(_class)
9865             {
9866                for(param = _class.templateParams.first; param; param = param.next)
9867                {
9868                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9869                      break;
9870                }
9871             }
9872             if(param && param.defaultArg.member)
9873             {
9874                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9875                if(argExp)
9876                {
9877                   Expression expMember = exp.member.exp;
9878                   Declarator decl;
9879                   OldList * specs = MkList();
9880                   char thisClassTypeString[1024];
9881
9882                   FreeIdentifier(exp.member.member);
9883
9884                   ProcessExpressionType(argExp);
9885
9886                   {
9887                      char * colon = strstr(param.defaultArg.memberString, "::");
9888                      if(colon)
9889                      {
9890                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9891                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9892                      }
9893                      else
9894                         strcpy(thisClassTypeString, _class.fullName);
9895                   }
9896
9897                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9898
9899                   exp.expType = ProcessType(specs, decl);
9900                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9901                   {
9902                      Class expClass = exp.expType._class.registered;
9903                      Class cClass = null;
9904                      int paramCount = 0;
9905                      int lastParam = -1;
9906
9907                      char templateString[1024];
9908                      ClassTemplateParameter param;
9909                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9910                      for(cClass = expClass; cClass; cClass = cClass.base)
9911                      {
9912                         int p = 0;
9913                         for(param = cClass.templateParams.first; param; param = param.next)
9914                         {
9915                            int id = p;
9916                            Class sClass;
9917                            ClassTemplateArgument arg;
9918                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9919                            arg = expClass.templateArgs[id];
9920
9921                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9922                            {
9923                               ClassTemplateParameter cParam;
9924                               //int p = numParams - sClass.templateParams.count;
9925                               int p = 0;
9926                               Class nextClass;
9927                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9928
9929                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9930                               {
9931                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9932                                  {
9933                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9934                                     {
9935                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9936                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9937                                        break;
9938                                     }
9939                                  }
9940                               }
9941                            }
9942
9943                            {
9944                               char argument[256];
9945                               argument[0] = '\0';
9946                               /*if(arg.name)
9947                               {
9948                                  strcat(argument, arg.name.string);
9949                                  strcat(argument, " = ");
9950                               }*/
9951                               switch(param.type)
9952                               {
9953                                  case expression:
9954                                  {
9955                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9956                                     char expString[1024];
9957                                     OldList * specs = MkList();
9958                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9959                                     Expression exp;
9960                                     char * string = PrintHexUInt64(arg.expression.ui64);
9961                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9962                                     delete string;
9963
9964                                     ProcessExpressionType(exp);
9965                                     ComputeExpression(exp);
9966                                     expString[0] = '\0';
9967                                     PrintExpression(exp, expString);
9968                                     strcat(argument, expString);
9969                                     // delete exp;
9970                                     FreeExpression(exp);
9971                                     break;
9972                                  }
9973                                  case identifier:
9974                                  {
9975                                     strcat(argument, arg.member.name);
9976                                     break;
9977                                  }
9978                                  case TemplateParameterType::type:
9979                                  {
9980                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9981                                     {
9982                                        if(!strcmp(arg.dataTypeString, "thisclass"))
9983                                           strcat(argument, thisClassTypeString);
9984                                        else
9985                                           strcat(argument, arg.dataTypeString);
9986                                     }
9987                                     break;
9988                                  }
9989                               }
9990                               if(argument[0])
9991                               {
9992                                  if(paramCount) strcat(templateString, ", ");
9993                                  if(lastParam != p - 1)
9994                                  {
9995                                     strcat(templateString, param.name);
9996                                     strcat(templateString, " = ");
9997                                  }
9998                                  strcat(templateString, argument);
9999                                  paramCount++;
10000                                  lastParam = p;
10001                               }
10002                               p++;
10003                            }
10004                         }
10005                      }
10006                      {
10007                         int len = strlen(templateString);
10008                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10009                         templateString[len++] = '>';
10010                         templateString[len++] = '\0';
10011                      }
10012                      {
10013                         Context context = SetupTemplatesContext(_class);
10014                         FreeType(exp.expType);
10015                         exp.expType = ProcessTypeString(templateString, false);
10016                         FinishTemplatesContext(context);
10017                      }
10018                   }
10019
10020                   // *([expType] *)(((byte *)[exp.member.exp]) + [argExp].member.offset)
10021                   exp.type = bracketsExp;
10022                   exp.list = MkListOne(MkExpOp(null, '*',
10023                   /*opExp;
10024                   exp.op.op = '*';
10025                   exp.op.exp1 = null;
10026                   exp.op.exp2 = */
10027                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10028                      MkExpBrackets(MkListOne(
10029                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), expMember))),
10030                            '+',
10031                            MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10032                            '+',
10033                            MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10034
10035                            ));
10036                }
10037             }
10038             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10039                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10040             {
10041                type = ProcessTemplateParameterType(type.templateParameter);
10042             }
10043          }
10044          // TODO: *** This seems to be where we should add method support for all basic types ***
10045          if(type && (type.kind == templateType));
10046          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10047                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10048                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10049                           (type.kind == pointerType && type.type.kind == charType)))
10050          {
10051             Identifier id = exp.member.member;
10052             TypeKind typeKind = type.kind;
10053             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10054             if(typeKind == subClassType && exp.member.exp.type == classExp)
10055             {
10056                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10057                typeKind = classType;
10058             }
10059
10060             if(id)
10061             {
10062                if(typeKind == intType || typeKind == enumType)
10063                   _class = eSystem_FindClass(privateModule, "int");
10064                else if(!_class)
10065                {
10066                   if(type.kind == classType && type._class && type._class.registered)
10067                   {
10068                      _class = type._class.registered;
10069                   }
10070                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10071                   {
10072                      _class = FindClass("char *").registered;
10073                   }
10074                   else if(type.kind == pointerType)
10075                   {
10076                      _class = eSystem_FindClass(privateModule, "uintptr");
10077                      FreeType(exp.expType);
10078                      exp.expType = ProcessTypeString("uintptr", false);
10079                      exp.byReference = true;
10080                   }
10081                   else
10082                   {
10083                      char string[1024] = "";
10084                      Symbol classSym;
10085                      PrintTypeNoConst(type, string, false, true);
10086                      classSym = FindClass(string);
10087                      if(classSym) _class = classSym.registered;
10088                   }
10089                }
10090             }
10091
10092             if(_class && id)
10093             {
10094                /*bool thisPtr =
10095                   (exp.member.exp.type == identifierExp &&
10096                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10097                Property prop = null;
10098                Method method = null;
10099                DataMember member = null;
10100                Property revConvert = null;
10101                ClassProperty classProp = null;
10102
10103                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10104                   exp.member.memberType = propertyMember;
10105
10106                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10107                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10108
10109                if(typeKind != subClassType)
10110                {
10111                   // Prioritize data members over properties for "this"
10112                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10113                   {
10114                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10115                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10116                      {
10117                         prop = eClass_FindProperty(_class, id.string, privateModule);
10118                         if(prop)
10119                            member = null;
10120                      }
10121                      if(!member && !prop)
10122                         prop = eClass_FindProperty(_class, id.string, privateModule);
10123                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10124                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10125                         exp.member.thisPtr = true;
10126                   }
10127                   // Prioritize properties over data members otherwise
10128                   else
10129                   {
10130                      bool useMemberForNonConst = false;
10131                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10132                      if(!id.classSym)
10133                      {
10134                         prop = eClass_FindProperty(_class, id.string, null);
10135
10136                         useMemberForNonConst = prop && exp.destType &&
10137                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10138                               !strncmp(prop.dataTypeString, "const ", 6);
10139
10140                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10141                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10142                      }
10143
10144                      if((!prop || useMemberForNonConst) && !member)
10145                      {
10146                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10147                         if(!method)
10148                         {
10149                            prop = eClass_FindProperty(_class, id.string, privateModule);
10150
10151                            useMemberForNonConst |= prop && exp.destType &&
10152                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10153                                  !strncmp(prop.dataTypeString, "const ", 6);
10154
10155                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10156                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10157                         }
10158                      }
10159
10160                      if(member && prop)
10161                      {
10162                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10163                            prop = null;
10164                         else
10165                            member = null;
10166                      }
10167                   }
10168                }
10169                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10170                   method = eClass_FindMethod(_class, id.string, privateModule);
10171                if(!prop && !member && !method)
10172                {
10173                   if(typeKind == subClassType)
10174                   {
10175                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10176                      if(classProp)
10177                      {
10178                         exp.member.memberType = classPropertyMember;
10179                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10180                      }
10181                      else
10182                      {
10183                         // Assume this is a class_data member
10184                         char structName[1024];
10185                         Identifier id = exp.member.member;
10186                         Expression classExp = exp.member.exp;
10187                         type.refCount++;
10188
10189                         FreeType(classExp.expType);
10190                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10191
10192                         strcpy(structName, "__ecereClassData_");
10193                         FullClassNameCat(structName, type._class.string, false);
10194                         exp.type = pointerExp;
10195                         exp.member.member = id;
10196
10197                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10198                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10199                               MkExpBrackets(MkListOne(MkExpOp(
10200                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10201                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10202                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10203                                  )));
10204
10205                         FreeType(type);
10206
10207                         ProcessExpressionType(exp);
10208                         return;
10209                      }
10210                   }
10211                   else
10212                   {
10213                      // Check for reverse conversion
10214                      // (Convert in an instantiation later, so that we can use
10215                      //  deep properties system)
10216                      Symbol classSym = FindClass(id.string);
10217                      if(classSym)
10218                      {
10219                         Class convertClass = classSym.registered;
10220                         if(convertClass)
10221                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10222                      }
10223                   }
10224                }
10225
10226                //if(!exp.member.exp.destType)
10227                if(exp.member.exp.destType)
10228                   FreeType(exp.member.exp.destType);
10229                {
10230                   if(method && !method._class.symbol)
10231                      method._class.symbol = FindClass(method._class.fullName);
10232                   if(prop && !prop._class.symbol)
10233                      prop._class.symbol = FindClass(prop._class.fullName);
10234
10235                   exp.member.exp.destType = Type
10236                   {
10237                      refCount = 1;
10238                      kind = classType;
10239                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10240                      // wasThisClass = type ? type.wasThisClass : false;
10241                   };
10242                }
10243
10244                if(prop)
10245                {
10246                   exp.member.memberType = propertyMember;
10247                   if(!prop.dataType)
10248                      ProcessPropertyType(prop);
10249                   exp.expType = prop.dataType;
10250                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10251                   {
10252                      Type type { };
10253                      CopyTypeInto(type, exp.expType);
10254                      type.refCount = 1;
10255                      type.constant = true;
10256                      exp.expType = type;
10257                   }
10258                   else if(prop.dataType)
10259                      prop.dataType.refCount++;
10260                }
10261                else if(member)
10262                {
10263                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10264                   {
10265                      FreeExpContents(exp);
10266                      exp.type = identifierExp;
10267                      exp.identifier = MkIdentifier("class");
10268                      ProcessExpressionType(exp);
10269                      return;
10270                   }
10271
10272                   exp.member.memberType = dataMember;
10273                   DeclareStruct(_class.fullName, false);
10274                   if(!member.dataType)
10275                   {
10276                      Context context = SetupTemplatesContext(_class);
10277                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10278                      FinishTemplatesContext(context);
10279                   }
10280                   exp.expType = member.dataType;
10281                   if(member.dataType) member.dataType.refCount++;
10282                }
10283                else if(revConvert)
10284                {
10285                   exp.member.memberType = reverseConversionMember;
10286                   exp.expType = MkClassType(revConvert._class.fullName);
10287                }
10288                else if(method)
10289                {
10290                   //if(inCompiler)
10291                   {
10292                      /*if(id._class)
10293                      {
10294                         exp.type = identifierExp;
10295                         exp.identifier = exp.member.member;
10296                      }
10297                      else*/
10298                         exp.member.memberType = methodMember;
10299                   }
10300                   if(!method.dataType)
10301                      ProcessMethodType(method);
10302                   exp.expType = Type
10303                   {
10304                      refCount = 1;
10305                      kind = methodType;
10306                      method = method;
10307                   };
10308
10309                   // Tricky spot here... To use instance versus class virtual table
10310                   // Put it back to what it was... What did we break?
10311
10312                   // Had to put it back for overriding Main of Thread global instance
10313
10314                   //exp.expType.methodClass = _class;
10315                   exp.expType.methodClass = (id && id._class) ? _class : null;
10316
10317                   // Need the actual class used for templated classes
10318                   exp.expType.usedClass = _class;
10319                }
10320                else if(!classProp)
10321                {
10322                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10323                   {
10324                      FreeExpContents(exp);
10325                      exp.type = identifierExp;
10326                      exp.identifier = MkIdentifier("class");
10327                      FreeType(exp.expType);
10328                      exp.expType = MkClassType("ecere::com::Class");
10329                      return;
10330                   }
10331                   yylloc = exp.member.member.loc;
10332                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10333                   if(inCompiler)
10334                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10335                }
10336
10337                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10338                {
10339                   Class tClass;
10340
10341                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10342                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10343
10344                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10345                   {
10346                      int id = 0;
10347                      ClassTemplateParameter curParam = null;
10348                      Class sClass;
10349
10350                      for(sClass = tClass; sClass; sClass = sClass.base)
10351                      {
10352                         id = 0;
10353                         if(sClass.templateClass) sClass = sClass.templateClass;
10354                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10355                         {
10356                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10357                            {
10358                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10359                                  id += sClass.templateParams.count;
10360                               break;
10361                            }
10362                            id++;
10363                         }
10364                         if(curParam) break;
10365                      }
10366
10367                      if(curParam && tClass.templateArgs[id].dataTypeString)
10368                      {
10369                         ClassTemplateArgument arg = tClass.templateArgs[id];
10370                         Context context = SetupTemplatesContext(tClass);
10371                         bool constant = exp.expType.constant;
10372                         /*if(!arg.dataType)
10373                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10374                         FreeType(exp.expType);
10375
10376                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10377                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10378                         else if(exp.expType.kind == pointerType)
10379                         {
10380                            Type t = exp.expType.type;
10381                            while(t.kind == pointerType) t = t.type;
10382                            if(constant) t.constant = constant;
10383                         }
10384                         if(exp.expType)
10385                         {
10386                            if(exp.expType.kind == thisClassType)
10387                            {
10388                               FreeType(exp.expType);
10389                               exp.expType = ReplaceThisClassType(_class);
10390                            }
10391
10392                            if(tClass.templateClass && (exp.expType.kind != templateType || (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType))))
10393                               exp.expType.passAsTemplate = true;
10394                            //exp.expType.refCount++;
10395                            if(!exp.destType)
10396                            {
10397                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10398                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10399                               else if(exp.destType.kind == pointerType)
10400                               {
10401                                  Type t = exp.destType.type;
10402                                  while(t.kind == pointerType) t = t.type;
10403                                  if(constant) t.constant = constant;
10404                               }
10405
10406                               //exp.destType.refCount++;
10407
10408                               if(exp.destType.kind == thisClassType)
10409                               {
10410                                  FreeType(exp.destType);
10411                                  exp.destType = ReplaceThisClassType(_class);
10412                               }
10413                            }
10414                         }
10415                         FinishTemplatesContext(context);
10416                      }
10417                   }
10418                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10419                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10420                   {
10421                      int id = 0;
10422                      ClassTemplateParameter curParam = null;
10423                      Class sClass;
10424
10425                      for(sClass = tClass; sClass; sClass = sClass.base)
10426                      {
10427                         id = 0;
10428                         if(sClass.templateClass) sClass = sClass.templateClass;
10429                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10430                         {
10431                            if(curParam.type == TemplateParameterType::type &&
10432                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10433                            {
10434                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10435                                  id += sClass.templateParams.count;
10436                               break;
10437                            }
10438                            id++;
10439                         }
10440                         if(curParam) break;
10441                      }
10442
10443                      if(curParam)
10444                      {
10445                         ClassTemplateArgument arg = tClass.templateArgs[id];
10446                         Context context = SetupTemplatesContext(tClass);
10447                         Type basicType;
10448                         /*if(!arg.dataType)
10449                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10450
10451                         basicType = ProcessTypeString(arg.dataTypeString, false);
10452                         if(basicType)
10453                         {
10454                            if(basicType.kind == thisClassType)
10455                            {
10456                               FreeType(basicType);
10457                               basicType = ReplaceThisClassType(_class);
10458                            }
10459
10460                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10461                            if(tClass.templateClass)
10462                               basicType.passAsTemplate = true;
10463                            */
10464
10465                            FreeType(exp.expType);
10466
10467                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10468                            //exp.expType.refCount++;
10469                            if(!exp.destType)
10470                            {
10471                               exp.destType = exp.expType;
10472                               exp.destType.refCount++;
10473                            }
10474
10475                            {
10476                               Expression newExp { };
10477                               OldList * specs = MkList();
10478                               Declarator decl;
10479                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10480                               *newExp = *exp;
10481                               if(exp.destType) exp.destType.refCount++;
10482                               if(exp.expType)  exp.expType.refCount++;
10483                               exp.type = castExp;
10484                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10485                               exp.cast.exp = newExp;
10486                               //FreeType(exp.expType);
10487                               //exp.expType = null;
10488                               //ProcessExpressionType(sourceExp);
10489                            }
10490                         }
10491                         FinishTemplatesContext(context);
10492                      }
10493                   }
10494                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10495                   {
10496                      Class expClass = exp.expType._class.registered;
10497                      if(expClass)
10498                      {
10499                         Class cClass = null;
10500                         int p = 0;
10501                         int paramCount = 0;
10502                         int lastParam = -1;
10503                         char templateString[1024];
10504                         ClassTemplateParameter param;
10505                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10506                         while(cClass != expClass)
10507                         {
10508                            Class sClass;
10509                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10510                            cClass = sClass;
10511
10512                            for(param = cClass.templateParams.first; param; param = param.next)
10513                            {
10514                               Class cClassCur = null;
10515                               int cp = 0;
10516                               ClassTemplateParameter paramCur = null;
10517                               ClassTemplateArgument arg;
10518                               while(cClassCur != tClass && !paramCur)
10519                               {
10520                                  Class sClassCur;
10521                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10522                                  cClassCur = sClassCur;
10523
10524                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10525                                  {
10526                                     if(!strcmp(paramCur.name, param.name))
10527                                     {
10528
10529                                        break;
10530                                     }
10531                                     cp++;
10532                                  }
10533                               }
10534                               if(paramCur && paramCur.type == TemplateParameterType::type)
10535                                  arg = tClass.templateArgs[cp];
10536                               else
10537                                  arg = expClass.templateArgs[p];
10538
10539                               {
10540                                  char argument[256];
10541                                  argument[0] = '\0';
10542                                  /*if(arg.name)
10543                                  {
10544                                     strcat(argument, arg.name.string);
10545                                     strcat(argument, " = ");
10546                                  }*/
10547                                  switch(param.type)
10548                                  {
10549                                     case expression:
10550                                     {
10551                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10552                                        char expString[1024];
10553                                        OldList * specs = MkList();
10554                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10555                                        Expression exp;
10556                                        char * string = PrintHexUInt64(arg.expression.ui64);
10557                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10558                                        delete string;
10559
10560                                        ProcessExpressionType(exp);
10561                                        ComputeExpression(exp);
10562                                        expString[0] = '\0';
10563                                        PrintExpression(exp, expString);
10564                                        strcat(argument, expString);
10565                                        // delete exp;
10566                                        FreeExpression(exp);
10567                                        break;
10568                                     }
10569                                     case identifier:
10570                                     {
10571                                        strcat(argument, arg.member.name);
10572                                        break;
10573                                     }
10574                                     case TemplateParameterType::type:
10575                                     {
10576                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10577                                           strcat(argument, arg.dataTypeString);
10578                                        break;
10579                                     }
10580                                  }
10581                                  if(argument[0])
10582                                  {
10583                                     if(paramCount) strcat(templateString, ", ");
10584                                     if(lastParam != p - 1)
10585                                     {
10586                                        strcat(templateString, param.name);
10587                                        strcat(templateString, " = ");
10588                                     }
10589                                     strcat(templateString, argument);
10590                                     paramCount++;
10591                                     lastParam = p;
10592                                  }
10593                               }
10594                               p++;
10595                            }
10596                         }
10597                         {
10598                            int len = strlen(templateString);
10599                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10600                            templateString[len++] = '>';
10601                            templateString[len++] = '\0';
10602                         }
10603
10604                         FreeType(exp.expType);
10605                         {
10606                            Context context = SetupTemplatesContext(tClass);
10607                            exp.expType = ProcessTypeString(templateString, false);
10608                            FinishTemplatesContext(context);
10609                         }
10610                      }
10611                   }
10612                }
10613             }
10614             else
10615                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10616          }
10617          else if(type && (type.kind == structType || type.kind == unionType))
10618          {
10619             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10620             if(memberType)
10621             {
10622                exp.expType = memberType;
10623                if(memberType)
10624                   memberType.refCount++;
10625             }
10626          }
10627          else
10628          {
10629             char expString[10240];
10630             expString[0] = '\0';
10631             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10632             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10633          }
10634
10635          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10636          {
10637             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10638             {
10639                Identifier id = exp.member.member;
10640                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10641                if(_class)
10642                {
10643                   FreeType(exp.expType);
10644                   exp.expType = ReplaceThisClassType(_class);
10645                }
10646             }
10647          }
10648          yylloc = oldyylloc;
10649          break;
10650       }
10651       // Convert x->y into (*x).y
10652       case pointerExp:
10653       {
10654          Type destType = exp.destType;
10655
10656          // DOING THIS LATER NOW...
10657          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10658          {
10659             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10660             /* TODO: Name Space Fix ups
10661             if(!exp.member.member.classSym)
10662                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10663             */
10664          }
10665
10666          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10667          exp.type = memberExp;
10668          if(destType)
10669             destType.count++;
10670          ProcessExpressionType(exp);
10671          if(destType)
10672             destType.count--;
10673          break;
10674       }
10675       case classSizeExp:
10676       {
10677          //ComputeExpression(exp);
10678
10679          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10680          if(classSym && classSym.registered)
10681          {
10682             if(classSym.registered.type == noHeadClass)
10683             {
10684                char name[1024];
10685                name[0] = '\0';
10686                DeclareStruct(classSym.string, false);
10687                FreeSpecifier(exp._class);
10688                exp.type = typeSizeExp;
10689                FullClassNameCat(name, classSym.string, false);
10690                exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10691             }
10692             else
10693             {
10694                if(classSym.registered.fixed)
10695                {
10696                   FreeSpecifier(exp._class);
10697                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10698                   exp.type = constantExp;
10699                }
10700                else
10701                {
10702                   char className[1024];
10703                   strcpy(className, "__ecereClass_");
10704                   FullClassNameCat(className, classSym.string, true);
10705                   //MangleClassName(className);
10706
10707                   DeclareClass(classSym, className);
10708
10709                   FreeExpContents(exp);
10710                   exp.type = pointerExp;
10711                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10712                   exp.member.member = MkIdentifier("structSize");
10713                }
10714             }
10715          }
10716
10717          exp.expType = Type
10718          {
10719             refCount = 1;
10720             kind = intSizeType;
10721          };
10722          // exp.isConstant = true;
10723          break;
10724       }
10725       case typeSizeExp:
10726       {
10727          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10728
10729          exp.expType = Type
10730          {
10731             refCount = 1;
10732             kind = intSizeType;
10733          };
10734          exp.isConstant = true;
10735
10736          DeclareType(type, false, false);
10737          FreeType(type);
10738          break;
10739       }
10740       case castExp:
10741       {
10742          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10743          type.count = 1;
10744          FreeType(exp.cast.exp.destType);
10745          exp.cast.exp.destType = type;
10746          type.refCount++;
10747          type.casted = true;
10748          ProcessExpressionType(exp.cast.exp);
10749          type.casted = false;
10750          type.count = 0;
10751          exp.expType = type;
10752          //type.refCount++;
10753
10754          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10755          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10756          {
10757             void * prev = exp.prev, * next = exp.next;
10758             Type expType = exp.cast.exp.destType;
10759             Expression castExp = exp.cast.exp;
10760             Type destType = exp.destType;
10761
10762             if(expType) expType.refCount++;
10763
10764             //FreeType(exp.destType);
10765             FreeType(exp.expType);
10766             FreeTypeName(exp.cast.typeName);
10767
10768             *exp = *castExp;
10769             FreeType(exp.expType);
10770             FreeType(exp.destType);
10771
10772             exp.expType = expType;
10773             exp.destType = destType;
10774
10775             delete castExp;
10776
10777             exp.prev = prev;
10778             exp.next = next;
10779
10780          }
10781          else
10782          {
10783             exp.isConstant = exp.cast.exp.isConstant;
10784          }
10785          //FreeType(type);
10786          break;
10787       }
10788       case extensionInitializerExp:
10789       {
10790          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10791          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10792          // ProcessInitializer(exp.initializer.initializer, type);
10793          exp.expType = type;
10794          break;
10795       }
10796       case vaArgExp:
10797       {
10798          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10799          ProcessExpressionType(exp.vaArg.exp);
10800          exp.expType = type;
10801          break;
10802       }
10803       case conditionExp:
10804       {
10805          Expression e;
10806          exp.isConstant = true;
10807
10808          FreeType(exp.cond.cond.destType);
10809          exp.cond.cond.destType = MkClassType("bool");
10810          exp.cond.cond.destType.truth = true;
10811          ProcessExpressionType(exp.cond.cond);
10812          if(!exp.cond.cond.isConstant)
10813             exp.isConstant = false;
10814          for(e = exp.cond.exp->first; e; e = e.next)
10815          {
10816             if(!e.next)
10817             {
10818                FreeType(e.destType);
10819                e.destType = exp.destType;
10820                if(e.destType) e.destType.refCount++;
10821             }
10822             ProcessExpressionType(e);
10823             if(!e.next)
10824             {
10825                exp.expType = e.expType;
10826                if(e.expType) e.expType.refCount++;
10827             }
10828             if(!e.isConstant)
10829                exp.isConstant = false;
10830          }
10831
10832          FreeType(exp.cond.elseExp.destType);
10833          // Added this check if we failed to find an expType
10834          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10835
10836          // Reversed it...
10837          exp.cond.elseExp.destType = exp.destType ? exp.destType : exp.expType;
10838
10839          if(exp.cond.elseExp.destType)
10840             exp.cond.elseExp.destType.refCount++;
10841          ProcessExpressionType(exp.cond.elseExp);
10842
10843          // FIXED THIS: Was done before calling process on elseExp
10844          if(!exp.cond.elseExp.isConstant)
10845             exp.isConstant = false;
10846          break;
10847       }
10848       case extensionCompoundExp:
10849       {
10850          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10851          {
10852             Statement last = exp.compound.compound.statements->last;
10853             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10854             {
10855                ((Expression)last.expressions->last).destType = exp.destType;
10856                if(exp.destType)
10857                   exp.destType.refCount++;
10858             }
10859             ProcessStatement(exp.compound);
10860             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10861             if(exp.expType)
10862                exp.expType.refCount++;
10863          }
10864          break;
10865       }
10866       case classExp:
10867       {
10868          Specifier spec = exp._classExp.specifiers->first;
10869          if(spec && spec.type == nameSpecifier)
10870          {
10871             exp.expType = MkClassType(spec.name);
10872             exp.expType.kind = subClassType;
10873             exp.byReference = true;
10874          }
10875          else
10876          {
10877             exp.expType = MkClassType("ecere::com::Class");
10878             exp.byReference = true;
10879          }
10880          break;
10881       }
10882       case classDataExp:
10883       {
10884          Class _class = thisClass ? thisClass : currentClass;
10885          if(_class)
10886          {
10887             Identifier id = exp.classData.id;
10888             char structName[1024];
10889             Expression classExp;
10890             strcpy(structName, "__ecereClassData_");
10891             FullClassNameCat(structName, _class.fullName, false);
10892             exp.type = pointerExp;
10893             exp.member.member = id;
10894             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10895                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10896             else
10897                classExp = MkExpIdentifier(MkIdentifier("class"));
10898
10899             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10900                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10901                   MkExpBrackets(MkListOne(MkExpOp(
10902                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10903                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10904                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10905                      )));
10906
10907             ProcessExpressionType(exp);
10908             return;
10909          }
10910          break;
10911       }
10912       case arrayExp:
10913       {
10914          Type type = null;
10915          const char * typeString = null;
10916          char typeStringBuf[1024];
10917          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
10918             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
10919          {
10920             Class templateClass = exp.destType._class.registered;
10921             typeString = templateClass.templateArgs[2].dataTypeString;
10922          }
10923          else if(exp.list)
10924          {
10925             // Guess type from expressions in the array
10926             Expression e;
10927             for(e = exp.list->first; e; e = e.next)
10928             {
10929                ProcessExpressionType(e);
10930                if(e.expType)
10931                {
10932                   if(!type) { type = e.expType; type.refCount++; }
10933                   else
10934                   {
10935                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
10936                      if(!MatchTypeExpression(e, type, null, false, true))
10937                      {
10938                         FreeType(type);
10939                         type = e.expType;
10940                         e.expType = null;
10941
10942                         e = exp.list->first;
10943                         ProcessExpressionType(e);
10944                         if(e.expType)
10945                         {
10946                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
10947                            if(!MatchTypeExpression(e, type, null, false, true))
10948                            {
10949                               FreeType(e.expType);
10950                               e.expType = null;
10951                               FreeType(type);
10952                               type = null;
10953                               break;
10954                            }
10955                         }
10956                      }
10957                   }
10958                   if(e.expType)
10959                   {
10960                      FreeType(e.expType);
10961                      e.expType = null;
10962                   }
10963                }
10964             }
10965             if(type)
10966             {
10967                typeStringBuf[0] = '\0';
10968                PrintTypeNoConst(type, typeStringBuf, false, true);
10969                typeString = typeStringBuf;
10970                FreeType(type);
10971                type = null;
10972             }
10973          }
10974          if(typeString)
10975          {
10976             /*
10977             (Container)& (struct BuiltInContainer)
10978             {
10979                ._vTbl = class(BuiltInContainer)._vTbl,
10980                ._class = class(BuiltInContainer),
10981                .refCount = 0,
10982                .data = (int[]){ 1, 7, 3, 4, 5 },
10983                .count = 5,
10984                .type = class(int),
10985             }
10986             */
10987             char templateString[1024];
10988             OldList * initializers = MkList();
10989             OldList * structInitializers = MkList();
10990             OldList * specs = MkList();
10991             Expression expExt;
10992             Declarator decl = SpecDeclFromString(typeString, specs, null);
10993             sprintf(templateString, "Container<%s>", typeString);
10994
10995             if(exp.list)
10996             {
10997                Expression e;
10998                type = ProcessTypeString(typeString, false);
10999                while((e = exp.list->first))
11000                {
11001                   exp.list->Remove(e);
11002                   e.destType = type;
11003                   type.refCount++;
11004                   ProcessExpressionType(e);
11005                   ListAdd(initializers, MkInitializerAssignment(e));
11006                }
11007                FreeType(type);
11008                delete exp.list;
11009             }
11010
11011             DeclareStruct("ecere::com::BuiltInContainer", false);
11012
11013             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11014                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11015             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11016                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11017             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11018                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11019             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11020                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11021                MkInitializerList(initializers))));
11022                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11023             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11024                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11025             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11026                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11027             exp.expType = ProcessTypeString(templateString, false);
11028             exp.type = bracketsExp;
11029             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11030                MkExpOp(null, '&',
11031                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11032                   MkInitializerList(structInitializers)))));
11033             ProcessExpressionType(expExt);
11034          }
11035          else
11036          {
11037             exp.expType = ProcessTypeString("Container", false);
11038             Compiler_Error($"Couldn't determine type of array elements\n");
11039          }
11040          break;
11041       }
11042    }
11043
11044    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11045    {
11046       FreeType(exp.expType);
11047       exp.expType = ReplaceThisClassType(thisClass);
11048    }
11049
11050    // Resolve structures here
11051    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11052    {
11053       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11054       // TODO: Fix members reference...
11055       if(symbol)
11056       {
11057          if(exp.expType.kind != enumType)
11058          {
11059             Type member;
11060             String enumName = CopyString(exp.expType.enumName);
11061
11062             // Fixed a memory leak on self-referencing C structs typedefs
11063             // by instantiating a new type rather than simply copying members
11064             // into exp.expType
11065             FreeType(exp.expType);
11066             exp.expType = Type { };
11067             exp.expType.kind = symbol.type.kind;
11068             exp.expType.refCount++;
11069             exp.expType.enumName = enumName;
11070
11071             exp.expType.members = symbol.type.members;
11072             for(member = symbol.type.members.first; member; member = member.next)
11073                member.refCount++;
11074          }
11075          else
11076          {
11077             NamedLink64 member;
11078             for(member = symbol.type.members.first; member; member = member.next)
11079             {
11080                NamedLink64 value { name = CopyString(member.name) };
11081                exp.expType.members.Add(value);
11082             }
11083          }
11084       }
11085    }
11086
11087    yylloc = exp.loc;
11088    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11089    else if(exp.destType && !exp.destType.keepCast)
11090    {
11091       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11092          exp.needTemplateCast = 1;
11093
11094       if(exp.destType.kind == voidType);
11095       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11096       {
11097          if(!exp.destType.count || unresolved)
11098          {
11099             if(!exp.expType)
11100             {
11101                yylloc = exp.loc;
11102                if(exp.destType.kind != ellipsisType)
11103                {
11104                   char type2[1024];
11105                   type2[0] = '\0';
11106                   if(inCompiler)
11107                   {
11108                      char expString[10240];
11109                      expString[0] = '\0';
11110
11111                      PrintType(exp.destType, type2, false, true);
11112
11113                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11114                      if(unresolved)
11115                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11116                      else if(exp.type != dummyExp)
11117                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11118                   }
11119                }
11120                else
11121                {
11122                   char expString[10240] ;
11123                   expString[0] = '\0';
11124                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11125
11126                   if(unresolved)
11127                      Compiler_Error($"unresolved identifier %s\n", expString);
11128                   else if(exp.type != dummyExp)
11129                      Compiler_Error($"couldn't determine type of %s\n", expString);
11130                }
11131             }
11132             else
11133             {
11134                char type1[1024];
11135                char type2[1024];
11136                type1[0] = '\0';
11137                type2[0] = '\0';
11138                if(inCompiler)
11139                {
11140                   PrintType(exp.expType, type1, false, true);
11141                   PrintType(exp.destType, type2, false, true);
11142                }
11143
11144                //CheckExpressionType(exp, exp.destType, false);
11145
11146                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11147                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11148                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11149                else
11150                {
11151                   char expString[10240];
11152                   expString[0] = '\0';
11153                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11154
11155 #ifdef _DEBUG
11156                   CheckExpressionType(exp, exp.destType, false, true);
11157 #endif
11158                   // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11159                   if(!sourceFile || (strcmp(sourceFile, "src\\lexer.ec") && strcmp(sourceFile, "src/lexer.ec") && strcmp(sourceFile, "src\\grammar.ec") && strcmp(sourceFile, "src/grammar.ec")))
11160                      Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11161
11162                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11163                   FreeType(exp.expType);
11164                   exp.destType.refCount++;
11165                   exp.expType = exp.destType;
11166                }
11167             }
11168          }
11169       }
11170       /*else if(exp.destType && exp.destType.kind == ellipsisType && exp.expType && exp.expType.passAsTemplate)
11171       {
11172          Expression newExp { };
11173          char typeString[1024];
11174          OldList * specs = MkList();
11175          Declarator decl;
11176
11177          typeString[0] = '\0';
11178
11179          *newExp = *exp;
11180
11181          if(exp.expType)  exp.expType.refCount++;
11182          if(exp.expType)  exp.expType.refCount++;
11183          exp.type = castExp;
11184          newExp.destType = exp.expType;
11185
11186          PrintType(exp.expType, typeString, false, false);
11187          decl = SpecDeclFromString(typeString, specs, null);
11188
11189          exp.cast.typeName = MkTypeName(specs, decl);
11190          exp.cast.exp = newExp;
11191       }*/
11192    }
11193    else if(unresolved)
11194    {
11195       if(exp.identifier._class && exp.identifier._class.name)
11196          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11197       else if(exp.identifier.string && exp.identifier.string[0])
11198          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11199    }
11200    else if(!exp.expType && exp.type != dummyExp)
11201    {
11202       char expString[10240];
11203       expString[0] = '\0';
11204       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11205       Compiler_Error($"couldn't determine type of %s\n", expString);
11206    }
11207
11208    // Let's try to support any_object & typed_object here:
11209    if(inCompiler)
11210       ApplyAnyObjectLogic(exp);
11211
11212    // Mark nohead classes as by reference, unless we're casting them to an integral type
11213    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11214       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11215          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11216           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11217    {
11218       exp.byReference = true;
11219    }
11220    yylloc = oldyylloc;
11221 }
11222
11223 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11224 {
11225    // THIS CODE WILL FIND NEXT MEMBER...
11226    if(*curMember)
11227    {
11228       *curMember = (*curMember).next;
11229
11230       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11231       {
11232          *curMember = subMemberStack[--(*subMemberStackPos)];
11233          *curMember = (*curMember).next;
11234       }
11235
11236       // SKIP ALL PROPERTIES HERE...
11237       while((*curMember) && (*curMember).isProperty)
11238          *curMember = (*curMember).next;
11239
11240       if(subMemberStackPos)
11241       {
11242          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11243          {
11244             subMemberStack[(*subMemberStackPos)++] = *curMember;
11245
11246             *curMember = (*curMember).members.first;
11247             while(*curMember && (*curMember).isProperty)
11248                *curMember = (*curMember).next;
11249          }
11250       }
11251    }
11252    while(!*curMember)
11253    {
11254       if(!*curMember)
11255       {
11256          if(subMemberStackPos && *subMemberStackPos)
11257          {
11258             *curMember = subMemberStack[--(*subMemberStackPos)];
11259             *curMember = (*curMember).next;
11260          }
11261          else
11262          {
11263             Class lastCurClass = *curClass;
11264
11265             if(*curClass == _class) break;     // REACHED THE END
11266
11267             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11268             *curMember = (*curClass).membersAndProperties.first;
11269          }
11270
11271          while((*curMember) && (*curMember).isProperty)
11272             *curMember = (*curMember).next;
11273          if(subMemberStackPos)
11274          {
11275             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11276             {
11277                subMemberStack[(*subMemberStackPos)++] = *curMember;
11278
11279                *curMember = (*curMember).members.first;
11280                while(*curMember && (*curMember).isProperty)
11281                   *curMember = (*curMember).next;
11282             }
11283          }
11284       }
11285    }
11286 }
11287
11288
11289 static void ProcessInitializer(Initializer init, Type type)
11290 {
11291    switch(init.type)
11292    {
11293       case expInitializer:
11294          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11295          {
11296             // TESTING THIS FOR SHUTTING = 0 WARNING
11297             if(init.exp && !init.exp.destType)
11298             {
11299                FreeType(init.exp.destType);
11300                init.exp.destType = type;
11301                if(type) type.refCount++;
11302             }
11303             if(init.exp)
11304             {
11305                ProcessExpressionType(init.exp);
11306                init.isConstant = init.exp.isConstant;
11307             }
11308             break;
11309          }
11310          else
11311          {
11312             Expression exp = init.exp;
11313             Instantiation inst = exp.instance;
11314             MembersInit members;
11315
11316             init.type = listInitializer;
11317             init.list = MkList();
11318
11319             if(inst.members)
11320             {
11321                for(members = inst.members->first; members; members = members.next)
11322                {
11323                   if(members.type == dataMembersInit)
11324                   {
11325                      MemberInit member;
11326                      for(member = members.dataMembers->first; member; member = member.next)
11327                      {
11328                         ListAdd(init.list, member.initializer);
11329                         member.initializer = null;
11330                      }
11331                   }
11332                   // Discard all MembersInitMethod
11333                }
11334             }
11335             FreeExpression(exp);
11336          }
11337       case listInitializer:
11338       {
11339          Initializer i;
11340          Type initializerType = null;
11341          Class curClass = null;
11342          DataMember curMember = null;
11343          DataMember subMemberStack[256];
11344          int subMemberStackPos = 0;
11345
11346          if(type && type.kind == arrayType)
11347             initializerType = Dereference(type);
11348          else if(type && (type.kind == structType || type.kind == unionType))
11349             initializerType = type.members.first;
11350
11351          for(i = init.list->first; i; i = i.next)
11352          {
11353             if(type && type.kind == classType && type._class && type._class.registered)
11354             {
11355                // 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)
11356                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11357                // TODO: Generate error on initializing a private data member this way from another module...
11358                if(curMember)
11359                {
11360                   if(!curMember.dataType)
11361                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11362                   initializerType = curMember.dataType;
11363                }
11364             }
11365             ProcessInitializer(i, initializerType);
11366             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11367                initializerType = initializerType.next;
11368             if(!i.isConstant)
11369                init.isConstant = false;
11370          }
11371
11372          if(type && type.kind == arrayType)
11373             FreeType(initializerType);
11374
11375          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11376          {
11377             Compiler_Error($"Assigning list initializer to non list\n");
11378          }
11379          break;
11380       }
11381    }
11382 }
11383
11384 static void ProcessSpecifier(Specifier spec, bool declareStruct)
11385 {
11386    switch(spec.type)
11387    {
11388       case baseSpecifier:
11389       {
11390          if(spec.specifier == THISCLASS)
11391          {
11392             if(thisClass)
11393             {
11394                spec.type = nameSpecifier;
11395                spec.name = ReplaceThisClass(thisClass);
11396                spec.symbol = FindClass(spec.name);
11397                ProcessSpecifier(spec, declareStruct);
11398             }
11399          }
11400          break;
11401       }
11402       case nameSpecifier:
11403       {
11404          Symbol symbol = FindType(curContext, spec.name);
11405          if(symbol)
11406             DeclareType(symbol.type, true, true);
11407          else if((symbol = spec.symbol /*FindClass(spec.name)*/) && symbol.registered && symbol.registered.type == structClass && declareStruct)
11408             DeclareStruct(spec.name, false);
11409          break;
11410       }
11411       case enumSpecifier:
11412       {
11413          Enumerator e;
11414          if(spec.list)
11415          {
11416             for(e = spec.list->first; e; e = e.next)
11417             {
11418                if(e.exp)
11419                   ProcessExpressionType(e.exp);
11420             }
11421          }
11422          break;
11423       }
11424       case structSpecifier:
11425       case unionSpecifier:
11426       {
11427          if(spec.definitions)
11428          {
11429             //ClassDef def;
11430             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11431             //if(symbol)
11432                ProcessClass(spec.definitions, symbol);
11433             /*else
11434             {
11435                for(def = spec.definitions->first; def; def = def.next)
11436                {
11437                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11438                      ProcessDeclaration(def.decl);
11439                }
11440             }*/
11441          }
11442          break;
11443       }
11444       /*
11445       case classSpecifier:
11446       {
11447          Symbol classSym = FindClass(spec.name);
11448          if(classSym && classSym.registered && classSym.registered.type == structClass)
11449             DeclareStruct(spec.name, false);
11450          break;
11451       }
11452       */
11453    }
11454 }
11455
11456
11457 static void ProcessDeclarator(Declarator decl)
11458 {
11459    switch(decl.type)
11460    {
11461       case identifierDeclarator:
11462          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11463          {
11464             FreeSpecifier(decl.identifier._class);
11465             decl.identifier._class = null;
11466          }
11467          break;
11468       case arrayDeclarator:
11469          if(decl.array.exp)
11470             ProcessExpressionType(decl.array.exp);
11471       case structDeclarator:
11472       case bracketsDeclarator:
11473       case functionDeclarator:
11474       case pointerDeclarator:
11475       case extendedDeclarator:
11476       case extendedDeclaratorEnd:
11477          if(decl.declarator)
11478             ProcessDeclarator(decl.declarator);
11479          if(decl.type == functionDeclarator)
11480          {
11481             Identifier id = GetDeclId(decl);
11482             if(id && id._class)
11483             {
11484                TypeName param
11485                {
11486                   qualifiers = MkListOne(id._class);
11487                   declarator = null;
11488                };
11489                if(!decl.function.parameters)
11490                   decl.function.parameters = MkList();
11491                decl.function.parameters->Insert(null, param);
11492                id._class = null;
11493             }
11494             if(decl.function.parameters)
11495             {
11496                TypeName param;
11497
11498                for(param = decl.function.parameters->first; param; param = param.next)
11499                {
11500                   if(param.qualifiers && param.qualifiers->first)
11501                   {
11502                      Specifier spec = param.qualifiers->first;
11503                      if(spec && spec.specifier == TYPED_OBJECT)
11504                      {
11505                         Declarator d = param.declarator;
11506                         TypeName newParam
11507                         {
11508                            qualifiers = MkListOne(MkSpecifier(VOID));
11509                            declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11510                         };
11511                         if(d.type != pointerDeclarator)
11512                            newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11513
11514                         FreeList(param.qualifiers, FreeSpecifier);
11515
11516                         param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11517                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11518
11519                         decl.function.parameters->Insert(param, newParam);
11520                         param = newParam;
11521                      }
11522                      else if(spec && spec.specifier == ANY_OBJECT)
11523                      {
11524                         Declarator d = param.declarator;
11525
11526                         FreeList(param.qualifiers, FreeSpecifier);
11527
11528                         param.qualifiers = MkListOne(MkSpecifier(VOID));
11529                         if(d.type != pointerDeclarator)
11530                            param.qualifiers->Insert(null, MkSpecifier(CONST));
11531                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11532                      }
11533                      else if(spec.specifier == THISCLASS)
11534                      {
11535                         if(thisClass)
11536                         {
11537                            spec.type = nameSpecifier;
11538                            spec.name = ReplaceThisClass(thisClass);
11539                            spec.symbol = FindClass(spec.name);
11540                            ProcessSpecifier(spec, false);
11541                         }
11542                      }
11543                   }
11544
11545                   if(param.declarator)
11546                      ProcessDeclarator(param.declarator);
11547                }
11548             }
11549          }
11550          break;
11551    }
11552 }
11553
11554 static void ProcessDeclaration(Declaration decl)
11555 {
11556    yylloc = decl.loc;
11557    switch(decl.type)
11558    {
11559       case initDeclaration:
11560       {
11561          bool declareStruct = false;
11562          /*
11563          lineNum = decl.pos.line;
11564          column = decl.pos.col;
11565          */
11566
11567          if(decl.declarators)
11568          {
11569             InitDeclarator d;
11570
11571             for(d = decl.declarators->first; d; d = d.next)
11572             {
11573                Type type, subType;
11574                ProcessDeclarator(d.declarator);
11575
11576                type = ProcessType(decl.specifiers, d.declarator);
11577
11578                if(d.initializer)
11579                {
11580                   ProcessInitializer(d.initializer, type);
11581
11582                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11583
11584                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11585                      d.initializer.exp.type == instanceExp)
11586                   {
11587                      if(type.kind == classType && type._class ==
11588                         d.initializer.exp.expType._class)
11589                      {
11590                         Instantiation inst = d.initializer.exp.instance;
11591                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11592
11593                         d.initializer.exp.instance = null;
11594                         if(decl.specifiers)
11595                            FreeList(decl.specifiers, FreeSpecifier);
11596                         FreeList(decl.declarators, FreeInitDeclarator);
11597
11598                         d = null;
11599
11600                         decl.type = instDeclaration;
11601                         decl.inst = inst;
11602                      }
11603                   }
11604                }
11605                for(subType = type; subType;)
11606                {
11607                   if(subType.kind == classType)
11608                   {
11609                      declareStruct = true;
11610                      break;
11611                   }
11612                   else if(subType.kind == pointerType)
11613                      break;
11614                   else if(subType.kind == arrayType)
11615                      subType = subType.arrayType;
11616                   else
11617                      break;
11618                }
11619
11620                FreeType(type);
11621                if(!d) break;
11622             }
11623          }
11624
11625          if(decl.specifiers)
11626          {
11627             Specifier s;
11628             for(s = decl.specifiers->first; s; s = s.next)
11629             {
11630                ProcessSpecifier(s, declareStruct);
11631             }
11632          }
11633          break;
11634       }
11635       case instDeclaration:
11636       {
11637          ProcessInstantiationType(decl.inst);
11638          break;
11639       }
11640       case structDeclaration:
11641       {
11642          Specifier spec;
11643          Declarator d;
11644          bool declareStruct = false;
11645
11646          if(decl.declarators)
11647          {
11648             for(d = decl.declarators->first; d; d = d.next)
11649             {
11650                Type type = ProcessType(decl.specifiers, d.declarator);
11651                Type subType;
11652                ProcessDeclarator(d);
11653                for(subType = type; subType;)
11654                {
11655                   if(subType.kind == classType)
11656                   {
11657                      declareStruct = true;
11658                      break;
11659                   }
11660                   else if(subType.kind == pointerType)
11661                      break;
11662                   else if(subType.kind == arrayType)
11663                      subType = subType.arrayType;
11664                   else
11665                      break;
11666                }
11667                FreeType(type);
11668             }
11669          }
11670          if(decl.specifiers)
11671          {
11672             for(spec = decl.specifiers->first; spec; spec = spec.next)
11673                ProcessSpecifier(spec, declareStruct);
11674          }
11675          break;
11676       }
11677    }
11678 }
11679
11680 static FunctionDefinition curFunction;
11681
11682 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11683 {
11684    char propName[1024], propNameM[1024];
11685    char getName[1024], setName[1024];
11686    OldList * args;
11687
11688    DeclareProperty(prop, setName, getName);
11689
11690    // eInstance_FireWatchers(object, prop);
11691    strcpy(propName, "__ecereProp_");
11692    FullClassNameCat(propName, prop._class.fullName, false);
11693    strcat(propName, "_");
11694    // strcat(propName, prop.name);
11695    FullClassNameCat(propName, prop.name, true);
11696    //MangleClassName(propName);
11697
11698    strcpy(propNameM, "__ecerePropM_");
11699    FullClassNameCat(propNameM, prop._class.fullName, false);
11700    strcat(propNameM, "_");
11701    // strcat(propNameM, prop.name);
11702    FullClassNameCat(propNameM, prop.name, true);
11703    //MangleClassName(propNameM);
11704
11705    if(prop.isWatchable)
11706    {
11707       args = MkList();
11708       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11709       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11710       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11711
11712       args = MkList();
11713       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11714       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11715       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11716    }
11717
11718
11719    {
11720       args = MkList();
11721       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11722       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11723       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11724
11725       args = MkList();
11726       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11727       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11728       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11729    }
11730
11731    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11732       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11733       curFunction.propSet.fireWatchersDone = true;
11734 }
11735
11736 static void ProcessStatement(Statement stmt)
11737 {
11738    yylloc = stmt.loc;
11739    /*
11740    lineNum = stmt.pos.line;
11741    column = stmt.pos.col;
11742    */
11743    switch(stmt.type)
11744    {
11745       case labeledStmt:
11746          ProcessStatement(stmt.labeled.stmt);
11747          break;
11748       case caseStmt:
11749          // This expression should be constant...
11750          if(stmt.caseStmt.exp)
11751          {
11752             FreeType(stmt.caseStmt.exp.destType);
11753             stmt.caseStmt.exp.destType = curSwitchType;
11754             if(curSwitchType) curSwitchType.refCount++;
11755             ProcessExpressionType(stmt.caseStmt.exp);
11756             ComputeExpression(stmt.caseStmt.exp);
11757          }
11758          if(stmt.caseStmt.stmt)
11759             ProcessStatement(stmt.caseStmt.stmt);
11760          break;
11761       case compoundStmt:
11762       {
11763          if(stmt.compound.context)
11764          {
11765             Declaration decl;
11766             Statement s;
11767
11768             Statement prevCompound = curCompound;
11769             Context prevContext = curContext;
11770
11771             if(!stmt.compound.isSwitch)
11772                curCompound = stmt;
11773             curContext = stmt.compound.context;
11774
11775             if(stmt.compound.declarations)
11776             {
11777                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
11778                   ProcessDeclaration(decl);
11779             }
11780             if(stmt.compound.statements)
11781             {
11782                for(s = stmt.compound.statements->first; s; s = s.next)
11783                   ProcessStatement(s);
11784             }
11785
11786             curContext = prevContext;
11787             curCompound = prevCompound;
11788          }
11789          break;
11790       }
11791       case expressionStmt:
11792       {
11793          Expression exp;
11794          if(stmt.expressions)
11795          {
11796             for(exp = stmt.expressions->first; exp; exp = exp.next)
11797                ProcessExpressionType(exp);
11798          }
11799          break;
11800       }
11801       case ifStmt:
11802       {
11803          Expression exp;
11804
11805          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
11806          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
11807          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
11808          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
11809          {
11810             ProcessExpressionType(exp);
11811          }
11812          if(stmt.ifStmt.stmt)
11813             ProcessStatement(stmt.ifStmt.stmt);
11814          if(stmt.ifStmt.elseStmt)
11815             ProcessStatement(stmt.ifStmt.elseStmt);
11816          break;
11817       }
11818       case switchStmt:
11819       {
11820          Type oldSwitchType = curSwitchType;
11821          if(stmt.switchStmt.exp)
11822          {
11823             Expression exp;
11824             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
11825             {
11826                if(!exp.next)
11827                {
11828                   /*
11829                   Type destType
11830                   {
11831                      kind = intType;
11832                      refCount = 1;
11833                   };
11834                   e.exp.destType = destType;
11835                   */
11836
11837                   ProcessExpressionType(exp);
11838                }
11839                if(!exp.next)
11840                   curSwitchType = exp.expType;
11841             }
11842          }
11843          ProcessStatement(stmt.switchStmt.stmt);
11844          curSwitchType = oldSwitchType;
11845          break;
11846       }
11847       case whileStmt:
11848       {
11849          if(stmt.whileStmt.exp)
11850          {
11851             Expression exp;
11852
11853             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
11854             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
11855             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
11856             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
11857             {
11858                ProcessExpressionType(exp);
11859             }
11860          }
11861          if(stmt.whileStmt.stmt)
11862             ProcessStatement(stmt.whileStmt.stmt);
11863          break;
11864       }
11865       case doWhileStmt:
11866       {
11867          if(stmt.doWhile.exp)
11868          {
11869             Expression exp;
11870
11871             if(stmt.doWhile.exp->last)
11872             {
11873                FreeType(((Expression)stmt.doWhile.exp->last).destType);
11874                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
11875                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
11876             }
11877             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
11878             {
11879                ProcessExpressionType(exp);
11880             }
11881          }
11882          if(stmt.doWhile.stmt)
11883             ProcessStatement(stmt.doWhile.stmt);
11884          break;
11885       }
11886       case forStmt:
11887       {
11888          Expression exp;
11889          if(stmt.forStmt.init)
11890             ProcessStatement(stmt.forStmt.init);
11891
11892          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
11893          {
11894             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
11895             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
11896             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
11897          }
11898
11899          if(stmt.forStmt.check)
11900             ProcessStatement(stmt.forStmt.check);
11901          if(stmt.forStmt.increment)
11902          {
11903             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
11904                ProcessExpressionType(exp);
11905          }
11906
11907          if(stmt.forStmt.stmt)
11908             ProcessStatement(stmt.forStmt.stmt);
11909          break;
11910       }
11911       case forEachStmt:
11912       {
11913          Identifier id = stmt.forEachStmt.id;
11914          OldList * exp = stmt.forEachStmt.exp;
11915          OldList * filter = stmt.forEachStmt.filter;
11916          Statement block = stmt.forEachStmt.stmt;
11917          char iteratorType[1024];
11918          Type source;
11919          Expression e;
11920          bool isBuiltin = exp && exp->last &&
11921             (((Expression)exp->last).type == ExpressionType::arrayExp ||
11922               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
11923          Expression arrayExp;
11924          const char * typeString = null;
11925          int builtinCount = 0;
11926
11927          for(e = exp ? exp->first : null; e; e = e.next)
11928          {
11929             if(!e.next)
11930             {
11931                FreeType(e.destType);
11932                e.destType = ProcessTypeString("Container", false);
11933             }
11934             if(!isBuiltin || e.next)
11935                ProcessExpressionType(e);
11936          }
11937
11938          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
11939          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
11940             eClass_IsDerived(source._class.registered, containerClass)))
11941          {
11942             Class _class = source ? source._class.registered : null;
11943             Symbol symbol;
11944             Expression expIt = null;
11945             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
11946             Class arrayClass = eSystem_FindClass(privateModule, "Array");
11947             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
11948             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
11949             stmt.type = compoundStmt;
11950
11951             stmt.compound.context = Context { };
11952             stmt.compound.context.parent = curContext;
11953             curContext = stmt.compound.context;
11954
11955             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
11956             {
11957                Class mapClass = eSystem_FindClass(privateModule, "Map");
11958                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
11959                isCustomAVLTree = true;
11960                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
11961                   isAVLTree = true;
11962                else */if(eClass_IsDerived(source._class.registered, mapClass))
11963                   isMap = true;
11964             }
11965             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
11966             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
11967             {
11968                Class listClass = eSystem_FindClass(privateModule, "List");
11969                isLinkList = true;
11970                isList = eClass_IsDerived(source._class.registered, listClass);
11971             }
11972
11973             if(isArray)
11974             {
11975                Declarator decl;
11976                OldList * specs = MkList();
11977                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
11978                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
11979                stmt.compound.declarations = MkListOne(
11980                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11981                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11982                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
11983                      MkInitializerAssignment(MkExpBrackets(exp))))));
11984             }
11985             else if(isBuiltin)
11986             {
11987                Type type = null;
11988                char typeStringBuf[1024];
11989
11990                // TODO: Merge this code?
11991                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
11992                if(((Expression)exp->last).type == castExp)
11993                {
11994                   TypeName typeName = ((Expression)exp->last).cast.typeName;
11995                   if(typeName)
11996                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
11997                }
11998
11999                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12000                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12001                   arrayExp.destType._class.registered.templateArgs)
12002                {
12003                   Class templateClass = arrayExp.destType._class.registered;
12004                   typeString = templateClass.templateArgs[2].dataTypeString;
12005                }
12006                else if(arrayExp.list)
12007                {
12008                   // Guess type from expressions in the array
12009                   Expression e;
12010                   for(e = arrayExp.list->first; e; e = e.next)
12011                   {
12012                      ProcessExpressionType(e);
12013                      if(e.expType)
12014                      {
12015                         if(!type) { type = e.expType; type.refCount++; }
12016                         else
12017                         {
12018                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12019                            if(!MatchTypeExpression(e, type, null, false, true))
12020                            {
12021                               FreeType(type);
12022                               type = e.expType;
12023                               e.expType = null;
12024
12025                               e = arrayExp.list->first;
12026                               ProcessExpressionType(e);
12027                               if(e.expType)
12028                               {
12029                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12030                                  if(!MatchTypeExpression(e, type, null, false, true))
12031                                  {
12032                                     FreeType(e.expType);
12033                                     e.expType = null;
12034                                     FreeType(type);
12035                                     type = null;
12036                                     break;
12037                                  }
12038                               }
12039                            }
12040                         }
12041                         if(e.expType)
12042                         {
12043                            FreeType(e.expType);
12044                            e.expType = null;
12045                         }
12046                      }
12047                   }
12048                   if(type)
12049                   {
12050                      typeStringBuf[0] = '\0';
12051                      PrintType(type, typeStringBuf, false, true);
12052                      typeString = typeStringBuf;
12053                      FreeType(type);
12054                   }
12055                }
12056                if(typeString)
12057                {
12058                   OldList * initializers = MkList();
12059                   Declarator decl;
12060                   OldList * specs = MkList();
12061                   if(arrayExp.list)
12062                   {
12063                      Expression e;
12064
12065                      builtinCount = arrayExp.list->count;
12066                      type = ProcessTypeString(typeString, false);
12067                      while((e = arrayExp.list->first))
12068                      {
12069                         arrayExp.list->Remove(e);
12070                         e.destType = type;
12071                         type.refCount++;
12072                         ProcessExpressionType(e);
12073                         ListAdd(initializers, MkInitializerAssignment(e));
12074                      }
12075                      FreeType(type);
12076                      delete arrayExp.list;
12077                   }
12078                   decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12079                   stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12080                      MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12081
12082                   ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12083                      PlugDeclarator(
12084                         /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12085                         ), MkInitializerList(initializers)))));
12086                   FreeList(exp, FreeExpression);
12087                }
12088                else
12089                {
12090                   arrayExp.expType = ProcessTypeString("Container", false);
12091                   Compiler_Error($"Couldn't determine type of array elements\n");
12092                }
12093
12094                /*
12095                Declarator decl;
12096                OldList * specs = MkList();
12097
12098                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12099                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12100                stmt.compound.declarations = MkListOne(
12101                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12102                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12103                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12104                      MkInitializerAssignment(MkExpBrackets(exp))))));
12105                */
12106             }
12107             else if(isLinkList && !isList)
12108             {
12109                Declarator decl;
12110                OldList * specs = MkList();
12111                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12112                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12113                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12114                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12115                      MkInitializerAssignment(MkExpBrackets(exp))))));
12116             }
12117             /*else if(isCustomAVLTree)
12118             {
12119                Declarator decl;
12120                OldList * specs = MkList();
12121                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12122                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12123                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12124                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12125                      MkInitializerAssignment(MkExpBrackets(exp))))));
12126             }*/
12127             else if(_class.templateArgs)
12128             {
12129                if(isMap)
12130                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12131                else
12132                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12133
12134                stmt.compound.declarations = MkListOne(
12135                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12136                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12137                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12138             }
12139             symbol = FindSymbol(id.string, curContext, curContext, false, false);
12140
12141             if(block)
12142             {
12143                // Reparent sub-contexts in this statement
12144                switch(block.type)
12145                {
12146                   case compoundStmt:
12147                      if(block.compound.context)
12148                         block.compound.context.parent = stmt.compound.context;
12149                      break;
12150                   case ifStmt:
12151                      if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12152                         block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12153                      if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12154                         block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12155                      break;
12156                   case switchStmt:
12157                      if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12158                         block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12159                      break;
12160                   case whileStmt:
12161                      if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12162                         block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12163                      break;
12164                   case doWhileStmt:
12165                      if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12166                         block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12167                      break;
12168                   case forStmt:
12169                      if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12170                         block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12171                      break;
12172                   case forEachStmt:
12173                      if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12174                         block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12175                      break;
12176                   /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12177                   case labeledStmt:
12178                   case caseStmt
12179                   case expressionStmt:
12180                   case gotoStmt:
12181                   case continueStmt:
12182                   case breakStmt
12183                   case returnStmt:
12184                   case asmStmt:
12185                   case badDeclarationStmt:
12186                   case fireWatchersStmt:
12187                   case stopWatchingStmt:
12188                   case watchStmt:
12189                   */
12190                }
12191             }
12192             if(filter)
12193             {
12194                block = MkIfStmt(filter, block, null);
12195             }
12196             if(isArray)
12197             {
12198                stmt.compound.statements = MkListOne(MkForStmt(
12199                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12200                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12201                      MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12202                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12203                   block));
12204               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12205               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12206               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12207             }
12208             else if(isBuiltin)
12209             {
12210                char count[128];
12211                //OldList * specs = MkList();
12212                // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12213
12214                sprintf(count, "%d", builtinCount);
12215
12216                stmt.compound.statements = MkListOne(MkForStmt(
12217                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12218                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12219                      MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12220                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12221                   block));
12222
12223                /*
12224                Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12225                stmt.compound.statements = MkListOne(MkForStmt(
12226                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12227                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12228                      MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12229                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12230                   block));
12231               */
12232               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12233               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12234               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12235             }
12236             else if(isLinkList && !isList)
12237             {
12238                Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12239                Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12240                if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12241                   !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12242                {
12243                   stmt.compound.statements = MkListOne(MkForStmt(
12244                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12245                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12246                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12247                      block));
12248                }
12249                else
12250                {
12251                   OldList * specs = MkList();
12252                   Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12253                   stmt.compound.statements = MkListOne(MkForStmt(
12254                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12255                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12256                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12257                         MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12258                            MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12259                      block));
12260                }
12261                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12262                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12263                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12264             }
12265             /*else if(isCustomAVLTree)
12266             {
12267                stmt.compound.statements = MkListOne(MkForStmt(
12268                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12269                      MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12270                   MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12271                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12272                   block));
12273
12274                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12275                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12276                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12277             }*/
12278             else
12279             {
12280                stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12281                   MkIdentifier("Next")), null)), block));
12282             }
12283             ProcessExpressionType(expIt);
12284             if(stmt.compound.declarations->first)
12285                ProcessDeclaration(stmt.compound.declarations->first);
12286
12287             if(symbol)
12288                symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12289
12290             ProcessStatement(stmt);
12291             curContext = stmt.compound.context.parent;
12292             break;
12293          }
12294          else
12295          {
12296             Compiler_Error($"Expression is not a container\n");
12297          }
12298          break;
12299       }
12300       case gotoStmt:
12301          break;
12302       case continueStmt:
12303          break;
12304       case breakStmt:
12305          break;
12306       case returnStmt:
12307       {
12308          Expression exp;
12309          if(stmt.expressions)
12310          {
12311             for(exp = stmt.expressions->first; exp; exp = exp.next)
12312             {
12313                if(!exp.next)
12314                {
12315                   if(curFunction && !curFunction.type)
12316                      curFunction.type = ProcessType(
12317                         curFunction.specifiers, curFunction.declarator);
12318                   FreeType(exp.destType);
12319                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12320                   if(exp.destType) exp.destType.refCount++;
12321                }
12322                ProcessExpressionType(exp);
12323             }
12324          }
12325          break;
12326       }
12327       case badDeclarationStmt:
12328       {
12329          ProcessDeclaration(stmt.decl);
12330          break;
12331       }
12332       case asmStmt:
12333       {
12334          AsmField field;
12335          if(stmt.asmStmt.inputFields)
12336          {
12337             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12338                if(field.expression)
12339                   ProcessExpressionType(field.expression);
12340          }
12341          if(stmt.asmStmt.outputFields)
12342          {
12343             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12344                if(field.expression)
12345                   ProcessExpressionType(field.expression);
12346          }
12347          if(stmt.asmStmt.clobberedFields)
12348          {
12349             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12350             {
12351                if(field.expression)
12352                   ProcessExpressionType(field.expression);
12353             }
12354          }
12355          break;
12356       }
12357       case watchStmt:
12358       {
12359          PropertyWatch propWatch;
12360          OldList * watches = stmt._watch.watches;
12361          Expression object = stmt._watch.object;
12362          Expression watcher = stmt._watch.watcher;
12363          if(watcher)
12364             ProcessExpressionType(watcher);
12365          if(object)
12366             ProcessExpressionType(object);
12367
12368          if(inCompiler)
12369          {
12370             if(watcher || thisClass)
12371             {
12372                External external = curExternal;
12373                Context context = curContext;
12374
12375                stmt.type = expressionStmt;
12376                stmt.expressions = MkList();
12377
12378                curExternal = external.prev;
12379
12380                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12381                {
12382                   ClassFunction func;
12383                   char watcherName[1024];
12384                   Class watcherClass = watcher ?
12385                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12386                   External createdExternal;
12387
12388                   // Create a declaration above
12389                   External externalDecl = MkExternalDeclaration(null);
12390                   ast->Insert(curExternal.prev, externalDecl);
12391
12392                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12393                   if(propWatch.deleteWatch)
12394                      strcat(watcherName, "_delete");
12395                   else
12396                   {
12397                      Identifier propID;
12398                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12399                      {
12400                         strcat(watcherName, "_");
12401                         strcat(watcherName, propID.string);
12402                      }
12403                   }
12404
12405                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12406                   {
12407                      // TESTING THIS STUFF... BEWARE OF SYMBOL ID ISSUES
12408                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12409                         //MkListOne(MkTypeName(MkListOne(MkSpecifier(VOID)), null))), null);
12410                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12411                      ProcessClassFunctionBody(func, propWatch.compound);
12412                      propWatch.compound = null;
12413
12414                      //afterExternal = afterExternal ? afterExternal : curExternal;
12415
12416                      //createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal.prev);
12417                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12418                      // TESTING THIS...
12419                      createdExternal.symbol.idCode = external.symbol.idCode;
12420
12421                      curExternal = createdExternal;
12422                      ProcessFunction(createdExternal.function);
12423
12424
12425                      // Create a declaration above
12426                      {
12427                         Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
12428                            MkListOne(MkInitDeclarator(CopyDeclarator(createdExternal.function.declarator), null)));
12429                         externalDecl.declaration = decl;
12430                         if(decl.symbol && !decl.symbol.pointerExternal)
12431                            decl.symbol.pointerExternal = externalDecl;
12432                      }
12433
12434                      if(propWatch.deleteWatch)
12435                      {
12436                         OldList * args = MkList();
12437                         ListAdd(args, CopyExpression(object));
12438                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12439                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12440                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12441                      }
12442                      else
12443                      {
12444                         Class _class = object.expType._class.registered;
12445                         Identifier propID;
12446
12447                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12448                         {
12449                            char propName[1024];
12450                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12451                            if(prop)
12452                            {
12453                               char getName[1024], setName[1024];
12454                               OldList * args = MkList();
12455
12456                               DeclareProperty(prop, setName, getName);
12457
12458                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12459                               strcpy(propName, "__ecereProp_");
12460                               FullClassNameCat(propName, prop._class.fullName, false);
12461                               strcat(propName, "_");
12462                               // strcat(propName, prop.name);
12463                               FullClassNameCat(propName, prop.name, true);
12464
12465                               ListAdd(args, CopyExpression(object));
12466                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12467                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12468                               ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12469
12470                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12471                            }
12472                            else
12473                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12474                         }
12475                      }
12476                   }
12477                   else
12478                      Compiler_Error($"Invalid watched object\n");
12479                }
12480
12481                curExternal = external;
12482                curContext = context;
12483
12484                if(watcher)
12485                   FreeExpression(watcher);
12486                if(object)
12487                   FreeExpression(object);
12488                FreeList(watches, FreePropertyWatch);
12489             }
12490             else
12491                Compiler_Error($"No observer specified and not inside a _class\n");
12492          }
12493          else
12494          {
12495             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12496             {
12497                ProcessStatement(propWatch.compound);
12498             }
12499
12500          }
12501          break;
12502       }
12503       case fireWatchersStmt:
12504       {
12505          OldList * watches = stmt._watch.watches;
12506          Expression object = stmt._watch.object;
12507          Class _class;
12508          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12509          // printf("%X\n", watches);
12510          // printf("%X\n", stmt._watch.watches);
12511          if(object)
12512             ProcessExpressionType(object);
12513
12514          if(inCompiler)
12515          {
12516             _class = object ?
12517                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12518
12519             if(_class)
12520             {
12521                Identifier propID;
12522
12523                stmt.type = expressionStmt;
12524                stmt.expressions = MkList();
12525
12526                // Check if we're inside a property set
12527                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12528                {
12529                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12530                }
12531                else if(!watches)
12532                {
12533                   //Compiler_Error($"No property specified and not inside a property set\n");
12534                }
12535                if(watches)
12536                {
12537                   for(propID = watches->first; propID; propID = propID.next)
12538                   {
12539                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12540                      if(prop)
12541                      {
12542                         CreateFireWatcher(prop, object, stmt);
12543                      }
12544                      else
12545                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12546                   }
12547                }
12548                else
12549                {
12550                   // Fire all properties!
12551                   Property prop;
12552                   Class base;
12553                   for(base = _class; base; base = base.base)
12554                   {
12555                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12556                      {
12557                         if(prop.isProperty && prop.isWatchable)
12558                         {
12559                            CreateFireWatcher(prop, object, stmt);
12560                         }
12561                      }
12562                   }
12563                }
12564
12565                if(object)
12566                   FreeExpression(object);
12567                FreeList(watches, FreeIdentifier);
12568             }
12569             else
12570                Compiler_Error($"Invalid object specified and not inside a class\n");
12571          }
12572          break;
12573       }
12574       case stopWatchingStmt:
12575       {
12576          OldList * watches = stmt._watch.watches;
12577          Expression object = stmt._watch.object;
12578          Expression watcher = stmt._watch.watcher;
12579          Class _class;
12580          if(object)
12581             ProcessExpressionType(object);
12582          if(watcher)
12583             ProcessExpressionType(watcher);
12584          if(inCompiler)
12585          {
12586             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12587
12588             if(watcher || thisClass)
12589             {
12590                if(_class)
12591                {
12592                   Identifier propID;
12593
12594                   stmt.type = expressionStmt;
12595                   stmt.expressions = MkList();
12596
12597                   if(!watches)
12598                   {
12599                      OldList * args;
12600                      // eInstance_StopWatching(object, null, watcher);
12601                      args = MkList();
12602                      ListAdd(args, CopyExpression(object));
12603                      ListAdd(args, MkExpConstant("0"));
12604                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12605                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12606                   }
12607                   else
12608                   {
12609                      for(propID = watches->first; propID; propID = propID.next)
12610                      {
12611                         char propName[1024];
12612                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12613                         if(prop)
12614                         {
12615                            char getName[1024], setName[1024];
12616                            OldList * args = MkList();
12617
12618                            DeclareProperty(prop, setName, getName);
12619
12620                            // eInstance_StopWatching(object, prop, watcher);
12621                            strcpy(propName, "__ecereProp_");
12622                            FullClassNameCat(propName, prop._class.fullName, false);
12623                            strcat(propName, "_");
12624                            // strcat(propName, prop.name);
12625                            FullClassNameCat(propName, prop.name, true);
12626                            //MangleClassName(propName);
12627
12628                            ListAdd(args, CopyExpression(object));
12629                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12630                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12631                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12632                         }
12633                         else
12634                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12635                      }
12636                   }
12637
12638                   if(object)
12639                      FreeExpression(object);
12640                   if(watcher)
12641                      FreeExpression(watcher);
12642                   FreeList(watches, FreeIdentifier);
12643                }
12644                else
12645                   Compiler_Error($"Invalid object specified and not inside a class\n");
12646             }
12647             else
12648                Compiler_Error($"No observer specified and not inside a class\n");
12649          }
12650          break;
12651       }
12652    }
12653 }
12654
12655 static void ProcessFunction(FunctionDefinition function)
12656 {
12657    Identifier id = GetDeclId(function.declarator);
12658    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12659    Type type = symbol ? symbol.type : null;
12660    Class oldThisClass = thisClass;
12661    Context oldTopContext = topContext;
12662
12663    yylloc = function.loc;
12664    // Process thisClass
12665
12666    if(type && type.thisClass)
12667    {
12668       Symbol classSym = type.thisClass;
12669       Class _class = type.thisClass.registered;
12670       char className[1024];
12671       char structName[1024];
12672       Declarator funcDecl;
12673       Symbol thisSymbol;
12674
12675       bool typedObject = false;
12676
12677       if(_class && !_class.base)
12678       {
12679          _class = currentClass;
12680          if(_class && !_class.symbol)
12681             _class.symbol = FindClass(_class.fullName);
12682          classSym = _class ? _class.symbol : null;
12683          typedObject = true;
12684       }
12685
12686       thisClass = _class;
12687
12688       if(inCompiler && _class)
12689       {
12690          if(type.kind == functionType)
12691          {
12692             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12693             {
12694                //TypeName param = symbol.type.params.first;
12695                Type param = symbol.type.params.first;
12696                symbol.type.params.Remove(param);
12697                //FreeTypeName(param);
12698                FreeType(param);
12699             }
12700             if(type.classObjectType != classPointer)
12701             {
12702                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12703                symbol.type.staticMethod = true;
12704                symbol.type.thisClass = null;
12705
12706                // HIGH DANGER: VERIFYING THIS...
12707                symbol.type.extraParam = false;
12708             }
12709          }
12710
12711          strcpy(className, "__ecereClass_");
12712          FullClassNameCat(className, _class.fullName, true);
12713
12714          //MangleClassName(className);
12715
12716          structName[0] = 0;
12717          FullClassNameCat(structName, _class.fullName, false);
12718
12719          // [class] this
12720
12721
12722          funcDecl = GetFuncDecl(function.declarator);
12723          if(funcDecl)
12724          {
12725             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12726             {
12727                TypeName param = funcDecl.function.parameters->first;
12728                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12729                {
12730                   funcDecl.function.parameters->Remove(param);
12731                   FreeTypeName(param);
12732                }
12733             }
12734
12735             // DANGER: Watch for this... Check if it's a Conversion?
12736             // if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12737
12738             // WAS TRYING THIS FOR CONVERSION PROPERTIES ON NOHEAD CLASSES: if((_class.type == structClass) || function != (FunctionDefinition)symbol.externalSet)
12739             if(!function.propertyNoThis)
12740             {
12741                TypeName thisParam = null;
12742
12743                if(type.classObjectType != classPointer)
12744                {
12745                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12746                   if(!funcDecl.function.parameters)
12747                      funcDecl.function.parameters = MkList();
12748                   funcDecl.function.parameters->Insert(null, thisParam);
12749                }
12750
12751                if(typedObject)
12752                {
12753                   if(type.classObjectType != classPointer)
12754                   {
12755                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
12756                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
12757                   }
12758
12759                   thisParam = TypeName
12760                   {
12761                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
12762                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
12763                   };
12764                   funcDecl.function.parameters->Insert(null, thisParam);
12765                }
12766             }
12767          }
12768
12769          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12770          {
12771             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12772             funcDecl = GetFuncDecl(initDecl.declarator);
12773             if(funcDecl)
12774             {
12775                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12776                {
12777                   TypeName param = funcDecl.function.parameters->first;
12778                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12779                   {
12780                      funcDecl.function.parameters->Remove(param);
12781                      FreeTypeName(param);
12782                   }
12783                }
12784
12785                if(type.classObjectType != classPointer)
12786                {
12787                   // DANGER: Watch for this... Check if it's a Conversion?
12788                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12789                   {
12790                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12791
12792                      if(!funcDecl.function.parameters)
12793                         funcDecl.function.parameters = MkList();
12794                      funcDecl.function.parameters->Insert(null, thisParam);
12795                   }
12796                }
12797             }
12798          }
12799       }
12800
12801       // Add this to the context
12802       if(function.body)
12803       {
12804          if(type.classObjectType != classPointer)
12805          {
12806             thisSymbol = Symbol
12807             {
12808                string = CopyString("this");
12809                type = classSym ? MkClassType(classSym.string) : null; //_class.fullName);
12810             };
12811             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
12812
12813             if(typedObject && thisSymbol.type)
12814             {
12815                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
12816                thisSymbol.type.byReference = type.byReference;
12817                thisSymbol.type.typedByReference = type.byReference;
12818                /*
12819                thisSymbol = Symbol { string = CopyString("class") };
12820                function.body.compound.context.symbols.Add(thisSymbol);
12821                */
12822             }
12823          }
12824       }
12825
12826       // Pointer to class data
12827
12828       if(inCompiler && _class && (_class.type == normalClass /*|| _class.type == noHeadClass*/) && type.classObjectType != classPointer)
12829       {
12830          DataMember member = null;
12831          {
12832             Class base;
12833             for(base = _class; base && base.type != systemClass; base = base.next)
12834             {
12835                for(member = base.membersAndProperties.first; member; member = member.next)
12836                   if(!member.isProperty)
12837                      break;
12838                if(member)
12839                   break;
12840             }
12841          }
12842          for(member = _class.membersAndProperties.first; member; member = member.next)
12843             if(!member.isProperty)
12844                break;
12845          if(member)
12846          {
12847             char pointerName[1024];
12848
12849             Declaration decl;
12850             Initializer initializer;
12851             Expression exp, bytePtr;
12852
12853             strcpy(pointerName, "__ecerePointer_");
12854             FullClassNameCat(pointerName, _class.fullName, false);
12855             {
12856                char className[1024];
12857                strcpy(className, "__ecereClass_");
12858                FullClassNameCat(className, classSym.string, true);
12859                //MangleClassName(className);
12860
12861                // Testing This
12862                DeclareClass(classSym, className);
12863             }
12864
12865             // ((byte *) this)
12866             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
12867
12868             if(_class.fixed)
12869             {
12870                char string[256];
12871                sprintf(string, "%d", _class.offset);
12872                exp = QBrackets(MkExpOp(bytePtr, '+', MkExpConstant(string)));
12873             }
12874             else
12875             {
12876                // ([bytePtr] + [className]->offset)
12877                exp = QBrackets(MkExpOp(bytePtr, '+',
12878                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
12879             }
12880
12881             // (this ? [exp] : 0)
12882             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
12883             exp.expType = Type
12884             {
12885                refCount = 1;
12886                kind = pointerType;
12887                type = Type { refCount = 1, kind = voidType };
12888             };
12889
12890             if(function.body)
12891             {
12892                yylloc = function.body.loc;
12893                // ([structName] *) [exp]
12894                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
12895                initializer = MkInitializerAssignment(
12896                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
12897
12898                // [structName] * [pointerName] = [initializer];
12899                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
12900
12901                {
12902                   Context prevContext = curContext;
12903                   curContext = function.body.compound.context;
12904
12905                   decl = MkDeclaration(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)),
12906                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
12907
12908                   curContext = prevContext;
12909                }
12910
12911                // WHY?
12912                decl.symbol = null;
12913
12914                if(!function.body.compound.declarations)
12915                   function.body.compound.declarations = MkList();
12916                function.body.compound.declarations->Insert(null, decl);
12917             }
12918          }
12919       }
12920
12921
12922       // Loop through the function and replace undeclared identifiers
12923       // which are a member of the class (methods, properties or data)
12924       // by "this.[member]"
12925    }
12926    else
12927       thisClass = null;
12928
12929    if(id)
12930    {
12931       FreeSpecifier(id._class);
12932       id._class = null;
12933
12934       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12935       {
12936          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12937          id = GetDeclId(initDecl.declarator);
12938
12939          FreeSpecifier(id._class);
12940          id._class = null;
12941       }
12942    }
12943    if(function.body)
12944       topContext = function.body.compound.context;
12945    {
12946       FunctionDefinition oldFunction = curFunction;
12947       curFunction = function;
12948       if(function.body)
12949          ProcessStatement(function.body);
12950
12951       // If this is a property set and no firewatchers has been done yet, add one here
12952       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
12953       {
12954          Statement prevCompound = curCompound;
12955          Context prevContext = curContext;
12956
12957          Statement fireWatchers = MkFireWatchersStmt(null, null);
12958          if(!function.body.compound.statements) function.body.compound.statements = MkList();
12959          ListAdd(function.body.compound.statements, fireWatchers);
12960
12961          curCompound = function.body;
12962          curContext = function.body.compound.context;
12963
12964          ProcessStatement(fireWatchers);
12965
12966          curContext = prevContext;
12967          curCompound = prevCompound;
12968
12969       }
12970
12971       curFunction = oldFunction;
12972    }
12973
12974    if(function.declarator)
12975    {
12976       ProcessDeclarator(function.declarator);
12977    }
12978
12979    topContext = oldTopContext;
12980    thisClass = oldThisClass;
12981 }
12982
12983 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
12984 static void ProcessClass(OldList definitions, Symbol symbol)
12985 {
12986    ClassDef def;
12987    External external = curExternal;
12988    Class regClass = symbol ? symbol.registered : null;
12989
12990    // Process all functions
12991    for(def = definitions.first; def; def = def.next)
12992    {
12993       if(def.type == functionClassDef)
12994       {
12995          if(def.function.declarator)
12996             curExternal = def.function.declarator.symbol.pointerExternal;
12997          else
12998             curExternal = external;
12999
13000          ProcessFunction((FunctionDefinition)def.function);
13001       }
13002       else if(def.type == declarationClassDef)
13003       {
13004          if(def.decl.type == instDeclaration)
13005          {
13006             thisClass = regClass;
13007             ProcessInstantiationType(def.decl.inst);
13008             thisClass = null;
13009          }
13010          // Testing this
13011          else
13012          {
13013             Class backThisClass = thisClass;
13014             if(regClass) thisClass = regClass;
13015             ProcessDeclaration(def.decl);
13016             thisClass = backThisClass;
13017          }
13018       }
13019       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13020       {
13021          MemberInit defProperty;
13022
13023          // Add this to the context
13024          Symbol thisSymbol = Symbol
13025          {
13026             string = CopyString("this");
13027             type = regClass ? MkClassType(regClass.fullName) : null;
13028          };
13029          globalContext.symbols.Add((BTNode)thisSymbol);
13030
13031          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13032          {
13033             thisClass = regClass;
13034             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13035             thisClass = null;
13036          }
13037
13038          globalContext.symbols.Remove((BTNode)thisSymbol);
13039          FreeSymbol(thisSymbol);
13040       }
13041       else if(def.type == propertyClassDef && def.propertyDef)
13042       {
13043          PropertyDef prop = def.propertyDef;
13044
13045          // Add this to the context
13046          /*
13047          Symbol thisSymbol = Symbol { string = CopyString("this"), type = MkClassType(regClass.fullName) };
13048          globalContext.symbols.Add(thisSymbol);
13049          */
13050
13051          thisClass = regClass;
13052          if(prop.setStmt)
13053          {
13054             if(regClass)
13055             {
13056                Symbol thisSymbol
13057                {
13058                   string = CopyString("this");
13059                   type = MkClassType(regClass.fullName);
13060                };
13061                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13062             }
13063
13064             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13065             ProcessStatement(prop.setStmt);
13066          }
13067          if(prop.getStmt)
13068          {
13069             if(regClass)
13070             {
13071                Symbol thisSymbol
13072                {
13073                   string = CopyString("this");
13074                   type = MkClassType(regClass.fullName);
13075                };
13076                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13077             }
13078
13079             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13080             ProcessStatement(prop.getStmt);
13081          }
13082          if(prop.issetStmt)
13083          {
13084             if(regClass)
13085             {
13086                Symbol thisSymbol
13087                {
13088                   string = CopyString("this");
13089                   type = MkClassType(regClass.fullName);
13090                };
13091                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13092             }
13093
13094             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13095             ProcessStatement(prop.issetStmt);
13096          }
13097
13098          thisClass = null;
13099
13100          /*
13101          globalContext.symbols.Remove(thisSymbol);
13102          FreeSymbol(thisSymbol);
13103          */
13104       }
13105       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13106       {
13107          PropertyWatch propertyWatch = def.propertyWatch;
13108
13109          thisClass = regClass;
13110          if(propertyWatch.compound)
13111          {
13112             Symbol thisSymbol
13113             {
13114                string = CopyString("this");
13115                type = regClass ? MkClassType(regClass.fullName) : null;
13116             };
13117
13118             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13119
13120             curExternal = null;
13121             ProcessStatement(propertyWatch.compound);
13122          }
13123          thisClass = null;
13124       }
13125    }
13126 }
13127
13128 void DeclareFunctionUtil(const String s)
13129 {
13130    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13131    if(function)
13132    {
13133       char name[1024];
13134       name[0] = 0;
13135       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13136          strcpy(name, "__ecereFunction_");
13137       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13138       DeclareFunction(function, name);
13139    }
13140 }
13141
13142 void ComputeDataTypes()
13143 {
13144    External external;
13145    External temp { };
13146    External after = null;
13147
13148    currentClass = null;
13149
13150    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13151
13152    for(external = ast->first; external; external = external.next)
13153    {
13154       if(external.type == declarationExternal)
13155       {
13156          Declaration decl = external.declaration;
13157          if(decl)
13158          {
13159             OldList * decls = decl.declarators;
13160             if(decls)
13161             {
13162                InitDeclarator initDecl = decls->first;
13163                if(initDecl)
13164                {
13165                   Declarator declarator = initDecl.declarator;
13166                   if(declarator && declarator.type == identifierDeclarator)
13167                   {
13168                      Identifier id = declarator.identifier;
13169                      if(id && id.string)
13170                      {
13171                         if(!strcmp(id.string, "uintptr_t") || !strcmp(id.string, "intptr_t") || !strcmp(id.string, "size_t") || !strcmp(id.string, "ssize_t"))
13172                         {
13173                            external.symbol.id = -1001, external.symbol.idCode = -1001;
13174                            after = external;
13175                         }
13176                      }
13177                   }
13178                }
13179             }
13180          }
13181        }
13182    }
13183
13184    {
13185       // Workaround until we have proper toposort for declarations reordering
13186       External e = MkExternalDeclaration(MkDeclaration(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Instance"), null)), null));
13187       ast->Insert(after, e);
13188       after = e;
13189    }
13190
13191    temp.symbol = Symbol { id = -1000, idCode = -1000 };
13192    ast->Insert(after, temp);
13193    curExternal = temp;
13194
13195    DeclareFunctionUtil("eSystem_New");
13196    DeclareFunctionUtil("eSystem_New0");
13197    DeclareFunctionUtil("eSystem_Renew");
13198    DeclareFunctionUtil("eSystem_Renew0");
13199    DeclareFunctionUtil("eSystem_Delete");
13200    DeclareFunctionUtil("eClass_GetProperty");
13201    DeclareFunctionUtil("eClass_SetProperty");
13202    DeclareFunctionUtil("eInstance_FireSelfWatchers");
13203    DeclareFunctionUtil("eInstance_SetMethod");
13204    DeclareFunctionUtil("eInstance_IncRef");
13205    DeclareFunctionUtil("eInstance_StopWatching");
13206    DeclareFunctionUtil("eInstance_Watch");
13207    DeclareFunctionUtil("eInstance_FireWatchers");
13208
13209    DeclareStruct("ecere::com::Class", false);
13210    DeclareStruct("ecere::com::Instance", false);
13211    DeclareStruct("ecere::com::Property", false);
13212    DeclareStruct("ecere::com::DataMember", false);
13213    DeclareStruct("ecere::com::Method", false);
13214    DeclareStruct("ecere::com::SerialBuffer", false);
13215    DeclareStruct("ecere::com::ClassTemplateArgument", false);
13216
13217    ast->Remove(temp);
13218
13219    for(external = ast->first; external; external = external.next)
13220    {
13221       afterExternal = curExternal = external;
13222       if(external.type == functionExternal)
13223       {
13224          currentClass = external.function._class;
13225          ProcessFunction(external.function);
13226       }
13227       // There shouldn't be any _class member access here anyways...
13228       else if(external.type == declarationExternal)
13229       {
13230          currentClass = null;
13231          if(external.declaration)
13232             ProcessDeclaration(external.declaration);
13233       }
13234       else if(external.type == classExternal)
13235       {
13236          ClassDefinition _class = external._class;
13237          currentClass = external.symbol.registered;
13238          if(_class.definitions)
13239          {
13240             ProcessClass(_class.definitions, _class.symbol);
13241          }
13242          if(inCompiler)
13243          {
13244             // Free class data...
13245             ast->Remove(external);
13246             delete external;
13247          }
13248       }
13249       else if(external.type == nameSpaceExternal)
13250       {
13251          thisNameSpace = external.id.string;
13252       }
13253    }
13254    currentClass = null;
13255    thisNameSpace = null;
13256    curExternal = null;
13257
13258    delete temp.symbol;
13259    delete temp;
13260 }