compiler/libec: Fixed potential null pointer crashes
[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             if(!type.members.first && type.enumName)
822             {
823                Symbol symbol = FindStruct(curContext, type.enumName);
824                if(symbol && symbol.type)
825                {
826                   ComputeTypeSize(symbol.type);
827                   size = symbol.type.size;
828                }
829             }
830             else
831             {
832                Type member;
833                for(member = type.members.first; member; member = member.next)
834                {
835                   uint addSize = ComputeTypeSize(member);
836
837                   member.offset = size;
838                   if(member.alignment && size % member.alignment)
839                      member.offset += member.alignment - (size % member.alignment);
840                   size = member.offset;
841
842                   type.alignment = Max(type.alignment, member.alignment);
843                   size += addSize;
844                }
845                if(type.alignment && size % type.alignment)
846                   size += type.alignment - (size % type.alignment);
847             }
848             break;
849          }
850          case unionType:
851          {
852             if(!type.members.first && type.enumName)
853             {
854                Symbol symbol = FindStruct(curContext, type.enumName);
855                if(symbol && symbol.type)
856                {
857                   ComputeTypeSize(symbol.type);
858                   size = symbol.type.size;
859                }
860             }
861             else
862             {
863                Type member;
864                for(member = type.members.first; member; member = member.next)
865                {
866                   uint addSize = ComputeTypeSize(member);
867
868                   member.offset = size;
869                   if(member.alignment && size % member.alignment)
870                      member.offset += member.alignment - (size % member.alignment);
871                   size = member.offset;
872
873                   type.alignment = Max(type.alignment, member.alignment);
874                   size = Max(size, addSize);
875                }
876                if(type.alignment && size % type.alignment)
877                   size += type.alignment - (size % type.alignment);
878             }
879             break;
880          }
881          case templateType:
882          {
883             TemplateParameter param = type.templateParameter;
884             Type baseType = ProcessTemplateParameterType(param);
885             if(baseType)
886             {
887                size = ComputeTypeSize(baseType);
888                type.alignment = baseType.alignment;
889             }
890             else
891                type.alignment = size = sizeof(uint64);
892             break;
893          }
894          case enumType:
895          {
896             type.alignment = size = sizeof(enum { test });
897             break;
898          }
899          case thisClassType:
900          {
901             type.alignment = size = targetBits / 8; //sizeof(void *);
902             break;
903          }
904       }
905       type.size = size;
906       type.computing = false;
907    }
908    return size;
909 }
910
911
912 /*static */int AddMembers(OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
913 {
914    // This function is in need of a major review when implementing private members etc.
915    DataMember topMember = isMember ? (DataMember) _class : null;
916    uint totalSize = 0;
917    uint maxSize = 0;
918    int alignment;
919    uint size;
920    DataMember member;
921    int anonID = 1;
922    Context context = isMember ? null : SetupTemplatesContext(_class);
923    if(addedPadding)
924       *addedPadding = false;
925
926    if(!isMember && _class.base)
927    {
928       maxSize = _class.structSize;
929       //if(_class.base.type != systemClass) // Commented out with new Instance _class
930       {
931          // DANGER: Testing this noHeadClass here...
932          if(_class.type == structClass || _class.type == noHeadClass)
933             /*totalSize = */AddMembers(declarations, _class.base, false, &totalSize, topClass, null);
934          else
935          {
936             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
937             if(maxSize > baseSize)
938                maxSize -= baseSize;
939             else
940                maxSize = 0;
941          }
942       }
943    }
944
945    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
946    {
947       if(!member.isProperty)
948       {
949          switch(member.type)
950          {
951             case normalMember:
952             {
953                if(member.dataTypeString)
954                {
955                   OldList * specs = MkList(), * decls = MkList();
956                   Declarator decl;
957
958                   decl = SpecDeclFromString(member.dataTypeString, specs,
959                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
960                   ListAdd(decls, MkStructDeclarator(decl, null));
961                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
962
963                   if(!member.dataType)
964                      member.dataType = ProcessType(specs, decl);
965
966                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
967
968                   {
969                      Type type = ProcessType(specs, decl);
970                      DeclareType(member.dataType, false, false);
971                      FreeType(type);
972                   }
973                   /*
974                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
975                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
976                      DeclareStruct(member.dataType._class.string, false);
977                   */
978
979                   ComputeTypeSize(member.dataType);
980                   size = member.dataType.size;
981                   alignment = member.dataType.alignment;
982
983                   if(alignment)
984                   {
985                      if(totalSize % alignment)
986                         totalSize += alignment - (totalSize % alignment);
987                   }
988                   totalSize += size;
989                }
990                break;
991             }
992             case unionMember:
993             case structMember:
994             {
995                OldList * specs = MkList(), * list = MkList();
996                char id[100];
997                sprintf(id, "__anon%d", anonID++);
998
999                size = 0;
1000                AddMembers(list, (Class)member, true, &size, topClass, null);
1001                ListAdd(specs,
1002                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
1003                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, MkListOne(MkDeclaratorIdentifier(MkIdentifier(id))),null)));
1004                alignment = member.structAlignment;
1005
1006                if(alignment)
1007                {
1008                   if(totalSize % alignment)
1009                      totalSize += alignment - (totalSize % alignment);
1010                }
1011                totalSize += size;
1012                break;
1013             }
1014          }
1015       }
1016    }
1017    if(retSize)
1018    {
1019       if(topMember && topMember.type == unionMember)
1020          *retSize = Max(*retSize, totalSize);
1021       else
1022          *retSize += totalSize;
1023    }
1024    else if(totalSize < maxSize && _class.type != systemClass)
1025    {
1026       int autoPadding = 0;
1027       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
1028          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
1029       if(totalSize + autoPadding < maxSize)
1030       {
1031          char sizeString[50];
1032          sprintf(sizeString, "%d", maxSize - totalSize);
1033          ListAdd(declarations,
1034             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
1035             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
1036          if(addedPadding)
1037             *addedPadding = true;
1038       }
1039    }
1040    if(context)
1041       FinishTemplatesContext(context);
1042    return topMember ? topMember.memberID : _class.memberID;
1043 }
1044
1045 static int DeclareMembers(Class _class, bool isMember)
1046 {
1047    DataMember topMember = isMember ? (DataMember) _class : null;
1048    DataMember member;
1049    Context context = isMember ? null : SetupTemplatesContext(_class);
1050
1051    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1052       DeclareMembers(_class.base, false);
1053
1054    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1055    {
1056       if(!member.isProperty)
1057       {
1058          switch(member.type)
1059          {
1060             case normalMember:
1061             {
1062                /*
1063                if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
1064                   member.dataType._class.registered && member.dataType._class.registered.type == structClass)
1065                   DeclareStruct(member.dataType._class.string, false);
1066                   */
1067                if(!member.dataType && member.dataTypeString)
1068                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1069                if(member.dataType)
1070                   DeclareType(member.dataType, false, false);
1071                break;
1072             }
1073             case unionMember:
1074             case structMember:
1075             {
1076                DeclareMembers((Class)member, true);
1077                break;
1078             }
1079          }
1080       }
1081    }
1082    if(context)
1083       FinishTemplatesContext(context);
1084
1085    return topMember ? topMember.memberID : _class.memberID;
1086 }
1087
1088 static void IdentifyAnonStructs(OldList/*<ClassDef>*/ *  definitions)
1089 {
1090    ClassDef def;
1091    int anonID = 1;
1092    for(def = definitions->first; def; def = def.next)
1093    {
1094       if(def.type == declarationClassDef)
1095       {
1096          Declaration decl = def.decl;
1097          if(decl && decl.specifiers)
1098          {
1099             Specifier spec;
1100             bool isStruct = false;
1101             for(spec = decl.specifiers->first; spec; spec = spec.next)
1102             {
1103                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1104                {
1105                   if(spec.definitions)
1106                      IdentifyAnonStructs(spec.definitions);
1107                   isStruct = true;
1108                }
1109             }
1110             if(isStruct)
1111             {
1112                Declarator d = null;
1113                if(decl.declarators)
1114                {
1115                   for(d = decl.declarators->first; d; d = d.next)
1116                   {
1117                      Identifier idDecl = GetDeclId(d);
1118                      if(idDecl)
1119                         break;
1120                   }
1121                }
1122                if(!d)
1123                {
1124                   char id[100];
1125                   sprintf(id, "__anon%d", anonID++);
1126                   if(!decl.declarators)
1127                      decl.declarators = MkList();
1128                   ListAdd(decl.declarators, MkDeclaratorIdentifier(MkIdentifier(id)));
1129                }
1130             }
1131          }
1132       }
1133    }
1134 }
1135
1136 void DeclareStruct(const char * name, bool skipNoHead)
1137 {
1138    External external = null;
1139    Symbol classSym = FindClass(name);
1140
1141    if(!inCompiler || !classSym) return;
1142
1143    // We don't need any declaration for bit classes...
1144    if(classSym.registered &&
1145       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1146       return;
1147
1148    /*if(classSym.registered.templateClass)
1149       return DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1150    */
1151
1152    if(classSym.registered && classSym.imported && !classSym.declaredStructSym)
1153    {
1154       // Add typedef struct
1155       Declaration decl;
1156       OldList * specifiers, * declarators;
1157       OldList * declarations = null;
1158       char structName[1024];
1159       Specifier spec = null;
1160       external = (classSym.registered && classSym.registered.type == structClass) ?
1161          classSym.pointerExternal : classSym.structExternal;
1162
1163       // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1164       // Moved this one up because DeclareClass done later will need it
1165
1166       classSym.declaring++;
1167
1168       if(strchr(classSym.string, '<'))
1169       {
1170          if(classSym.registered.templateClass)
1171          {
1172             DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1173             classSym.declaring--;
1174          }
1175          return;
1176       }
1177
1178       //if(!skipNoHead)
1179          DeclareMembers(classSym.registered, false);
1180
1181       structName[0] = 0;
1182       FullClassNameCat(structName, name, false);
1183
1184       if(external && external.declaration && external.declaration.specifiers)
1185       {
1186          for(spec = external.declaration.specifiers->first; spec; spec = spec.next)
1187          {
1188             if(spec.type == structSpecifier || spec.type == unionSpecifier)
1189                break;
1190          }
1191       }
1192
1193       /*if(!external)
1194          external = MkExternalDeclaration(null);*/
1195
1196       if(!skipNoHead && (!spec || !spec.definitions))
1197       {
1198          bool addedPadding = false;
1199          classSym.declaredStructSym = true;
1200
1201          declarations = MkList();
1202
1203          AddMembers(declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1204
1205          //ListAdd(specifiers, MkSpecifier(TYPEDEF));
1206          //ListAdd(specifiers, MkStructOrUnion(structSpecifier, null, declarations));
1207
1208          if(!declarations->count || (declarations->count == 1 && addedPadding))
1209          {
1210             FreeList(declarations, FreeClassDef);
1211             declarations = null;
1212          }
1213       }
1214       if(skipNoHead || declarations)
1215       {
1216          if(spec)
1217          {
1218             if(declarations)
1219                spec.definitions = declarations;
1220
1221             if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1222             {
1223                // TODO: Fix this
1224                //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1225
1226                // DANGER
1227                if(classSym.structExternal)
1228                   ast->Move(classSym.structExternal, curExternal.prev);
1229                ast->Move(classSym.pointerExternal, curExternal.prev);
1230
1231                classSym.id = curExternal.symbol.idCode;
1232                classSym.idCode = curExternal.symbol.idCode;
1233                // external = classSym.pointerExternal;
1234                //external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1235             }
1236          }
1237          else
1238          {
1239             if(!external)
1240                external = MkExternalDeclaration(null);
1241
1242             specifiers = MkList();
1243             declarators = MkList();
1244             ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1245
1246             /*
1247             d = MkDeclaratorIdentifier(MkIdentifier(structName));
1248             ListAdd(declarators, MkInitDeclarator(d, null));
1249             */
1250             external.declaration = decl = MkDeclaration(specifiers, declarators);
1251             if(decl.symbol && !decl.symbol.pointerExternal)
1252                decl.symbol.pointerExternal = external;
1253
1254             // For simple classes, keep the declaration as the external to move around
1255             if(classSym.registered && classSym.registered.type == structClass)
1256             {
1257                char className[1024];
1258                strcpy(className, "__ecereClass_");
1259                FullClassNameCat(className, classSym.string, true);
1260                //MangleClassName(className);
1261
1262                // Testing This
1263                DeclareClass(classSym, className);
1264
1265                external.symbol = classSym;
1266                classSym.pointerExternal = external;
1267                classSym.id = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1268                classSym.idCode = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1269             }
1270             else
1271             {
1272                char className[1024];
1273                strcpy(className, "__ecereClass_");
1274                FullClassNameCat(className, classSym.string, true);
1275                //MangleClassName(className);
1276
1277                // TOFIX: TESTING THIS...
1278                classSym.structExternal = external;
1279                DeclareClass(classSym, className);
1280                external.symbol = classSym;
1281             }
1282
1283             //if(curExternal)
1284                ast->Insert(curExternal ? curExternal.prev : null, external);
1285          }
1286       }
1287
1288       classSym.declaring--;
1289    }
1290    else
1291    {
1292       if(classSym.structExternal && classSym.structExternal.declaration && classSym.structExternal.declaration.specifiers)
1293       {
1294          Specifier spec;
1295          for(spec = classSym.structExternal.declaration.specifiers->first; spec; spec = spec.next)
1296          {
1297             IdentifyAnonStructs(spec.definitions);
1298          }
1299       }
1300
1301       if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1302       {
1303          // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1304          // Moved this one up because DeclareClass done later will need it
1305
1306          // TESTING THIS:
1307          classSym.declaring++;
1308
1309          //if(!skipNoHead)
1310          {
1311             if(classSym.registered)
1312                DeclareMembers(classSym.registered, false);
1313          }
1314
1315          if(classSym.registered && (classSym.registered.type == structClass || classSym.registered.type == noHeadClass))
1316          {
1317             // TODO: Fix this
1318             //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1319
1320             // DANGER
1321             if(classSym.structExternal)
1322                ast->Move(classSym.structExternal, curExternal.prev);
1323             ast->Move(classSym.pointerExternal, curExternal.prev);
1324
1325             classSym.id = curExternal.symbol.idCode;
1326             classSym.idCode = curExternal.symbol.idCode;
1327             // external = classSym.pointerExternal;
1328             // external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1329          }
1330
1331          classSym.declaring--;
1332       }
1333    }
1334    //return external;
1335 }
1336
1337 void DeclareProperty(Property prop, char * setName, char * getName)
1338 {
1339    Symbol symbol = prop.symbol;
1340
1341    strcpy(setName, "__ecereProp_");
1342    FullClassNameCat(setName, prop._class.fullName, false);
1343    strcat(setName, "_Set_");
1344    // strcat(setName, prop.name);
1345    FullClassNameCat(setName, prop.name, true);
1346    //MangleClassName(setName);
1347
1348    strcpy(getName, "__ecereProp_");
1349    FullClassNameCat(getName, prop._class.fullName, false);
1350    strcat(getName, "_Get_");
1351    FullClassNameCat(getName, prop.name, true);
1352    // strcat(getName, prop.name);
1353
1354    // To support "char *" property
1355    //MangleClassName(getName);
1356
1357    if(prop._class.type == structClass)
1358       DeclareStruct(prop._class.fullName, false);
1359
1360    if(!symbol || curExternal.symbol.idCode < symbol.id)
1361    {
1362       bool imported = false;
1363       bool dllImport = false;
1364
1365       if(!symbol || symbol._import)
1366       {
1367          if(!symbol)
1368          {
1369             Symbol classSym;
1370             if(!prop._class.symbol)
1371                prop._class.symbol = FindClass(prop._class.fullName);
1372             classSym = prop._class.symbol;
1373             if(classSym && !classSym._import)
1374             {
1375                ModuleImport module;
1376
1377                if(prop._class.module)
1378                   module = FindModule(prop._class.module);
1379                else
1380                   module = mainModule;
1381
1382                classSym._import = ClassImport
1383                {
1384                   name = CopyString(prop._class.fullName);
1385                   isRemote = prop._class.isRemote;
1386                };
1387                module.classes.Add(classSym._import);
1388             }
1389             symbol = prop.symbol = Symbol { };
1390             symbol._import = (ClassImport)PropertyImport
1391             {
1392                name = CopyString(prop.name);
1393                isVirtual = false; //prop.isVirtual;
1394                hasSet = prop.Set ? true : false;
1395                hasGet = prop.Get ? true : false;
1396             };
1397             if(classSym)
1398                classSym._import.properties.Add(symbol._import);
1399          }
1400          imported = true;
1401          // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1402          if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1403             prop._class.module.importType != staticImport)
1404             dllImport = true;
1405       }
1406
1407       if(!symbol.type)
1408       {
1409          Context context = SetupTemplatesContext(prop._class);
1410          symbol.type = ProcessTypeString(prop.dataTypeString, false);
1411          FinishTemplatesContext(context);
1412       }
1413
1414       // Get
1415       if(prop.Get)
1416       {
1417          if(!symbol.externalGet || symbol.externalGet.type == functionExternal)
1418          {
1419             Declaration decl;
1420             OldList * specifiers, * declarators;
1421             Declarator d;
1422             OldList * params;
1423             Specifier spec;
1424             External external;
1425             Declarator typeDecl;
1426             bool simple = false;
1427
1428             specifiers = MkList();
1429             declarators = MkList();
1430             params = MkList();
1431
1432             ListAdd(params, MkTypeName(MkListOne(MkSpecifierName /*MkClassName*/(prop._class.fullName)),
1433                MkDeclaratorIdentifier(MkIdentifier("this"))));
1434
1435             d = MkDeclaratorIdentifier(MkIdentifier(getName));
1436             //if(imported)
1437             if(dllImport)
1438                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1439
1440             {
1441                Context context = SetupTemplatesContext(prop._class);
1442                typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1443                FinishTemplatesContext(context);
1444             }
1445
1446             // Make sure the simple _class's type is declared
1447             for(spec = specifiers->first; spec; spec = spec.next)
1448             {
1449                if(spec.type == nameSpecifier /*SpecifierClass*/)
1450                {
1451                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1452                   {
1453                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1454                      symbol._class = classSym.registered;
1455                      if(classSym.registered && classSym.registered.type == structClass)
1456                      {
1457                         DeclareStruct(spec.name, false);
1458                         simple = true;
1459                      }
1460                   }
1461                }
1462             }
1463
1464             if(!simple)
1465                d = PlugDeclarator(typeDecl, d);
1466             else
1467             {
1468                ListAdd(params, MkTypeName(specifiers,
1469                   PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1470                specifiers = MkList();
1471             }
1472
1473             d = MkDeclaratorFunction(d, params);
1474
1475             //if(imported)
1476             if(dllImport)
1477                specifiers->Insert(null, MkSpecifier(EXTERN));
1478             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1479                specifiers->Insert(null, MkSpecifier(STATIC));
1480             if(simple)
1481                ListAdd(specifiers, MkSpecifier(VOID));
1482
1483             ListAdd(declarators, MkInitDeclarator(d, null));
1484
1485             decl = MkDeclaration(specifiers, declarators);
1486
1487             external = MkExternalDeclaration(decl);
1488             ast->Insert(curExternal.prev, external);
1489             external.symbol = symbol;
1490             symbol.externalGet = external;
1491
1492             ReplaceThisClassSpecifiers(specifiers, prop._class);
1493
1494             if(typeDecl)
1495                FreeDeclarator(typeDecl);
1496          }
1497          else
1498          {
1499             // Move declaration higher...
1500             ast->Move(symbol.externalGet, curExternal.prev);
1501          }
1502       }
1503
1504       // Set
1505       if(prop.Set)
1506       {
1507          if(!symbol.externalSet || symbol.externalSet.type == functionExternal)
1508          {
1509             Declaration decl;
1510             OldList * specifiers, * declarators;
1511             Declarator d;
1512             OldList * params;
1513             Specifier spec;
1514             External external;
1515             Declarator typeDecl;
1516
1517             declarators = MkList();
1518             params = MkList();
1519
1520             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1521             if(!prop.conversion || prop._class.type == structClass)
1522             {
1523                ListAdd(params, MkTypeName(MkListOne(MkSpecifierName/*MkClassName*/(prop._class.fullName)),
1524                   MkDeclaratorIdentifier(MkIdentifier("this"))));
1525             }
1526
1527             specifiers = MkList();
1528
1529             {
1530                Context context = SetupTemplatesContext(prop._class);
1531                typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1532                   MkDeclaratorIdentifier(MkIdentifier("value")));
1533                FinishTemplatesContext(context);
1534             }
1535             if(!strcmp(prop._class.base.fullName, "eda::Row") || !strcmp(prop._class.base.fullName, "eda::Id"))
1536                specifiers->Insert(null, MkSpecifier(CONST));
1537
1538             ListAdd(params, MkTypeName(specifiers, d));
1539
1540             d = MkDeclaratorIdentifier(MkIdentifier(setName));
1541             //if(imported)
1542             if(dllImport)
1543                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1544             d = MkDeclaratorFunction(d, params);
1545
1546             // Make sure the simple _class's type is declared
1547             for(spec = specifiers->first; spec; spec = spec.next)
1548             {
1549                if(spec.type == nameSpecifier /*SpecifierClass*/)
1550                {
1551                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1552                   {
1553                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1554                      symbol._class = classSym.registered;
1555                      if(classSym.registered && classSym.registered.type == structClass)
1556                         DeclareStruct(spec.name, false);
1557                   }
1558                }
1559             }
1560
1561             ListAdd(declarators, MkInitDeclarator(d, null));
1562
1563             specifiers = MkList();
1564             //if(imported)
1565             if(dllImport)
1566                specifiers->Insert(null, MkSpecifier(EXTERN));
1567             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1568                specifiers->Insert(null, MkSpecifier(STATIC));
1569
1570             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1571             if(!prop.conversion || prop._class.type == structClass)
1572                ListAdd(specifiers, MkSpecifier(VOID));
1573             else
1574                ListAdd(specifiers, MkSpecifierName/*MkClassName*/(prop._class.fullName));
1575
1576             decl = MkDeclaration(specifiers, declarators);
1577
1578             external = MkExternalDeclaration(decl);
1579             ast->Insert(curExternal.prev, external);
1580             external.symbol = symbol;
1581             symbol.externalSet = external;
1582
1583             ReplaceThisClassSpecifiers(specifiers, prop._class);
1584          }
1585          else
1586          {
1587             // Move declaration higher...
1588             ast->Move(symbol.externalSet, curExternal.prev);
1589          }
1590       }
1591
1592       // Property (for Watchers)
1593       if(!symbol.externalPtr)
1594       {
1595          Declaration decl;
1596          External external;
1597          OldList * specifiers = MkList();
1598          char propName[1024];
1599
1600          if(imported)
1601             specifiers->Insert(null, MkSpecifier(EXTERN));
1602          else
1603          {
1604             specifiers->Insert(null, MkSpecifier(STATIC));
1605             specifiers->Add(MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
1606          }
1607
1608          ListAdd(specifiers, MkSpecifierName("Property"));
1609
1610          strcpy(propName, "__ecereProp_");
1611          FullClassNameCat(propName, prop._class.fullName, false);
1612          strcat(propName, "_");
1613          FullClassNameCat(propName, prop.name, true);
1614          // strcat(propName, prop.name);
1615          //MangleClassName(propName);
1616
1617          {
1618             OldList * list = MkList();
1619             ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1620
1621             if(!imported)
1622             {
1623                strcpy(propName, "__ecerePropM_");
1624                FullClassNameCat(propName, prop._class.fullName, false);
1625                strcat(propName, "_");
1626                // strcat(propName, prop.name);
1627                FullClassNameCat(propName, prop.name, true);
1628
1629                //MangleClassName(propName);
1630
1631                ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1632             }
1633             decl = MkDeclaration(specifiers, list);
1634          }
1635
1636          external = MkExternalDeclaration(decl);
1637          ast->Insert(curExternal.prev, external);
1638          external.symbol = symbol;
1639          symbol.externalPtr = external;
1640       }
1641       else
1642       {
1643          // Move declaration higher...
1644          ast->Move(symbol.externalPtr, curExternal.prev);
1645       }
1646
1647       symbol.id = curExternal.symbol.idCode;
1648    }
1649 }
1650
1651 // ***************** EXPRESSION PROCESSING ***************************
1652 public Type Dereference(Type source)
1653 {
1654    Type type = null;
1655    if(source)
1656    {
1657       if(source.kind == pointerType || source.kind == arrayType)
1658       {
1659          type = source.type;
1660          source.type.refCount++;
1661       }
1662       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1663       {
1664          type = Type
1665          {
1666             kind = charType;
1667             refCount = 1;
1668          };
1669       }
1670       // Support dereferencing of no head classes for now...
1671       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1672       {
1673          type = source;
1674          source.refCount++;
1675       }
1676       else
1677          Compiler_Error($"cannot dereference type\n");
1678    }
1679    return type;
1680 }
1681
1682 static Type Reference(Type source)
1683 {
1684    Type type = null;
1685    if(source)
1686    {
1687       type = Type
1688       {
1689          kind = pointerType;
1690          type = source;
1691          refCount = 1;
1692       };
1693       source.refCount++;
1694    }
1695    return type;
1696 }
1697
1698 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1699 {
1700    Identifier ident = member.identifiers ? member.identifiers->first : null;
1701    bool found = false;
1702    DataMember dataMember = null;
1703    Method method = null;
1704    bool freeType = false;
1705
1706    yylloc = member.loc;
1707
1708    if(!ident)
1709    {
1710       if(curMember)
1711       {
1712          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1713          if(*curMember)
1714          {
1715             found = true;
1716             dataMember = *curMember;
1717          }
1718       }
1719    }
1720    else
1721    {
1722       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1723       DataMember _subMemberStack[256];
1724       int _subMemberStackPos = 0;
1725
1726       // FILL MEMBER STACK
1727       if(!thisMember)
1728          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1729       if(thisMember)
1730       {
1731          dataMember = thisMember;
1732          if(curMember && thisMember.memberAccess == publicAccess)
1733          {
1734             *curMember = thisMember;
1735             *curClass = thisMember._class;
1736             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1737             *subMemberStackPos = _subMemberStackPos;
1738          }
1739          found = true;
1740       }
1741       else
1742       {
1743          // Setting a method
1744          method = eClass_FindMethod(_class, ident.string, privateModule);
1745          if(method && method.type == virtualMethod)
1746             found = true;
1747          else
1748             method = null;
1749       }
1750    }
1751
1752    if(found)
1753    {
1754       Type type = null;
1755       if(dataMember)
1756       {
1757          if(!dataMember.dataType && dataMember.dataTypeString)
1758          {
1759             //Context context = SetupTemplatesContext(dataMember._class);
1760             Context context = SetupTemplatesContext(_class);
1761             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1762             FinishTemplatesContext(context);
1763          }
1764          type = dataMember.dataType;
1765       }
1766       else if(method)
1767       {
1768          // This is for destination type...
1769          if(!method.dataType)
1770             ProcessMethodType(method);
1771          //DeclareMethod(method);
1772          // method.dataType = ((Symbol)method.symbol)->type;
1773          type = method.dataType;
1774       }
1775
1776       if(ident && ident.next)
1777       {
1778          for(ident = ident.next; ident && type; ident = ident.next)
1779          {
1780             if(type.kind == classType)
1781             {
1782                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1783                if(!dataMember)
1784                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1785                if(dataMember)
1786                   type = dataMember.dataType;
1787             }
1788             else if(type.kind == structType || type.kind == unionType)
1789             {
1790                Type memberType;
1791                for(memberType = type.members.first; memberType; memberType = memberType.next)
1792                {
1793                   if(!strcmp(memberType.name, ident.string))
1794                   {
1795                      type = memberType;
1796                      break;
1797                   }
1798                }
1799             }
1800          }
1801       }
1802
1803       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1804       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1805       {
1806          int id = 0;
1807          ClassTemplateParameter curParam = null;
1808          Class sClass;
1809          for(sClass = _class; sClass; sClass = sClass.base)
1810          {
1811             id = 0;
1812             if(sClass.templateClass) sClass = sClass.templateClass;
1813             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1814             {
1815                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1816                {
1817                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1818                   {
1819                      if(sClass.templateClass) sClass = sClass.templateClass;
1820                      id += sClass.templateParams.count;
1821                   }
1822                   break;
1823                }
1824                id++;
1825             }
1826             if(curParam) break;
1827          }
1828
1829          if(curParam)
1830          {
1831             ClassTemplateArgument arg = _class.templateArgs[id];
1832             if(arg.dataTypeString)
1833             {
1834                bool constant = type.constant;
1835                // FreeType(type);
1836                type = ProcessTypeString(arg.dataTypeString, false);
1837                if(type.kind == classType && constant) type.constant = true;
1838                else if(type.kind == pointerType)
1839                {
1840                   Type t = type.type;
1841                   while(t.kind == pointerType) t = t.type;
1842                   if(constant) t.constant = constant;
1843                }
1844                freeType = true;
1845                if(type && _class.templateClass)
1846                   type.passAsTemplate = true;
1847                if(type)
1848                {
1849                   // type.refCount++;
1850                   /*if(!exp.destType)
1851                   {
1852                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1853                      exp.destType.refCount++;
1854                   }*/
1855                }
1856             }
1857          }
1858       }
1859       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1860       {
1861          Class expClass = type._class.registered;
1862          Class cClass = null;
1863          int paramCount = 0;
1864          int lastParam = -1;
1865
1866          char templateString[1024];
1867          ClassTemplateParameter param;
1868          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1869          for(cClass = expClass; cClass; cClass = cClass.base)
1870          {
1871             int p = 0;
1872             if(cClass.templateClass) cClass = cClass.templateClass;
1873             for(param = cClass.templateParams.first; param; param = param.next)
1874             {
1875                int id = p;
1876                Class sClass;
1877                ClassTemplateArgument arg;
1878                for(sClass = cClass.base; sClass; sClass = sClass.base)
1879                {
1880                   if(sClass.templateClass) sClass = sClass.templateClass;
1881                   id += sClass.templateParams.count;
1882                }
1883                arg = expClass.templateArgs[id];
1884
1885                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1886                {
1887                   ClassTemplateParameter cParam;
1888                   //int p = numParams - sClass.templateParams.count;
1889                   int p = 0;
1890                   Class nextClass;
1891                   if(sClass.templateClass) sClass = sClass.templateClass;
1892
1893                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1894                   {
1895                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1896                      p += nextClass.templateParams.count;
1897                   }
1898
1899                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1900                   {
1901                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1902                      {
1903                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1904                         {
1905                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1906                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1907                            break;
1908                         }
1909                      }
1910                   }
1911                }
1912
1913                {
1914                   char argument[256];
1915                   argument[0] = '\0';
1916                   /*if(arg.name)
1917                   {
1918                      strcat(argument, arg.name.string);
1919                      strcat(argument, " = ");
1920                   }*/
1921                   switch(param.type)
1922                   {
1923                      case expression:
1924                      {
1925                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1926                         char expString[1024];
1927                         OldList * specs = MkList();
1928                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1929                         Expression exp;
1930                         char * string = PrintHexUInt64(arg.expression.ui64);
1931                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1932                         delete string;
1933
1934                         ProcessExpressionType(exp);
1935                         ComputeExpression(exp);
1936                         expString[0] = '\0';
1937                         PrintExpression(exp, expString);
1938                         strcat(argument, expString);
1939                         //delete exp;
1940                         FreeExpression(exp);
1941                         break;
1942                      }
1943                      case identifier:
1944                      {
1945                         strcat(argument, arg.member.name);
1946                         break;
1947                      }
1948                      case TemplateParameterType::type:
1949                      {
1950                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1951                            strcat(argument, arg.dataTypeString);
1952                         break;
1953                      }
1954                   }
1955                   if(argument[0])
1956                   {
1957                      if(paramCount) strcat(templateString, ", ");
1958                      if(lastParam != p - 1)
1959                      {
1960                         strcat(templateString, param.name);
1961                         strcat(templateString, " = ");
1962                      }
1963                      strcat(templateString, argument);
1964                      paramCount++;
1965                      lastParam = p;
1966                   }
1967                   p++;
1968                }
1969             }
1970          }
1971          {
1972             int len = strlen(templateString);
1973             if(templateString[len-1] == '<')
1974                len--;
1975             else
1976             {
1977                if(templateString[len-1] == '>')
1978                   templateString[len++] = ' ';
1979                templateString[len++] = '>';
1980             }
1981             templateString[len++] = '\0';
1982          }
1983          {
1984             Context context = SetupTemplatesContext(_class);
1985             if(freeType) FreeType(type);
1986             type = ProcessTypeString(templateString, false);
1987             freeType = true;
1988             FinishTemplatesContext(context);
1989          }
1990       }
1991
1992       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1993       {
1994          ProcessExpressionType(member.initializer.exp);
1995          if(!member.initializer.exp.expType)
1996          {
1997             if(inCompiler)
1998             {
1999                char expString[10240];
2000                expString[0] = '\0';
2001                PrintExpression(member.initializer.exp, expString);
2002                ChangeCh(expString, '\n', ' ');
2003                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
2004             }
2005          }
2006          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
2007          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
2008          {
2009             Compiler_Error($"incompatible instance method %s\n", ident.string);
2010          }
2011       }
2012       else if(member.initializer)
2013       {
2014          /*
2015          FreeType(member.exp.destType);
2016          member.exp.destType = type;
2017          if(member.exp.destType)
2018             member.exp.destType.refCount++;
2019          ProcessExpressionType(member.exp);
2020          */
2021
2022          ProcessInitializer(member.initializer, type);
2023       }
2024       if(freeType) FreeType(type);
2025    }
2026    else
2027    {
2028       if(_class && _class.type == unitClass)
2029       {
2030          if(member.initializer)
2031          {
2032             /*
2033             FreeType(member.exp.destType);
2034             member.exp.destType = MkClassType(_class.fullName);
2035             ProcessExpressionType(member.initializer, type);
2036             */
2037             Type type = MkClassType(_class.fullName);
2038             ProcessInitializer(member.initializer, type);
2039             FreeType(type);
2040          }
2041       }
2042       else
2043       {
2044          if(member.initializer)
2045          {
2046             //ProcessExpressionType(member.exp);
2047             ProcessInitializer(member.initializer, null);
2048          }
2049          if(ident)
2050          {
2051             if(method)
2052             {
2053                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2054             }
2055             else if(_class)
2056             {
2057                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2058                if(inCompiler)
2059                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2060             }
2061          }
2062          else if(_class)
2063             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2064       }
2065    }
2066 }
2067
2068 void ProcessInstantiationType(Instantiation inst)
2069 {
2070    yylloc = inst.loc;
2071    if(inst._class)
2072    {
2073       MembersInit members;
2074       Symbol classSym; // = inst._class.symbol; // FindClass(inst._class.name);
2075       Class _class;
2076
2077       /*if(!inst._class.symbol)
2078          inst._class.symbol = FindClass(inst._class.name);*/
2079       classSym = inst._class.symbol;
2080       _class = classSym ? classSym.registered : null;
2081
2082       // DANGER: Patch for mutex not declaring its struct when not needed
2083       if(!_class || _class.type != noHeadClass)
2084          DeclareStruct(inst._class.name, false); //_class && _class.type == noHeadClass);
2085
2086       afterExternal = afterExternal ? afterExternal : curExternal;
2087
2088       if(inst.exp)
2089          ProcessExpressionType(inst.exp);
2090
2091       inst.isConstant = true;
2092       if(inst.members)
2093       {
2094          DataMember curMember = null;
2095          Class curClass = null;
2096          DataMember subMemberStack[256];
2097          int subMemberStackPos = 0;
2098
2099          for(members = inst.members->first; members; members = members.next)
2100          {
2101             switch(members.type)
2102             {
2103                case methodMembersInit:
2104                {
2105                   char name[1024];
2106                   static uint instMethodID = 0;
2107                   External external = curExternal;
2108                   Context context = curContext;
2109                   Declarator declarator = members.function.declarator;
2110                   Identifier nameID = GetDeclId(declarator);
2111                   char * unmangled = nameID ? nameID.string : null;
2112                   Expression exp;
2113                   External createdExternal = null;
2114
2115                   if(inCompiler)
2116                   {
2117                      char number[16];
2118                      //members.function.dontMangle = true;
2119                      strcpy(name, "__ecereInstMeth_");
2120                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2121                      strcat(name, "_");
2122                      strcat(name, nameID.string);
2123                      strcat(name, "_");
2124                      sprintf(number, "_%08d", instMethodID++);
2125                      strcat(name, number);
2126                      nameID.string = CopyString(name);
2127                   }
2128
2129                   // Do modifications here...
2130                   if(declarator)
2131                   {
2132                      Symbol symbol = declarator.symbol;
2133                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2134
2135                      if(method && method.type == virtualMethod)
2136                      {
2137                         symbol.method = method;
2138                         ProcessMethodType(method);
2139
2140                         if(!symbol.type.thisClass)
2141                         {
2142                            if(method.dataType.thisClass && currentClass &&
2143                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2144                            {
2145                               if(!currentClass.symbol)
2146                                  currentClass.symbol = FindClass(currentClass.fullName);
2147                               symbol.type.thisClass = currentClass.symbol;
2148                            }
2149                            else
2150                            {
2151                               if(!_class.symbol)
2152                                  _class.symbol = FindClass(_class.fullName);
2153                               symbol.type.thisClass = _class.symbol;
2154                            }
2155                         }
2156                         // TESTING THIS HERE:
2157                         DeclareType(symbol.type, true, true);
2158
2159                      }
2160                      else if(classSym)
2161                      {
2162                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2163                            unmangled, classSym.string);
2164                      }
2165                   }
2166
2167                   //declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2168                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2169
2170                   if(nameID)
2171                   {
2172                      FreeSpecifier(nameID._class);
2173                      nameID._class = null;
2174                   }
2175
2176                   if(inCompiler)
2177                   {
2178                      //Type type = declarator.symbol.type;
2179                      External oldExternal = curExternal;
2180
2181                      // *** Commented this out... Any negative impact? Yes: makes double prototypes declarations... Why was it commented out?
2182                      // *** It was commented out for problems such as
2183                      /*
2184                            class VirtualDesktop : Window
2185                            {
2186                               clientSize = Size { };
2187                               Timer timer
2188                               {
2189                                  bool DelayExpired()
2190                                  {
2191                                     clientSize.w;
2192                                     return true;
2193                                  }
2194                               };
2195                            }
2196                      */
2197                      // Commented Out: Good for bet.ec in Poker (Otherwise: obj\bet.c:187: error: `currentBet' undeclared (first use in this function))
2198
2199                      declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2200
2201                      /*
2202                      if(strcmp(declarator.symbol.string, name))
2203                      {
2204                         printf("TOCHECK: Look out for this\n");
2205                         delete declarator.symbol.string;
2206                         declarator.symbol.string = CopyString(name);
2207                      }
2208
2209                      if(!declarator.symbol.parent && globalContext.symbols.root != (BTNode)declarator.symbol)
2210                      {
2211                         printf("TOCHECK: Will this ever be in a list? Yes.\n");
2212                         excludedSymbols->Remove(declarator.symbol);
2213                         globalContext.symbols.Add((BTNode)declarator.symbol);
2214                         if(strstr(declarator.symbol.string), "::")
2215                            globalContext.hasNameSpace = true;
2216
2217                      }
2218                      */
2219
2220                      //curExternal = curExternal.prev;
2221                      //afterExternal = afterExternal->next;
2222
2223                      //ProcessFunction(afterExternal->function);
2224
2225                      //curExternal = afterExternal;
2226                      {
2227                         External externalDecl;
2228                         externalDecl = MkExternalDeclaration(null);
2229                         ast->Insert(oldExternal.prev, externalDecl);
2230
2231                         // Which function does this process?
2232                         if(createdExternal.function)
2233                         {
2234                            ProcessFunction(createdExternal.function);
2235
2236                            //curExternal = oldExternal;
2237
2238                            {
2239                               //Declaration decl = MkDeclaration(members.function.specifiers, MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2240
2241                               Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
2242                                  MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2243
2244                               //externalDecl = MkExternalDeclaration(decl);
2245
2246                               //***** ast->Insert(external.prev, externalDecl);
2247                               //ast->Insert(curExternal.prev, externalDecl);
2248                               externalDecl.declaration = decl;
2249                               if(decl.symbol && !decl.symbol.pointerExternal)
2250                                  decl.symbol.pointerExternal = externalDecl;
2251
2252                               // Trying this out...
2253                               declarator.symbol.pointerExternal = externalDecl;
2254                            }
2255                         }
2256                      }
2257                   }
2258                   else if(declarator)
2259                   {
2260                      curExternal = declarator.symbol.pointerExternal;
2261                      ProcessFunction((FunctionDefinition)members.function);
2262                   }
2263                   curExternal = external;
2264                   curContext = context;
2265
2266                   if(inCompiler)
2267                   {
2268                      FreeClassFunction(members.function);
2269
2270                      // In this pass, turn this into a MemberInitData
2271                      exp = QMkExpId(name);
2272                      members.type = dataMembersInit;
2273                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2274
2275                      delete unmangled;
2276                   }
2277                   break;
2278                }
2279                case dataMembersInit:
2280                {
2281                   if(members.dataMembers && classSym)
2282                   {
2283                      MemberInit member;
2284                      Location oldyyloc = yylloc;
2285                      for(member = members.dataMembers->first; member; member = member.next)
2286                      {
2287                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2288                         if(member.initializer && !member.initializer.isConstant)
2289                            inst.isConstant = false;
2290                      }
2291                      yylloc = oldyyloc;
2292                   }
2293                   break;
2294                }
2295             }
2296          }
2297       }
2298    }
2299 }
2300
2301 static void DeclareType(Type type, bool declarePointers, bool declareParams)
2302 {
2303    // OPTIMIZATIONS: TESTING THIS...
2304    if(inCompiler)
2305    {
2306       if(type.kind == functionType)
2307       {
2308          Type param;
2309          if(declareParams)
2310          {
2311             for(param = type.params.first; param; param = param.next)
2312                DeclareType(param, declarePointers, true);
2313          }
2314          DeclareType(type.returnType, declarePointers, true);
2315       }
2316       else if(type.kind == pointerType && declarePointers)
2317          DeclareType(type.type, declarePointers, false);
2318       else if(type.kind == classType)
2319       {
2320          if(type._class.registered && (type._class.registered.type == structClass || type._class.registered.type == noHeadClass) && !type._class.declaring)
2321             DeclareStruct(type._class.registered.fullName, type._class.registered.type == noHeadClass);
2322       }
2323       else if(type.kind == structType || type.kind == unionType)
2324       {
2325          Type member;
2326          for(member = type.members.first; member; member = member.next)
2327             DeclareType(member, false, false);
2328       }
2329       else if(type.kind == arrayType)
2330          DeclareType(type.arrayType, declarePointers, false);
2331    }
2332 }
2333
2334 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2335 {
2336    ClassTemplateArgument * arg = null;
2337    int id = 0;
2338    ClassTemplateParameter curParam = null;
2339    Class sClass;
2340    for(sClass = _class; sClass; sClass = sClass.base)
2341    {
2342       id = 0;
2343       if(sClass.templateClass) sClass = sClass.templateClass;
2344       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2345       {
2346          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2347          {
2348             for(sClass = sClass.base; sClass; sClass = sClass.base)
2349             {
2350                if(sClass.templateClass) sClass = sClass.templateClass;
2351                id += sClass.templateParams.count;
2352             }
2353             break;
2354          }
2355          id++;
2356       }
2357       if(curParam) break;
2358    }
2359    if(curParam)
2360    {
2361       arg = &_class.templateArgs[id];
2362       if(arg && param.type == type)
2363          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2364    }
2365    return arg;
2366 }
2367
2368 public Context SetupTemplatesContext(Class _class)
2369 {
2370    Context context = PushContext();
2371    context.templateTypesOnly = true;
2372    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2373    {
2374       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2375       for(; param; param = param.next)
2376       {
2377          if(param.type == type && param.identifier)
2378          {
2379             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2380             curContext.templateTypes.Add((BTNode)type);
2381          }
2382       }
2383    }
2384    else if(_class)
2385    {
2386       Class sClass;
2387       for(sClass = _class; sClass; sClass = sClass.base)
2388       {
2389          ClassTemplateParameter p;
2390          for(p = sClass.templateParams.first; p; p = p.next)
2391          {
2392             //OldList * specs = MkList();
2393             //Declarator decl = null;
2394             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2395             if(p.type == type)
2396             {
2397                TemplateParameter param = p.param;
2398                TemplatedType type;
2399                if(!param)
2400                {
2401                   // ADD DATA TYPE HERE...
2402                   p.param = param = TemplateParameter
2403                   {
2404                      identifier = MkIdentifier(p.name), type = p.type,
2405                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2406                   };
2407                }
2408                type = TemplatedType { key = (uintptr)p.name, param = param };
2409                curContext.templateTypes.Add((BTNode)type);
2410             }
2411          }
2412       }
2413    }
2414    return context;
2415 }
2416
2417 public void FinishTemplatesContext(Context context)
2418 {
2419    PopContext(context);
2420    FreeContext(context);
2421    delete context;
2422 }
2423
2424 public void ProcessMethodType(Method method)
2425 {
2426    if(!method.dataType)
2427    {
2428       Context context = SetupTemplatesContext(method._class);
2429
2430       method.dataType = ProcessTypeString(method.dataTypeString, false);
2431
2432       FinishTemplatesContext(context);
2433
2434       if(method.type != virtualMethod && method.dataType)
2435       {
2436          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2437          {
2438             if(!method._class.symbol)
2439                method._class.symbol = FindClass(method._class.fullName);
2440             method.dataType.thisClass = method._class.symbol;
2441          }
2442       }
2443
2444       // Why was this commented out? Working fine without now...
2445
2446       /*
2447       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2448          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2449          */
2450    }
2451
2452    /*
2453    if(type)
2454    {
2455       char * par = strstr(type, "(");
2456       char * classOp = null;
2457       int classOpLen = 0;
2458       if(par)
2459       {
2460          int c;
2461          for(c = par-type-1; c >= 0; c++)
2462          {
2463             if(type[c] == ':' && type[c+1] == ':')
2464             {
2465                classOp = type + c - 1;
2466                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2467                {
2468                   classOp--;
2469                   classOpLen++;
2470                }
2471                break;
2472             }
2473             else if(!isspace(type[c]))
2474                break;
2475          }
2476       }
2477       if(classOp)
2478       {
2479          char temp[1024];
2480          int typeLen = strlen(type);
2481          memcpy(temp, classOp, classOpLen);
2482          temp[classOpLen] = '\0';
2483          if(temp[0])
2484             _class = eSystem_FindClass(module, temp);
2485          else
2486             _class = null;
2487          method.dataTypeString = new char[typeLen - classOpLen + 1];
2488          memcpy(method.dataTypeString, type, classOp - type);
2489          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2490       }
2491       else
2492          method.dataTypeString = type;
2493    }
2494    */
2495 }
2496
2497
2498 public void ProcessPropertyType(Property prop)
2499 {
2500    if(!prop.dataType)
2501    {
2502       Context context = SetupTemplatesContext(prop._class);
2503       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2504       FinishTemplatesContext(context);
2505    }
2506 }
2507
2508 public void DeclareMethod(Method method, const char * name)
2509 {
2510    Symbol symbol = method.symbol;
2511    if(!symbol || (!symbol.pointerExternal && method.type == virtualMethod) || symbol.id > (curExternal ? curExternal.symbol.idCode : -1))
2512    {
2513       //bool imported = false;
2514       bool dllImport = false;
2515
2516       if(!method.dataType)
2517          method.dataType = ProcessTypeString(method.dataTypeString, false);
2518
2519       if(!symbol || symbol._import || method.type == virtualMethod)
2520       {
2521          if(!symbol || method.type == virtualMethod)
2522          {
2523             Symbol classSym;
2524             if(!method._class.symbol)
2525                method._class.symbol = FindClass(method._class.fullName);
2526             classSym = method._class.symbol;
2527             if(!classSym._import)
2528             {
2529                ModuleImport module;
2530
2531                if(method._class.module && method._class.module.name)
2532                   module = FindModule(method._class.module);
2533                else
2534                   module = mainModule;
2535                classSym._import = ClassImport
2536                {
2537                   name = CopyString(method._class.fullName);
2538                   isRemote = method._class.isRemote;
2539                };
2540                module.classes.Add(classSym._import);
2541             }
2542             if(!symbol)
2543             {
2544                symbol = method.symbol = Symbol { };
2545             }
2546             if(!symbol._import)
2547             {
2548                symbol._import = (ClassImport)MethodImport
2549                {
2550                   name = CopyString(method.name);
2551                   isVirtual = method.type == virtualMethod;
2552                };
2553                classSym._import.methods.Add(symbol._import);
2554             }
2555             if(!symbol)
2556             {
2557                // Set the symbol type
2558                /*
2559                if(!type.thisClass)
2560                {
2561                   type.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2562                }
2563                else if(type.thisClass == (void *)-1)
2564                {
2565                   type.thisClass = null;
2566                }
2567                */
2568                // symbol.type = ProcessTypeString(method.dataTypeString, false);
2569                symbol.type = method.dataType;
2570                if(symbol.type) symbol.type.refCount++;
2571             }
2572             /*
2573             if(!method.thisClass || strcmp(method.thisClass, "void"))
2574                symbol.type.params.Insert(null,
2575                   MkClassType(method.thisClass ? method.thisClass : method._class.fullName));
2576             */
2577          }
2578          if(!method.dataType.dllExport)
2579          {
2580             //imported = true;
2581             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2582                dllImport = true;
2583          }
2584       }
2585
2586       /* MOVING THIS UP
2587       if(!method.dataType)
2588          method.dataType = ((Symbol)method.symbol).type;
2589          //ProcessMethodType(method);
2590       */
2591
2592       if(method.type != virtualMethod && method.dataType)
2593          DeclareType(method.dataType, true, true);
2594
2595       if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2596       {
2597          // We need a declaration here :)
2598          Declaration decl;
2599          OldList * specifiers, * declarators;
2600          Declarator d;
2601          Declarator funcDecl;
2602          External external;
2603
2604          specifiers = MkList();
2605          declarators = MkList();
2606
2607          //if(imported)
2608          if(dllImport)
2609             ListAdd(specifiers, MkSpecifier(EXTERN));
2610          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2611             ListAdd(specifiers, MkSpecifier(STATIC));
2612
2613          if(method.type == virtualMethod)
2614          {
2615             ListAdd(specifiers, MkSpecifier(INT));
2616             d = MkDeclaratorIdentifier(MkIdentifier(name));
2617          }
2618          else
2619          {
2620             d = MkDeclaratorIdentifier(MkIdentifier(name));
2621             //if(imported)
2622             if(dllImport)
2623                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2624             {
2625                Context context = SetupTemplatesContext(method._class);
2626                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2627                FinishTemplatesContext(context);
2628             }
2629             funcDecl = GetFuncDecl(d);
2630
2631             if(dllImport)
2632             {
2633                Specifier spec, next;
2634                for(spec = specifiers->first; spec; spec = next)
2635                {
2636                   next = spec.next;
2637                   if(spec.type == extendedSpecifier)
2638                   {
2639                      specifiers->Remove(spec);
2640                      FreeSpecifier(spec);
2641                   }
2642                }
2643             }
2644
2645             // Add this parameter if not a static method
2646             if(method.dataType && !method.dataType.staticMethod)
2647             {
2648                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2649                {
2650                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2651                   TypeName thisParam = MkTypeName(MkListOne(
2652                      MkSpecifierName/*MkClassName*/(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2653                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2654                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2655                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2656
2657                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2658                   {
2659                      TypeName param = funcDecl.function.parameters->first;
2660                      funcDecl.function.parameters->Remove(param);
2661                      FreeTypeName(param);
2662                   }
2663
2664                   if(!funcDecl.function.parameters)
2665                      funcDecl.function.parameters = MkList();
2666                   funcDecl.function.parameters->Insert(null, thisParam);
2667                }
2668             }
2669             // Make sure we don't have empty parameter declarations for static methods...
2670             /*
2671             else if(!funcDecl.function.parameters)
2672             {
2673                funcDecl.function.parameters = MkList();
2674                funcDecl.function.parameters->Insert(null,
2675                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2676             }*/
2677          }
2678          // TESTING THIS:
2679          ProcessDeclarator(d);
2680
2681          ListAdd(declarators, MkInitDeclarator(d, null));
2682
2683          decl = MkDeclaration(specifiers, declarators);
2684
2685          ReplaceThisClassSpecifiers(specifiers, method._class);
2686
2687          // Keep a different symbol for the function definition than the declaration...
2688          if(symbol.pointerExternal)
2689          {
2690             Symbol functionSymbol { };
2691
2692             // Copy symbol
2693             {
2694                *functionSymbol = *symbol;
2695                functionSymbol.string = CopyString(symbol.string);
2696                if(functionSymbol.type)
2697                   functionSymbol.type.refCount++;
2698             }
2699
2700             excludedSymbols->Add(functionSymbol);
2701             symbol.pointerExternal.symbol = functionSymbol;
2702          }
2703          external = MkExternalDeclaration(decl);
2704          if(curExternal)
2705             ast->Insert(curExternal ? curExternal.prev : null, external);
2706          external.symbol = symbol;
2707          symbol.pointerExternal = external;
2708       }
2709       else if(ast)
2710       {
2711          // Move declaration higher...
2712          ast->Move(symbol.pointerExternal, curExternal.prev);
2713       }
2714
2715       symbol.id = curExternal ? curExternal.symbol.idCode : MAXINT;
2716    }
2717 }
2718
2719 char * ReplaceThisClass(Class _class)
2720 {
2721    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2722    {
2723       bool first = true;
2724       int p = 0;
2725       ClassTemplateParameter param;
2726       int lastParam = -1;
2727
2728       char className[1024];
2729       strcpy(className, _class.fullName);
2730       for(param = _class.templateParams.first; param; param = param.next)
2731       {
2732          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2733          {
2734             if(first) strcat(className, "<");
2735             if(!first) strcat(className, ", ");
2736             if(lastParam + 1 != p)
2737             {
2738                strcat(className, param.name);
2739                strcat(className, " = ");
2740             }
2741             strcat(className, param.name);
2742             first = false;
2743             lastParam = p;
2744          }
2745          p++;
2746       }
2747       if(!first)
2748       {
2749          int len = strlen(className);
2750          if(className[len-1] == '>') className[len++] = ' ';
2751          className[len++] = '>';
2752          className[len++] = '\0';
2753       }
2754       return CopyString(className);
2755    }
2756    else
2757       return CopyString(_class.fullName);
2758 }
2759
2760 Type ReplaceThisClassType(Class _class)
2761 {
2762    Type type;
2763    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2764    {
2765       bool first = true;
2766       int p = 0;
2767       ClassTemplateParameter param;
2768       int lastParam = -1;
2769       char className[1024];
2770       strcpy(className, _class.fullName);
2771
2772       for(param = _class.templateParams.first; param; param = param.next)
2773       {
2774          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2775          {
2776             if(first) strcat(className, "<");
2777             if(!first) strcat(className, ", ");
2778             if(lastParam + 1 != p)
2779             {
2780                strcat(className, param.name);
2781                strcat(className, " = ");
2782             }
2783             strcat(className, param.name);
2784             first = false;
2785             lastParam = p;
2786          }
2787          p++;
2788       }
2789       if(!first)
2790       {
2791          int len = strlen(className);
2792          if(className[len-1] == '>') className[len++] = ' ';
2793          className[len++] = '>';
2794          className[len++] = '\0';
2795       }
2796       type = MkClassType(className);
2797       //type = ProcessTypeString(className, false);
2798    }
2799    else
2800    {
2801       type = MkClassType(_class.fullName);
2802       //type = ProcessTypeString(_class.fullName, false);
2803    }
2804    //type.wasThisClass = true;
2805    return type;
2806 }
2807
2808 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2809 {
2810    if(specs != null && _class)
2811    {
2812       Specifier spec;
2813       for(spec = specs.first; spec; spec = spec.next)
2814       {
2815          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2816          {
2817             spec.type = nameSpecifier;
2818             spec.name = ReplaceThisClass(_class);
2819             spec.symbol = FindClass(spec.name); //_class.symbol;
2820          }
2821       }
2822    }
2823 }
2824
2825 // Returns imported or not
2826 bool DeclareFunction(GlobalFunction function, char * name)
2827 {
2828    Symbol symbol = function.symbol;
2829    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2830    {
2831       bool imported = false;
2832       bool dllImport = false;
2833
2834       if(!function.dataType)
2835       {
2836          function.dataType = ProcessTypeString(function.dataTypeString, false);
2837          if(!function.dataType.thisClass)
2838             function.dataType.staticMethod = true;
2839       }
2840
2841       if(inCompiler)
2842       {
2843          if(!symbol)
2844          {
2845             ModuleImport module = FindModule(function.module);
2846             // WARNING: This is not added anywhere...
2847             symbol = function.symbol = Symbol {  };
2848
2849             if(module.name)
2850             {
2851                if(!function.dataType.dllExport)
2852                {
2853                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2854                   module.functions.Add(symbol._import);
2855                }
2856             }
2857             // Set the symbol type
2858             {
2859                symbol.type = ProcessTypeString(function.dataTypeString, false);
2860                if(!symbol.type.thisClass)
2861                   symbol.type.staticMethod = true;
2862             }
2863          }
2864          imported = symbol._import ? true : false;
2865          if(imported && function.module != privateModule && function.module.importType != staticImport)
2866             dllImport = true;
2867       }
2868
2869       DeclareType(function.dataType, true, true);
2870
2871       if(inCompiler)
2872       {
2873          if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2874          {
2875             // We need a declaration here :)
2876             Declaration decl;
2877             OldList * specifiers, * declarators;
2878             Declarator d;
2879             Declarator funcDecl;
2880             External external;
2881
2882             specifiers = MkList();
2883             declarators = MkList();
2884
2885             //if(imported)
2886                ListAdd(specifiers, MkSpecifier(EXTERN));
2887             /*
2888             else
2889                ListAdd(specifiers, MkSpecifier(STATIC));
2890             */
2891
2892             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2893             //if(imported)
2894             if(dllImport)
2895                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2896
2897             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2898             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2899             if(function.module.importType == staticImport)
2900             {
2901                Specifier spec;
2902                for(spec = specifiers->first; spec; spec = spec.next)
2903                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2904                   {
2905                      specifiers->Remove(spec);
2906                      FreeSpecifier(spec);
2907                      break;
2908                   }
2909             }
2910
2911             funcDecl = GetFuncDecl(d);
2912
2913             // Make sure we don't have empty parameter declarations for static methods...
2914             if(funcDecl && !funcDecl.function.parameters)
2915             {
2916                funcDecl.function.parameters = MkList();
2917                funcDecl.function.parameters->Insert(null,
2918                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2919             }
2920
2921             ListAdd(declarators, MkInitDeclarator(d, null));
2922
2923             {
2924                Context oldCtx = curContext;
2925                curContext = globalContext;
2926                decl = MkDeclaration(specifiers, declarators);
2927                curContext = oldCtx;
2928             }
2929
2930             // Keep a different symbol for the function definition than the declaration...
2931             if(symbol.pointerExternal)
2932             {
2933                Symbol functionSymbol { };
2934                // Copy symbol
2935                {
2936                   *functionSymbol = *symbol;
2937                   functionSymbol.string = CopyString(symbol.string);
2938                   if(functionSymbol.type)
2939                      functionSymbol.type.refCount++;
2940                }
2941
2942                excludedSymbols->Add(functionSymbol);
2943
2944                symbol.pointerExternal.symbol = functionSymbol;
2945             }
2946             external = MkExternalDeclaration(decl);
2947             if(curExternal)
2948                ast->Insert(curExternal.prev, external);
2949             external.symbol = symbol;
2950             symbol.pointerExternal = external;
2951          }
2952          else
2953          {
2954             // Move declaration higher...
2955             ast->Move(symbol.pointerExternal, curExternal.prev);
2956          }
2957
2958          if(curExternal)
2959             symbol.id = curExternal.symbol.idCode;
2960       }
2961    }
2962    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2963 }
2964
2965 void DeclareGlobalData(GlobalData data)
2966 {
2967    Symbol symbol = data.symbol;
2968    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2969    {
2970       if(inCompiler)
2971       {
2972          if(!symbol)
2973             symbol = data.symbol = Symbol { };
2974       }
2975       if(!data.dataType)
2976          data.dataType = ProcessTypeString(data.dataTypeString, false);
2977       DeclareType(data.dataType, true, true);
2978       if(inCompiler)
2979       {
2980          if(!symbol.pointerExternal)
2981          {
2982             // We need a declaration here :)
2983             Declaration decl;
2984             OldList * specifiers, * declarators;
2985             Declarator d;
2986             External external;
2987
2988             specifiers = MkList();
2989             declarators = MkList();
2990
2991             ListAdd(specifiers, MkSpecifier(EXTERN));
2992             d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2993             d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2994
2995             ListAdd(declarators, MkInitDeclarator(d, null));
2996
2997             decl = MkDeclaration(specifiers, declarators);
2998             external = MkExternalDeclaration(decl);
2999             if(curExternal)
3000                ast->Insert(curExternal.prev, external);
3001             external.symbol = symbol;
3002             symbol.pointerExternal = external;
3003          }
3004          else
3005          {
3006             // Move declaration higher...
3007             ast->Move(symbol.pointerExternal, curExternal.prev);
3008          }
3009
3010          if(curExternal)
3011             symbol.id = curExternal.symbol.idCode;
3012       }
3013    }
3014 }
3015
3016 class Conversion : struct
3017 {
3018    Conversion prev, next;
3019    Property convert;
3020    bool isGet;
3021    Type resultType;
3022 };
3023
3024 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
3025 {
3026    bool status = true;
3027    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
3028       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
3029    {
3030       Class sourceClass = source.kind == classType ? source._class.registered : null;
3031       Class destClass = dest.kind == classType ? dest._class.registered : null;
3032       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
3033          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
3034       {
3035          Type sourceType = source, destType = dest;
3036          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
3037          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
3038          if(!destType.constant && sourceType.constant)
3039          {
3040             status = false;
3041             if(warn)
3042                Compiler_Warning($"discarding const qualifier\n");
3043          }
3044       }
3045    }
3046    return status;
3047 }
3048
3049 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
3050                        bool isConversionExploration, bool warnConst)
3051 {
3052    if(source && dest)
3053    {
3054       if(warnConst)
3055          CheckConstCompatibility(source, dest, true);
3056       // Property convert;
3057
3058       if(source.kind == templateType && dest.kind != templateType)
3059       {
3060          Type type = ProcessTemplateParameterType(source.templateParameter);
3061          if(type) source = type;
3062       }
3063
3064       if(dest.kind == templateType && source.kind != templateType)
3065       {
3066          Type type = ProcessTemplateParameterType(dest.templateParameter);
3067          if(type) dest = type;
3068       }
3069
3070       if(dest.classObjectType == typedObject && dest.kind != functionType)
3071       {
3072          if(source.classObjectType != anyObject)
3073             return true;
3074          else
3075          {
3076             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
3077             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
3078             {
3079                return true;
3080             }
3081          }
3082       }
3083       else
3084       {
3085          if(source.kind != functionType && source.classObjectType == anyObject)
3086             return true;
3087          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
3088             return true;
3089       }
3090
3091       if((dest.kind == structType && source.kind == structType) ||
3092          (dest.kind == unionType && source.kind == unionType))
3093       {
3094          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
3095              (source.members.first && source.members.first == dest.members.first))
3096             return true;
3097       }
3098
3099       if(dest.kind == ellipsisType && source.kind != voidType)
3100          return true;
3101
3102       if(dest.kind == pointerType && dest.type.kind == voidType &&
3103          ((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))
3104          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
3105
3106          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
3107
3108          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
3109          return true;
3110       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
3111          ((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))
3112          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
3113          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
3114
3115          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
3116          return true;
3117
3118       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
3119       {
3120          if(source._class.registered && source._class.registered.type == unitClass)
3121          {
3122             if(conversions != null)
3123             {
3124                if(source._class.registered == dest._class.registered)
3125                   return true;
3126             }
3127             else
3128             {
3129                Class sourceBase, destBase;
3130                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
3131                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
3132                if(sourceBase == destBase)
3133                   return true;
3134             }
3135          }
3136          // Don't match enum inheriting from other enum if resolving enumeration values
3137          // TESTING: !dest.classObjectType
3138          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
3139             (enumBaseType ||
3140                (!source._class.registered || source._class.registered.type != enumClass) ||
3141                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
3142             return true;
3143          else
3144          {
3145             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
3146             if(enumBaseType &&
3147                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
3148                ((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)
3149             {
3150                if(eClass_IsDerived(dest._class.registered, source._class.registered))
3151                {
3152                   return true;
3153                }
3154             }
3155          }
3156       }
3157
3158       // JUST ADDED THIS...
3159       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
3160          return true;
3161
3162       if(doConversion)
3163       {
3164          // Just added this for Straight conversion of ColorAlpha => Color
3165          if(source.kind == classType)
3166          {
3167             Class _class;
3168             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3169             {
3170                Property convert;
3171                for(convert = _class.conversions.first; convert; convert = convert.next)
3172                {
3173                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3174                   {
3175                      Conversion after = (conversions != null) ? conversions.last : null;
3176
3177                      if(!convert.dataType)
3178                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3179                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
3180                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3181                         MatchTypes(convert.dataType, dest, conversions, null, null,
3182                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
3183                               convert.dataType.kind == classType, false, true, warnConst))
3184                      {
3185                         if(!conversions && !convert.Get)
3186                            return true;
3187                         else if(conversions != null)
3188                         {
3189                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3190                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3191                               (dest.kind != classType || dest._class.registered != _class.base))
3192                               return true;
3193                            else
3194                            {
3195                               Conversion conv { convert = convert, isGet = true };
3196                               // conversions.Add(conv);
3197                               conversions.Insert(after, conv);
3198
3199                               return true;
3200                            }
3201                         }
3202                      }
3203                   }
3204                }
3205             }
3206          }
3207
3208          // MOVING THIS??
3209
3210          if(dest.kind == classType)
3211          {
3212             Class _class;
3213             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3214             {
3215                Property convert;
3216                for(convert = _class.conversions.first; convert; convert = convert.next)
3217                {
3218                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3219                   {
3220                      Type constType = null;
3221                      bool success = false;
3222                      // Conversion after = (conversions != null) ? conversions.last : null;
3223
3224                      if(!convert.dataType)
3225                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3226
3227                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3228                      {
3229                         Type ptrType { };
3230                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3231                         CopyTypeInto(ptrType, convert.dataType.type);
3232                         ptrType.constant = true;
3233                      }
3234
3235                      // Just added this equality check to prevent recursion.... Make it safer?
3236                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3237                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3238                      {
3239                         if(!conversions && !convert.Set)
3240                            success = true;
3241                         else if(conversions != null)
3242                         {
3243                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3244                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3245                               (source.kind != classType || source._class.registered != _class.base))
3246                               success = true;
3247                            else
3248                            {
3249                               // *** Testing this! ***
3250                               Conversion conv { convert = convert };
3251                               conversions.Add(conv);
3252                               //conversions.Insert(after, conv);
3253                               success = true;
3254                            }
3255                         }
3256                      }
3257                      if(constType)
3258                         FreeType(constType);
3259                      if(success)
3260                         return true;
3261                   }
3262                }
3263             }
3264             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3265             {
3266                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3267                   (source.kind != classType || source._class.registered.type != structClass))
3268                   return true;
3269             }*/
3270
3271             // TESTING THIS... IS THIS OK??
3272             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3273             {
3274                if(!dest._class.registered.dataType)
3275                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3276                // Only support this for classes...
3277                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3278                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3279                {
3280                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3281                   {
3282                      return true;
3283                   }
3284                }
3285             }
3286          }
3287
3288          // Moved this lower
3289          if(source.kind == classType)
3290          {
3291             Class _class;
3292             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3293             {
3294                Property convert;
3295                for(convert = _class.conversions.first; convert; convert = convert.next)
3296                {
3297                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3298                   {
3299                      Conversion after = (conversions != null) ? conversions.last : null;
3300
3301                      if(!convert.dataType)
3302                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3303                      if(convert.dataType != source &&
3304                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3305                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3306                      {
3307                         if(!conversions && !convert.Get)
3308                            return true;
3309                         else if(conversions != null)
3310                         {
3311                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3312                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3313                               (dest.kind != classType || dest._class.registered != _class.base))
3314                               return true;
3315                            else
3316                            {
3317                               Conversion conv { convert = convert, isGet = true };
3318
3319                               // conversions.Add(conv);
3320                               conversions.Insert(after, conv);
3321                               return true;
3322                            }
3323                         }
3324                      }
3325                   }
3326                }
3327             }
3328
3329             // TESTING THIS... IS THIS OK??
3330             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3331             {
3332                if(!source._class.registered.dataType)
3333                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3334                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3335                {
3336                   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))
3337                      return true;
3338                   // For bool to be accepted by byte, short, etc.
3339                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3340                      return true;
3341                }
3342             }
3343          }
3344       }
3345
3346       if(source.kind == classType || source.kind == subClassType)
3347          ;
3348       else if(dest.kind == source.kind &&
3349          (dest.kind != structType && dest.kind != unionType &&
3350           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3351           return true;
3352       // RECENTLY ADDED THESE
3353       else if(dest.kind == doubleType && source.kind == floatType)
3354          return true;
3355       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3356          return true;
3357       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3358          return true;
3359       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3360          return true;
3361       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3362          return true;
3363       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3364          return true;
3365       else if(source.kind == enumType &&
3366          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3367           return true;
3368       else if(dest.kind == enumType && !isConversionExploration &&
3369          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3370           return true;
3371       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3372               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3373       {
3374          Type paramSource, paramDest;
3375
3376          if(dest.kind == methodType)
3377             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3378          if(source.kind == methodType)
3379             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3380
3381          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3382          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3383          if(dest.kind == methodType)
3384             dest = dest.method.dataType;
3385          if(source.kind == methodType)
3386             source = source.method.dataType;
3387
3388          paramSource = source.params.first;
3389          if(paramSource && paramSource.kind == voidType) paramSource = null;
3390          paramDest = dest.params.first;
3391          if(paramDest && paramDest.kind == voidType) paramDest = null;
3392
3393
3394          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3395             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3396          {
3397             // Source thisClass must be derived from destination thisClass
3398             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3399                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3400             {
3401                if(paramDest && paramDest.kind == classType)
3402                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3403                else
3404                   Compiler_Error($"method class should not take an object\n");
3405                return false;
3406             }
3407             paramDest = paramDest.next;
3408          }
3409          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3410          {
3411             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3412             {
3413                if(dest.thisClass)
3414                {
3415                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3416                   {
3417                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3418                      return false;
3419                   }
3420                }
3421                else
3422                {
3423                   // THIS WAS BACKWARDS:
3424                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3425                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3426                   {
3427                      if(owningClassDest)
3428                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3429                      else
3430                         Compiler_Error($"overriding class expected to be derived from method class\n");
3431                      return false;
3432                   }
3433                }
3434                paramSource = paramSource.next;
3435             }
3436             else
3437             {
3438                if(dest.thisClass)
3439                {
3440                   // Source thisClass must be derived from destination thisClass
3441                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3442                   {
3443                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3444                      return false;
3445                   }
3446                }
3447                else
3448                {
3449                   // THIS WAS BACKWARDS TOO??
3450                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3451                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3452                   {
3453                      //if(owningClass)
3454                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3455                      //else
3456                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3457                      return false;
3458                   }
3459                }
3460             }
3461          }
3462
3463
3464          // Source return type must be derived from destination return type
3465          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3466          {
3467             Compiler_Warning($"incompatible return type for function\n");
3468             return false;
3469          }
3470          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3471          else
3472             CheckConstCompatibility(dest.returnType, source.returnType, true);
3473
3474          // Check parameters
3475
3476          for(; paramDest; paramDest = paramDest.next)
3477          {
3478             if(!paramSource)
3479             {
3480                //Compiler_Warning($"not enough parameters\n");
3481                Compiler_Error($"not enough parameters\n");
3482                return false;
3483             }
3484             {
3485                Type paramDestType = paramDest;
3486                Type paramSourceType = paramSource;
3487                Type type = paramDestType;
3488
3489                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3490                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3491                   paramSource.kind != templateType)
3492                {
3493                   int id = 0;
3494                   ClassTemplateParameter curParam = null;
3495                   Class sClass;
3496                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3497                   {
3498                      id = 0;
3499                      if(sClass.templateClass) sClass = sClass.templateClass;
3500                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3501                      {
3502                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3503                         {
3504                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3505                            {
3506                               if(sClass.templateClass) sClass = sClass.templateClass;
3507                               id += sClass.templateParams.count;
3508                            }
3509                            break;
3510                         }
3511                         id++;
3512                      }
3513                      if(curParam) break;
3514                   }
3515
3516                   if(curParam)
3517                   {
3518                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3519                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3520                   }
3521                }
3522
3523                // paramDest must be derived from paramSource
3524                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3525                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3526                {
3527                   char type[1024];
3528                   type[0] = 0;
3529                   PrintType(paramDest, type, false, true);
3530                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3531
3532                   if(paramDestType != paramDest)
3533                      FreeType(paramDestType);
3534                   return false;
3535                }
3536                if(paramDestType != paramDest)
3537                   FreeType(paramDestType);
3538             }
3539
3540             paramSource = paramSource.next;
3541          }
3542          if(paramSource)
3543          {
3544             Compiler_Error($"too many parameters\n");
3545             return false;
3546          }
3547          return true;
3548       }
3549       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3550       {
3551          return true;
3552       }
3553       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3554          (source.kind == arrayType || source.kind == pointerType))
3555       {
3556          // Pointers to pointer is incompatible with non normal/nohead classes
3557          if(!(dest.type && dest.type.kind == pointerType && source.type.kind == classType && source.type._class &&
3558             source.type._class.registered && (source.type._class.registered.type != normalClass && source.type._class.registered.type != noHeadClass) && !source.type.byReference))
3559          {
3560             ComputeTypeSize(source.type);
3561             ComputeTypeSize(dest.type);
3562             if(source.type.size == dest.type.size && MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3563                return true;
3564          }
3565       }
3566    }
3567    return false;
3568 }
3569
3570 static void FreeConvert(Conversion convert)
3571 {
3572    if(convert.resultType)
3573       FreeType(convert.resultType);
3574 }
3575
3576 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3577                               char * string, OldList conversions)
3578 {
3579    BTNamedLink link;
3580
3581    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3582    {
3583       Class _class = link.data;
3584       if(_class.type == enumClass)
3585       {
3586          OldList converts { };
3587          Type type { };
3588          type.kind = classType;
3589
3590          if(!_class.symbol)
3591             _class.symbol = FindClass(_class.fullName);
3592          type._class = _class.symbol;
3593
3594          if(MatchTypes(type, dest, &converts, null, null, dest.kind != classType || !dest._class || strcmp(dest._class.string, "bool"),
3595                false, false, false, false))
3596          {
3597             NamedLink64 value;
3598             Class enumClass = eSystem_FindClass(privateModule, "enum");
3599             if(enumClass)
3600             {
3601                Class baseClass;
3602                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3603                {
3604                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3605                   for(value = e.values.first; value; value = value.next)
3606                   {
3607                      if(!strcmp(value.name, string))
3608                         break;
3609                   }
3610                   if(value)
3611                   {
3612                      FreeType(sourceExp.expType);
3613
3614                      sourceExp.isConstant = true;
3615                      sourceExp.expType = MkClassType(baseClass.fullName);
3616                      if(inCompiler || inPreCompiler || inDebugger)
3617                      {
3618                         char constant[256];
3619                         FreeExpContents(sourceExp);
3620
3621                         sourceExp.type = constantExp;
3622                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3623                            sprintf(constant, FORMAT64D, value.data);
3624                         else
3625                            sprintf(constant, FORMAT64HEXLL, value.data);
3626                         sourceExp.constant = CopyString(constant);
3627                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3628                      }
3629
3630                      while(converts.first)
3631                      {
3632                         Conversion convert = converts.first;
3633                         converts.Remove(convert);
3634                         conversions.Add(convert);
3635                      }
3636                      delete type;
3637                      return true;
3638                   }
3639                }
3640             }
3641          }
3642          if(converts.first)
3643             converts.Free(FreeConvert);
3644          delete type;
3645       }
3646    }
3647    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3648       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3649          return true;
3650    return false;
3651 }
3652
3653 public bool ModuleVisibility(Module searchIn, Module searchFor)
3654 {
3655    SubModule subModule;
3656
3657    if(searchFor == searchIn)
3658       return true;
3659
3660    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3661    {
3662       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3663       {
3664          if(ModuleVisibility(subModule.module, searchFor))
3665             return true;
3666       }
3667    }
3668    return false;
3669 }
3670
3671 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3672 {
3673    Module module;
3674
3675    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3676       return true;
3677    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3678       return true;
3679    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3680       return true;
3681
3682    for(module = mainModule.application.allModules.first; module; module = module.next)
3683    {
3684       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3685          return true;
3686    }
3687    return false;
3688 }
3689
3690 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3691 {
3692    Type source;
3693    Type realDest = dest;
3694    Type backupSourceExpType = null;
3695    Expression computedExp = sourceExp;
3696    dest.refCount++;
3697
3698    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3699       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3700    {
3701       computedExp = CopyExpression(sourceExp);        // Keep the original expression, but compute for checking enum ranges
3702       ComputeExpression(computedExp /*sourceExp*/);
3703    }
3704
3705    source = sourceExp.expType;
3706
3707    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3708    {
3709       if(computedExp != sourceExp)
3710       {
3711          FreeExpression(computedExp);
3712          computedExp = sourceExp;
3713       }
3714       FreeType(dest);
3715       return true;
3716    }
3717
3718    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3719    {
3720        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3721        {
3722           Class sourceBase, destBase;
3723           for(sourceBase = source._class.registered;
3724               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3725               sourceBase = sourceBase.base);
3726           for(destBase = dest._class.registered;
3727               destBase && destBase.base && destBase.base.type != systemClass;
3728               destBase = destBase.base);
3729           //if(source._class.registered == dest._class.registered)
3730           if(sourceBase == destBase)
3731           {
3732             if(computedExp != sourceExp)
3733             {
3734                FreeExpression(computedExp);
3735                computedExp = sourceExp;
3736             }
3737             FreeType(dest);
3738             return true;
3739          }
3740       }
3741    }
3742
3743    if(source)
3744    {
3745       OldList * specs;
3746       bool flag = false;
3747       int64 value = MAXINT;
3748
3749       source.refCount++;
3750
3751       if(computedExp.type == constantExp)
3752       {
3753          if(source.isSigned)
3754             value = strtoll(computedExp.constant, null, 0);
3755          else
3756             value = strtoull(computedExp.constant, null, 0);
3757       }
3758       else if(computedExp.type == opExp && sourceExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3759       {
3760          if(source.isSigned)
3761             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3762          else
3763             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3764       }
3765       if(computedExp != sourceExp)
3766       {
3767          FreeExpression(computedExp);
3768          computedExp = sourceExp;
3769       }
3770
3771       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3772          !strcmp(source._class.registered.fullName, "ecere::com::unichar"))
3773       {
3774          FreeType(source);
3775          source = Type { kind = intType, isSigned = false, refCount = 1 };
3776       }
3777
3778       if(dest.kind == classType)
3779       {
3780          Class _class = dest._class ? dest._class.registered : null;
3781
3782          if(_class && _class.type == unitClass)
3783          {
3784             if(source.kind != classType)
3785             {
3786                Type tempType { };
3787                Type tempDest, tempSource;
3788
3789                for(; _class.base.type != systemClass; _class = _class.base);
3790                tempSource = dest;
3791                tempDest = tempType;
3792
3793                tempType.kind = classType;
3794                if(!_class.symbol)
3795                   _class.symbol = FindClass(_class.fullName);
3796
3797                tempType._class = _class.symbol;
3798                tempType.truth = dest.truth;
3799                if(tempType._class)
3800                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3801
3802                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3803                backupSourceExpType = sourceExp.expType;
3804                sourceExp.expType = dest; dest.refCount++;
3805                //sourceExp.expType = MkClassType(_class.fullName);
3806                flag = true;
3807
3808                delete tempType;
3809             }
3810          }
3811
3812
3813          // Why wasn't there something like this?
3814          if(_class && _class.type == bitClass && source.kind != classType)
3815          {
3816             if(!dest._class.registered.dataType)
3817                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3818             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3819             {
3820                FreeType(source);
3821                FreeType(sourceExp.expType);
3822                source = sourceExp.expType = MkClassType(dest._class.string);
3823                source.refCount++;
3824
3825                //source.kind = classType;
3826                //source._class = dest._class;
3827             }
3828          }
3829
3830          // Adding two enumerations
3831          /*
3832          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3833          {
3834             if(!source._class.registered.dataType)
3835                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3836             if(!dest._class.registered.dataType)
3837                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3838
3839             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3840             {
3841                FreeType(source);
3842                source = sourceExp.expType = MkClassType(dest._class.string);
3843                source.refCount++;
3844
3845                //source.kind = classType;
3846                //source._class = dest._class;
3847             }
3848          }*/
3849
3850          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3851          {
3852             OldList * specs = MkList();
3853             Declarator decl;
3854             char string[1024];
3855
3856             ReadString(string, sourceExp.string);
3857             decl = SpecDeclFromString(string, specs, null);
3858
3859             FreeExpContents(sourceExp);
3860             FreeType(sourceExp.expType);
3861
3862             sourceExp.type = classExp;
3863             sourceExp._classExp.specifiers = specs;
3864             sourceExp._classExp.decl = decl;
3865             sourceExp.expType = dest;
3866             dest.refCount++;
3867
3868             FreeType(source);
3869             FreeType(dest);
3870             if(backupSourceExpType) FreeType(backupSourceExpType);
3871             return true;
3872          }
3873       }
3874       else if(source.kind == classType)
3875       {
3876          Class _class = source._class ? source._class.registered : null;
3877
3878          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || /*_class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3879          {
3880             /*
3881             if(dest.kind != classType)
3882             {
3883                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3884                if(!source._class.registered.dataType)
3885                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3886
3887                FreeType(dest);
3888                dest = MkClassType(source._class.string);
3889                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3890                //   dest = MkClassType(source._class.string);
3891             }
3892             */
3893
3894             if(dest.kind != classType)
3895             {
3896                Type tempType { };
3897                Type tempDest, tempSource;
3898
3899                if(!source._class.registered.dataType)
3900                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3901
3902                for(; _class.base.type != systemClass; _class = _class.base);
3903                tempDest = source;
3904                tempSource = tempType;
3905                tempType.kind = classType;
3906                tempType._class = FindClass(_class.fullName);
3907                tempType.truth = source.truth;
3908                tempType.classObjectType = source.classObjectType;
3909
3910                if(tempType._class)
3911                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3912
3913                // PUT THIS BACK TESTING UNITS?
3914                if(conversions && conversions.last)
3915                {
3916                   ((Conversion)(conversions.last)).resultType = dest;
3917                   dest.refCount++;
3918                }
3919
3920                FreeType(sourceExp.expType);
3921                sourceExp.expType = MkClassType(_class.fullName);
3922                sourceExp.expType.truth = source.truth;
3923                sourceExp.expType.classObjectType = source.classObjectType;
3924
3925                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3926
3927                if(!sourceExp.destType)
3928                {
3929                   FreeType(sourceExp.destType);
3930                   sourceExp.destType = sourceExp.expType;
3931                   if(sourceExp.expType)
3932                      sourceExp.expType.refCount++;
3933                }
3934                //flag = true;
3935                //source = _class.dataType;
3936
3937
3938                // TOCHECK: TESTING THIS NEW CODE
3939                if(!_class.dataType)
3940                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3941                FreeType(dest);
3942                dest = MkClassType(source._class.string);
3943                dest.truth = source.truth;
3944                dest.classObjectType = source.classObjectType;
3945
3946                FreeType(source);
3947                source = _class.dataType;
3948                source.refCount++;
3949
3950                delete tempType;
3951             }
3952          }
3953       }
3954
3955       if(!flag)
3956       {
3957          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3958          {
3959             FreeType(source);
3960             FreeType(dest);
3961             return true;
3962          }
3963       }
3964
3965       // Implicit Casts
3966       /*
3967       if(source.kind == classType)
3968       {
3969          Class _class = source._class.registered;
3970          if(_class.type == unitClass)
3971          {
3972             if(!_class.dataType)
3973                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3974             source = _class.dataType;
3975          }
3976       }*/
3977
3978       if(dest.kind == classType)
3979       {
3980          Class _class = dest._class ? dest._class.registered : null;
3981          bool fittingValue = false;
3982          if(_class && _class.type == enumClass)
3983          {
3984             Class enumClass = eSystem_FindClass(privateModule, "enum");
3985             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3986             if(c && value >= 0 && value <= c.largest)
3987                fittingValue = true;
3988          }
3989
3990          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3991             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3992          {
3993             if(_class.type == normalClass || _class.type == noHeadClass)
3994             {
3995                Expression newExp { };
3996                *newExp = *sourceExp;
3997                if(sourceExp.destType) sourceExp.destType.refCount++;
3998                if(sourceExp.expType)  sourceExp.expType.refCount++;
3999                sourceExp.type = castExp;
4000                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
4001                sourceExp.cast.exp = newExp;
4002                FreeType(sourceExp.expType);
4003                sourceExp.expType = null;
4004                ProcessExpressionType(sourceExp);
4005
4006                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
4007                if(!inCompiler)
4008                {
4009                   FreeType(sourceExp.expType);
4010                   sourceExp.expType = dest;
4011                }
4012
4013                FreeType(source);
4014                if(inCompiler) FreeType(dest);
4015
4016                if(backupSourceExpType) FreeType(backupSourceExpType);
4017                return true;
4018             }
4019
4020             if(!_class.dataType)
4021                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4022             FreeType(dest);
4023             dest = _class.dataType;
4024             dest.refCount++;
4025          }
4026
4027          // Accept lower precision types for units, since we want to keep the unit type
4028          if(dest.kind == doubleType &&
4029             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
4030              source.kind == charType || source.kind == _BoolType))
4031          {
4032             specs = MkListOne(MkSpecifier(DOUBLE));
4033          }
4034          else if(dest.kind == floatType &&
4035             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
4036             source.kind == _BoolType || source.kind == doubleType))
4037          {
4038             specs = MkListOne(MkSpecifier(FLOAT));
4039          }
4040          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
4041             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
4042          {
4043             specs = MkList();
4044             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4045             ListAdd(specs, MkSpecifier(INT64));
4046          }
4047          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
4048             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
4049          {
4050             specs = MkList();
4051             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4052             ListAdd(specs, MkSpecifier(INT));
4053          }
4054          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
4055             source.kind == floatType || source.kind == doubleType))
4056          {
4057             specs = MkList();
4058             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4059             ListAdd(specs, MkSpecifier(SHORT));
4060          }
4061          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
4062             source.kind == floatType || source.kind == doubleType))
4063          {
4064             specs = MkList();
4065             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4066             ListAdd(specs, MkSpecifier(CHAR));
4067          }
4068          else
4069          {
4070             FreeType(source);
4071             FreeType(dest);
4072             if(backupSourceExpType)
4073             {
4074                // Failed to convert: revert previous exp type
4075                if(sourceExp.expType) FreeType(sourceExp.expType);
4076                sourceExp.expType = backupSourceExpType;
4077             }
4078             return false;
4079          }
4080       }
4081       else if(dest.kind == doubleType &&
4082          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
4083           source.kind == _BoolType || source.kind == charType))
4084       {
4085          specs = MkListOne(MkSpecifier(DOUBLE));
4086       }
4087       else if(dest.kind == floatType &&
4088          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
4089       {
4090          specs = MkListOne(MkSpecifier(FLOAT));
4091       }
4092       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
4093          (value == 1 || value == 0))
4094       {
4095          specs = MkList();
4096          ListAdd(specs, MkSpecifier(BOOL));
4097       }
4098       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
4099          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
4100       {
4101          specs = MkList();
4102          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4103          ListAdd(specs, MkSpecifier(CHAR));
4104       }
4105       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
4106          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
4107       {
4108          specs = MkList();
4109          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4110          ListAdd(specs, MkSpecifier(SHORT));
4111       }
4112       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
4113       {
4114          specs = MkList();
4115          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4116          ListAdd(specs, MkSpecifier(INT));
4117       }
4118       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
4119       {
4120          specs = MkList();
4121          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
4122          ListAdd(specs, MkSpecifier(INT64));
4123       }
4124       else if(dest.kind == enumType &&
4125          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
4126       {
4127          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
4128       }
4129       else
4130       {
4131          FreeType(source);
4132          FreeType(dest);
4133          if(backupSourceExpType)
4134          {
4135             // Failed to convert: revert previous exp type
4136             if(sourceExp.expType) FreeType(sourceExp.expType);
4137             sourceExp.expType = backupSourceExpType;
4138          }
4139          return false;
4140       }
4141
4142       if(!flag && !sourceExp.opDestType)
4143       {
4144          Expression newExp { };
4145          *newExp = *sourceExp;
4146          newExp.prev = null;
4147          newExp.next = null;
4148          if(sourceExp.destType) sourceExp.destType.refCount++;
4149          if(sourceExp.expType)  sourceExp.expType.refCount++;
4150
4151          sourceExp.type = castExp;
4152          if(realDest.kind == classType)
4153          {
4154             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
4155             FreeList(specs, FreeSpecifier);
4156          }
4157          else
4158             sourceExp.cast.typeName = MkTypeName(specs, null);
4159          if(newExp.type == opExp)
4160          {
4161             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
4162          }
4163          else
4164             sourceExp.cast.exp = newExp;
4165
4166          FreeType(sourceExp.expType);
4167          sourceExp.expType = null;
4168          ProcessExpressionType(sourceExp);
4169       }
4170       else
4171          FreeList(specs, FreeSpecifier);
4172
4173       FreeType(dest);
4174       FreeType(source);
4175       if(backupSourceExpType) FreeType(backupSourceExpType);
4176
4177       return true;
4178    }
4179    else
4180    {
4181       if(computedExp != sourceExp)
4182       {
4183          FreeExpression(computedExp);
4184          computedExp = sourceExp;
4185       }
4186
4187       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4188       if(sourceExp.type == identifierExp)
4189       {
4190          Identifier id = sourceExp.identifier;
4191          if(dest.kind == classType)
4192          {
4193             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4194             {
4195                Class _class = dest._class.registered;
4196                Class enumClass = eSystem_FindClass(privateModule, "enum");
4197                if(enumClass)
4198                {
4199                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4200                   {
4201                      NamedLink64 value;
4202                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4203                      for(value = e.values.first; value; value = value.next)
4204                      {
4205                         if(!strcmp(value.name, id.string))
4206                            break;
4207                      }
4208                      if(value)
4209                      {
4210                         FreeType(sourceExp.expType);
4211
4212                         sourceExp.isConstant = true;
4213                         sourceExp.expType = MkClassType(_class.fullName);
4214                         if(inCompiler || inPreCompiler || inDebugger)
4215                         {
4216                            FreeExpContents(sourceExp);
4217
4218                            sourceExp.type = constantExp;
4219                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4220                               sourceExp.constant = PrintInt64(value.data);
4221                            else
4222                               sourceExp.constant = PrintUInt64(value.data);
4223                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4224                         }
4225                         FreeType(dest);
4226                         return true;
4227                      }
4228                   }
4229                }
4230             }
4231          }
4232
4233          // Loop through all enum classes
4234          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4235          {
4236             FreeType(dest);
4237             return true;
4238          }
4239       }
4240       FreeType(dest);
4241    }
4242    return false;
4243 }
4244
4245 #define TERTIARY(o, name, m, t, p) \
4246    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4247    {                                                              \
4248       exp.type = constantExp;                                    \
4249       exp.string = p(op1.m ? op2.m : op3.m);                     \
4250       if(!exp.expType) \
4251          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4252       return true;                                                \
4253    }
4254
4255 #define BINARY(o, name, m, t, p) \
4256    static bool name(Expression exp, Operand op1, Operand op2)   \
4257    {                                                              \
4258       t value2 = op2.m;                                           \
4259       exp.type = constantExp;                                    \
4260       exp.string = p((t)(op1.m o value2));                     \
4261       if(!exp.expType) \
4262          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4263       return true;                                                \
4264    }
4265
4266 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4267    static bool name(Expression exp, Operand op1, Operand op2)   \
4268    {                                                              \
4269       t value2 = op2.m;                                           \
4270       exp.type = constantExp;                                    \
4271       exp.string = p(value2 ? (op1.m o value2) : 0);             \
4272       if(!exp.expType) \
4273          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4274       return true;                                                \
4275    }
4276
4277 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4278    static bool name(Expression exp, Operand op1, Operand op2)   \
4279    {                                                              \
4280       t value2 = op2.m;                                           \
4281       exp.type = constantExp;                                    \
4282       exp.string = p(op1.m o value2);             \
4283       if(!exp.expType) \
4284          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4285       return true;                                                \
4286    }
4287
4288 #define UNARY(o, name, m, t, p) \
4289    static bool name(Expression exp, Operand op1)                \
4290    {                                                              \
4291       exp.type = constantExp;                                    \
4292       exp.string = p((t)(o op1.m));                                   \
4293       if(!exp.expType) \
4294          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4295       return true;                                                \
4296    }
4297
4298 #define OPERATOR_ALL(macro, o, name) \
4299    macro(o, Int##name, i, int, PrintInt) \
4300    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4301    macro(o, Int64##name, i64, int64, PrintInt64) \
4302    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4303    macro(o, Short##name, s, short, PrintShort) \
4304    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4305    macro(o, Char##name, c, char, PrintChar) \
4306    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4307    macro(o, Float##name, f, float, PrintFloat) \
4308    macro(o, Double##name, d, double, PrintDouble)
4309
4310 #define OPERATOR_INTTYPES(macro, o, name) \
4311    macro(o, Int##name, i, int, PrintInt) \
4312    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4313    macro(o, Int64##name, i64, int64, PrintInt64) \
4314    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4315    macro(o, Short##name, s, short, PrintShort) \
4316    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4317    macro(o, Char##name, c, char, PrintChar) \
4318    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4319
4320 #define OPERATOR_REALTYPES(macro, o, name) \
4321    macro(o, Float##name, f, float, PrintFloat) \
4322    macro(o, Double##name, d, double, PrintDouble)
4323
4324 // binary arithmetic
4325 OPERATOR_ALL(BINARY, +, Add)
4326 OPERATOR_ALL(BINARY, -, Sub)
4327 OPERATOR_ALL(BINARY, *, Mul)
4328 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4329 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4330 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4331
4332 // unary arithmetic
4333 OPERATOR_ALL(UNARY, -, Neg)
4334
4335 // unary arithmetic increment and decrement
4336 OPERATOR_ALL(UNARY, ++, Inc)
4337 OPERATOR_ALL(UNARY, --, Dec)
4338
4339 // binary arithmetic assignment
4340 OPERATOR_ALL(BINARY, =, Asign)
4341 OPERATOR_ALL(BINARY, +=, AddAsign)
4342 OPERATOR_ALL(BINARY, -=, SubAsign)
4343 OPERATOR_ALL(BINARY, *=, MulAsign)
4344 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4345 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4346 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4347
4348 // binary bitwise
4349 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4350 OPERATOR_INTTYPES(BINARY, |, BitOr)
4351 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4352 OPERATOR_INTTYPES(BINARY, <<, LShift)
4353 OPERATOR_INTTYPES(BINARY, >>, RShift)
4354
4355 // unary bitwise
4356 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4357
4358 // binary bitwise assignment
4359 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4360 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4361 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4362 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4363 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4364
4365 // unary logical negation
4366 OPERATOR_INTTYPES(UNARY, !, Not)
4367
4368 // binary logical equality
4369 OPERATOR_ALL(BINARY, ==, Equ)
4370 OPERATOR_ALL(BINARY, !=, Nqu)
4371
4372 // binary logical
4373 OPERATOR_ALL(BINARY, &&, And)
4374 OPERATOR_ALL(BINARY, ||, Or)
4375
4376 // binary logical relational
4377 OPERATOR_ALL(BINARY, >, Grt)
4378 OPERATOR_ALL(BINARY, <, Sma)
4379 OPERATOR_ALL(BINARY, >=, GrtEqu)
4380 OPERATOR_ALL(BINARY, <=, SmaEqu)
4381
4382 // tertiary condition operator
4383 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4384
4385 //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
4386 #define OPERATOR_TABLE_ALL(name, type) \
4387     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4388                           type##Neg, \
4389                           type##Inc, type##Dec, \
4390                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4391                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4392                           type##BitNot, \
4393                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4394                           type##Not, \
4395                           type##Equ, type##Nqu, \
4396                           type##And, type##Or, \
4397                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4398                         }; \
4399
4400 #define OPERATOR_TABLE_INTTYPES(name, type) \
4401     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4402                           type##Neg, \
4403                           type##Inc, type##Dec, \
4404                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4405                           null, null, null, null, null, \
4406                           null, \
4407                           null, null, null, null, null, \
4408                           null, \
4409                           type##Equ, type##Nqu, \
4410                           type##And, type##Or, \
4411                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4412                         }; \
4413
4414 OPERATOR_TABLE_ALL(int, Int)
4415 OPERATOR_TABLE_ALL(uint, UInt)
4416 OPERATOR_TABLE_ALL(int64, Int64)
4417 OPERATOR_TABLE_ALL(uint64, UInt64)
4418 OPERATOR_TABLE_ALL(short, Short)
4419 OPERATOR_TABLE_ALL(ushort, UShort)
4420 OPERATOR_TABLE_INTTYPES(float, Float)
4421 OPERATOR_TABLE_INTTYPES(double, Double)
4422 OPERATOR_TABLE_ALL(char, Char)
4423 OPERATOR_TABLE_ALL(uchar, UChar)
4424
4425 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4426 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4427 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4428 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4429 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4430 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4431 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4432 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4433
4434 public void ReadString(char * output,  char * string)
4435 {
4436    int len = strlen(string);
4437    int c,d = 0;
4438    bool quoted = false, escaped = false;
4439    for(c = 0; c<len; c++)
4440    {
4441       char ch = string[c];
4442       if(escaped)
4443       {
4444          switch(ch)
4445          {
4446             case 'n': output[d] = '\n'; break;
4447             case 't': output[d] = '\t'; break;
4448             case 'a': output[d] = '\a'; break;
4449             case 'b': output[d] = '\b'; break;
4450             case 'f': output[d] = '\f'; break;
4451             case 'r': output[d] = '\r'; break;
4452             case 'v': output[d] = '\v'; break;
4453             case '\\': output[d] = '\\'; break;
4454             case '\"': output[d] = '\"'; break;
4455             case '\'': output[d] = '\''; break;
4456             default: output[d] = ch;
4457          }
4458          d++;
4459          escaped = false;
4460       }
4461       else
4462       {
4463          if(ch == '\"')
4464             quoted ^= true;
4465          else if(quoted)
4466          {
4467             if(ch == '\\')
4468                escaped = true;
4469             else
4470                output[d++] = ch;
4471          }
4472       }
4473    }
4474    output[d] = '\0';
4475 }
4476
4477 // String Unescape Copy
4478
4479 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4480 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4481 public int UnescapeString(char * d, char * s, int len)
4482 {
4483    int j = 0, k = 0;
4484    char ch;
4485    while(j < len && (ch = s[j]))
4486    {
4487       switch(ch)
4488       {
4489          case '\\':
4490             switch((ch = s[++j]))
4491             {
4492                case 'n': d[k] = '\n'; break;
4493                case 't': d[k] = '\t'; break;
4494                case 'a': d[k] = '\a'; break;
4495                case 'b': d[k] = '\b'; break;
4496                case 'f': d[k] = '\f'; break;
4497                case 'r': d[k] = '\r'; break;
4498                case 'v': d[k] = '\v'; break;
4499                case '\\': d[k] = '\\'; break;
4500                case '\"': d[k] = '\"'; break;
4501                case '\'': d[k] = '\''; break;
4502                default: d[k] = '\\'; d[k] = ch;
4503             }
4504             break;
4505          default:
4506             d[k] = ch;
4507       }
4508       j++, k++;
4509    }
4510    d[k] = '\0';
4511    return k;
4512 }
4513
4514 public char * OffsetEscapedString(char * s, int len, int offset)
4515 {
4516    char ch;
4517    int j = 0, k = 0;
4518    while(j < len && k < offset && (ch = s[j]))
4519    {
4520       if(ch == '\\') ++j;
4521       j++, k++;
4522    }
4523    return (k == offset) ? s + j : null;
4524 }
4525
4526 public Operand GetOperand(Expression exp)
4527 {
4528    Operand op { };
4529    Type type = exp.expType;
4530    if(type)
4531    {
4532       while(type.kind == classType &&
4533          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4534       {
4535          if(!type._class.registered.dataType)
4536             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4537          type = type._class.registered.dataType;
4538
4539       }
4540       if(exp.type == stringExp && op.kind == pointerType)
4541       {
4542          op.ui64 = (uint64)(uintptr)exp.string;
4543          op.kind = pointerType;
4544          op.ops = uint64Ops;
4545       }
4546       else if(exp.isConstant && exp.type == constantExp)
4547       {
4548          op.kind = type.kind;
4549          op.type = type;
4550
4551          switch(op.kind)
4552          {
4553             case _BoolType:
4554             case charType:
4555             {
4556                if(exp.constant[0] == '\'')
4557                {
4558                   op.c = exp.constant[1];
4559                   op.ops = charOps;
4560                }
4561                else if(type.isSigned)
4562                {
4563                   op.c = (char)strtol(exp.constant, null, 0);
4564                   op.ops = charOps;
4565                }
4566                else
4567                {
4568                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4569                   op.ops = ucharOps;
4570                }
4571                break;
4572             }
4573             case shortType:
4574                if(type.isSigned)
4575                {
4576                   op.s = (short)strtol(exp.constant, null, 0);
4577                   op.ops = shortOps;
4578                }
4579                else
4580                {
4581                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4582                   op.ops = ushortOps;
4583                }
4584                break;
4585             case intType:
4586             case longType:
4587                if(type.isSigned)
4588                {
4589                   op.i = (int)strtol(exp.constant, null, 0);
4590                   op.ops = intOps;
4591                }
4592                else
4593                {
4594                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4595                   op.ops = uintOps;
4596                }
4597                op.kind = intType;
4598                break;
4599             case int64Type:
4600                if(type.isSigned)
4601                {
4602                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4603                   op.ops = int64Ops;
4604                }
4605                else
4606                {
4607                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4608                   op.ops = uint64Ops;
4609                }
4610                op.kind = int64Type;
4611                break;
4612             case intPtrType:
4613                if(type.isSigned)
4614                {
4615                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4616                   op.ops = int64Ops;
4617                }
4618                else
4619                {
4620                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4621                   op.ops = uint64Ops;
4622                }
4623                op.kind = int64Type;
4624                break;
4625             case intSizeType:
4626                if(type.isSigned)
4627                {
4628                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4629                   op.ops = int64Ops;
4630                }
4631                else
4632                {
4633                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4634                   op.ops = uint64Ops;
4635                }
4636                op.kind = int64Type;
4637                break;
4638             case floatType:
4639                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4640                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4641                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4642                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4643                else
4644                   op.f = (float)strtod(exp.constant, null);
4645                op.ops = floatOps;
4646                break;
4647             case doubleType:
4648                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4649                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4650                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4651                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4652                else
4653                   op.d = (double)strtod(exp.constant, null);
4654                op.ops = doubleOps;
4655                break;
4656             //case classType:    For when we have operator overloading...
4657             // Pointer additions
4658             //case functionType:
4659             case arrayType:
4660             case pointerType:
4661             case classType:
4662                op.ui64 = _strtoui64(exp.constant, null, 0);
4663                op.kind = pointerType;
4664                op.ops = uint64Ops;
4665                // op.ptrSize =
4666                break;
4667          }
4668       }
4669    }
4670    return op;
4671 }
4672
4673 static int64 GetEnumValue(Class _class, void * ptr)
4674 {
4675    int64 v = 0;
4676    switch(_class.typeSize)
4677    {
4678       case 8:
4679          if(!strcmp(_class.dataTypeString, "uint64"))
4680             v = (int64)*(uint64 *)ptr;
4681          else
4682             v = (int64)*(int64 *)ptr;
4683          break;
4684       case 4:
4685          if(!strcmp(_class.dataTypeString, "uint"))
4686             v = (int64)*(uint *)ptr;
4687          else
4688             v = (int64)*(int *)ptr;
4689          break;
4690       case 2:
4691          if(!strcmp(_class.dataTypeString, "uint16"))
4692             v = (int64)*(uint16 *)ptr;
4693          else
4694             v = (int64)*(short *)ptr;
4695          break;
4696       case 1:
4697          if(!strcmp(_class.dataTypeString, "byte"))
4698             v = (int64)*(byte *)ptr;
4699          else
4700             v = (int64)*(char *)ptr;
4701          break;
4702    }
4703    return v;
4704 }
4705
4706 static __attribute__((unused)) void UnusedFunction()
4707 {
4708    int a;
4709    a.OnGetString(0,0,0);
4710 }
4711 default:
4712 extern int __ecereVMethodID_class_OnGetString;
4713 public:
4714
4715 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4716 {
4717    DataMember dataMember;
4718    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4719    {
4720       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4721          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4722       else
4723       {
4724          Expression exp { };
4725          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4726          Type type;
4727          void * ptr = inst.data + dataMember.offset + offset;
4728          char * result = null;
4729          exp.loc = member.loc = inst.loc;
4730          ((Identifier)member.identifiers->first).loc = inst.loc;
4731
4732          if(!dataMember.dataType)
4733             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4734          type = dataMember.dataType;
4735          if(type.kind == classType)
4736          {
4737             Class _class = type._class.registered;
4738             if(_class.type == enumClass)
4739             {
4740                Class enumClass = eSystem_FindClass(privateModule, "enum");
4741                if(enumClass)
4742                {
4743                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4744                   NamedLink64 item;
4745                   for(item = e.values.first; item; item = item.next)
4746                   {
4747                      if(item.data == GetEnumValue(_class, ptr))
4748                      {
4749                         result = item.name;
4750                         break;
4751                      }
4752                   }
4753                   if(result)
4754                   {
4755                      exp.identifier = MkIdentifier(result);
4756                      exp.type = identifierExp;
4757                      exp.destType = MkClassType(_class.fullName);
4758                      ProcessExpressionType(exp);
4759                   }
4760                }
4761             }
4762             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4763             {
4764                if(!_class.dataType)
4765                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4766                type = _class.dataType;
4767             }
4768          }
4769          if(!result)
4770          {
4771             switch(type.kind)
4772             {
4773                case floatType:
4774                {
4775                   FreeExpContents(exp);
4776
4777                   exp.constant = PrintFloat(*(float*)ptr);
4778                   exp.type = constantExp;
4779                   break;
4780                }
4781                case doubleType:
4782                {
4783                   FreeExpContents(exp);
4784
4785                   exp.constant = PrintDouble(*(double*)ptr);
4786                   exp.type = constantExp;
4787                   break;
4788                }
4789                case intType:
4790                {
4791                   FreeExpContents(exp);
4792
4793                   exp.constant = PrintInt(*(int*)ptr);
4794                   exp.type = constantExp;
4795                   break;
4796                }
4797                case int64Type:
4798                {
4799                   FreeExpContents(exp);
4800
4801                   exp.constant = PrintInt64(*(int64*)ptr);
4802                   exp.type = constantExp;
4803                   break;
4804                }
4805                case intPtrType:
4806                {
4807                   FreeExpContents(exp);
4808                   // TODO: This should probably use proper type
4809                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4810                   exp.type = constantExp;
4811                   break;
4812                }
4813                case intSizeType:
4814                {
4815                   FreeExpContents(exp);
4816                   // TODO: This should probably use proper type
4817                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4818                   exp.type = constantExp;
4819                   break;
4820                }
4821                default:
4822                   Compiler_Error($"Unhandled type populating instance\n");
4823             }
4824          }
4825          ListAdd(memberList, member);
4826       }
4827
4828       if(parentDataMember.type == unionMember)
4829          break;
4830    }
4831 }
4832
4833 void PopulateInstance(Instantiation inst)
4834 {
4835    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4836    Class _class = classSym.registered;
4837    DataMember dataMember;
4838    OldList * memberList = MkList();
4839    // Added this check and ->Add to prevent memory leaks on bad code
4840    if(!inst.members)
4841       inst.members = MkListOne(MkMembersInitList(memberList));
4842    else
4843       inst.members->Add(MkMembersInitList(memberList));
4844    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4845    {
4846       if(!dataMember.isProperty)
4847       {
4848          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4849             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4850          else
4851          {
4852             Expression exp { };
4853             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4854             Type type;
4855             void * ptr = inst.data + dataMember.offset;
4856             char * result = null;
4857
4858             exp.loc = member.loc = inst.loc;
4859             ((Identifier)member.identifiers->first).loc = inst.loc;
4860
4861             if(!dataMember.dataType)
4862                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4863             type = dataMember.dataType;
4864             if(type.kind == classType)
4865             {
4866                Class _class = type._class.registered;
4867                if(_class.type == enumClass)
4868                {
4869                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4870                   if(enumClass)
4871                   {
4872                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4873                      NamedLink64 item;
4874                      for(item = e.values.first; item; item = item.next)
4875                      {
4876                         if(item.data == GetEnumValue(_class, ptr))
4877                         {
4878                            result = item.name;
4879                            break;
4880                         }
4881                      }
4882                   }
4883                   if(result)
4884                   {
4885                      exp.identifier = MkIdentifier(result);
4886                      exp.type = identifierExp;
4887                      exp.destType = MkClassType(_class.fullName);
4888                      ProcessExpressionType(exp);
4889                   }
4890                }
4891                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4892                {
4893                   if(!_class.dataType)
4894                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4895                   type = _class.dataType;
4896                }
4897             }
4898             if(!result)
4899             {
4900                switch(type.kind)
4901                {
4902                   case floatType:
4903                   {
4904                      exp.constant = PrintFloat(*(float*)ptr);
4905                      exp.type = constantExp;
4906                      break;
4907                   }
4908                   case doubleType:
4909                   {
4910                      exp.constant = PrintDouble(*(double*)ptr);
4911                      exp.type = constantExp;
4912                      break;
4913                   }
4914                   case intType:
4915                   {
4916                      exp.constant = PrintInt(*(int*)ptr);
4917                      exp.type = constantExp;
4918                      break;
4919                   }
4920                   case int64Type:
4921                   {
4922                      exp.constant = PrintInt64(*(int64*)ptr);
4923                      exp.type = constantExp;
4924                      break;
4925                   }
4926                   case intPtrType:
4927                   {
4928                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4929                      exp.type = constantExp;
4930                      break;
4931                   }
4932                   default:
4933                      Compiler_Error($"Unhandled type populating instance\n");
4934                }
4935             }
4936             ListAdd(memberList, member);
4937          }
4938       }
4939    }
4940 }
4941
4942 void ComputeInstantiation(Expression exp)
4943 {
4944    Instantiation inst = exp.instance;
4945    MembersInit members;
4946    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4947    Class _class = classSym ? classSym.registered : null;
4948    DataMember curMember = null;
4949    Class curClass = null;
4950    DataMember subMemberStack[256];
4951    int subMemberStackPos = 0;
4952    uint64 bits = 0;
4953
4954    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4955    {
4956       // Don't recompute the instantiation...
4957       // Non Simple classes will have become constants by now
4958       if(inst.data)
4959          return;
4960
4961       if(_class.type == normalClass || _class.type == noHeadClass)
4962       {
4963          inst.data = (byte *)eInstance_New(_class);
4964          if(_class.type == normalClass)
4965             ((Instance)inst.data)._refCount++;
4966       }
4967       else
4968          inst.data = new0 byte[_class.structSize];
4969    }
4970
4971    if(inst.members)
4972    {
4973       for(members = inst.members->first; members; members = members.next)
4974       {
4975          switch(members.type)
4976          {
4977             case dataMembersInit:
4978             {
4979                if(members.dataMembers)
4980                {
4981                   MemberInit member;
4982                   for(member = members.dataMembers->first; member; member = member.next)
4983                   {
4984                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4985                      bool found = false;
4986
4987                      Property prop = null;
4988                      DataMember dataMember = null;
4989                      uint dataMemberOffset;
4990
4991                      if(!ident)
4992                      {
4993                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4994                         if(curMember)
4995                         {
4996                            if(curMember.isProperty)
4997                               prop = (Property)curMember;
4998                            else
4999                            {
5000                               dataMember = curMember;
5001
5002                               // CHANGED THIS HERE
5003                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
5004
5005                               // 2013/17/29 -- It seems that this was missing here!
5006                               if(_class.type == normalClass)
5007                                  dataMemberOffset += _class.base.structSize;
5008                               // dataMemberOffset = dataMember.offset;
5009                            }
5010                            found = true;
5011                         }
5012                      }
5013                      else
5014                      {
5015                         prop = eClass_FindProperty(_class, ident.string, privateModule);
5016                         if(prop)
5017                         {
5018                            found = true;
5019                            if(prop.memberAccess == publicAccess)
5020                            {
5021                               curMember = (DataMember)prop;
5022                               curClass = prop._class;
5023                            }
5024                         }
5025                         else
5026                         {
5027                            DataMember _subMemberStack[256];
5028                            int _subMemberStackPos = 0;
5029
5030                            // FILL MEMBER STACK
5031                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
5032
5033                            if(dataMember)
5034                            {
5035                               found = true;
5036                               if(dataMember.memberAccess == publicAccess)
5037                               {
5038                                  curMember = dataMember;
5039                                  curClass = dataMember._class;
5040                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
5041                                  subMemberStackPos = _subMemberStackPos;
5042                               }
5043                            }
5044                         }
5045                      }
5046
5047                      if(found && member.initializer && member.initializer.type == expInitializer)
5048                      {
5049                         Expression value = member.initializer.exp;
5050                         Type type = null;
5051                         bool deepMember = false;
5052                         if(prop)
5053                         {
5054                            type = prop.dataType;
5055                         }
5056                         else if(dataMember)
5057                         {
5058                            if(!dataMember.dataType)
5059                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
5060
5061                            type = dataMember.dataType;
5062                         }
5063
5064                         if(ident && ident.next)
5065                         {
5066                            deepMember = true;
5067
5068                            // for(; ident && type; ident = ident.next)
5069                            for(ident = ident.next; ident && type; ident = ident.next)
5070                            {
5071                               if(type.kind == classType)
5072                               {
5073                                  prop = eClass_FindProperty(type._class.registered,
5074                                     ident.string, privateModule);
5075                                  if(prop)
5076                                     type = prop.dataType;
5077                                  else
5078                                  {
5079                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
5080                                        ident.string, &dataMemberOffset, privateModule, null, null);
5081                                     if(dataMember)
5082                                        type = dataMember.dataType;
5083                                  }
5084                               }
5085                               else if(type.kind == structType || type.kind == unionType)
5086                               {
5087                                  Type memberType;
5088                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
5089                                  {
5090                                     if(!strcmp(memberType.name, ident.string))
5091                                     {
5092                                        type = memberType;
5093                                        break;
5094                                     }
5095                                  }
5096                               }
5097                            }
5098                         }
5099                         if(value)
5100                         {
5101                            FreeType(value.destType);
5102                            value.destType = type;
5103                            if(type) type.refCount++;
5104                            ComputeExpression(value);
5105                         }
5106                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
5107                         {
5108                            if(type.kind == classType)
5109                            {
5110                               Class _class = type._class.registered;
5111                               if(_class && (_class.type == bitClass || _class.type == unitClass || _class.type == enumClass))
5112                               {
5113                                  if(!_class.dataType)
5114                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5115                                  type = _class.dataType;
5116                               }
5117                            }
5118
5119                            if(dataMember)
5120                            {
5121                               void * ptr = inst.data + dataMemberOffset;
5122
5123                               if(value.type == constantExp)
5124                               {
5125                                  switch(type.kind)
5126                                  {
5127                                     case intType:
5128                                     {
5129                                        GetInt(value, (int*)ptr);
5130                                        break;
5131                                     }
5132                                     case int64Type:
5133                                     {
5134                                        GetInt64(value, (int64*)ptr);
5135                                        break;
5136                                     }
5137                                     case intPtrType:
5138                                     {
5139                                        GetIntPtr(value, (intptr*)ptr);
5140                                        break;
5141                                     }
5142                                     case intSizeType:
5143                                     {
5144                                        GetIntSize(value, (intsize*)ptr);
5145                                        break;
5146                                     }
5147                                     case floatType:
5148                                     {
5149                                        GetFloat(value, (float*)ptr);
5150                                        break;
5151                                     }
5152                                     case doubleType:
5153                                     {
5154                                        GetDouble(value, (double *)ptr);
5155                                        break;
5156                                     }
5157                                  }
5158                               }
5159                               else if(value.type == instanceExp)
5160                               {
5161                                  if(type.kind == classType)
5162                                  {
5163                                     Class _class = type._class.registered;
5164                                     if(_class.type == structClass)
5165                                     {
5166                                        ComputeTypeSize(type);
5167                                        if(value.instance.data)
5168                                           memcpy(ptr, value.instance.data, type.size);
5169                                     }
5170                                  }
5171                               }
5172                            }
5173                            else if(prop && prop.Set != (void *)(intptr)1)
5174                            {
5175                               if(value.type == instanceExp && value.instance.data)
5176                               {
5177                                  if(type.kind == classType)
5178                                  {
5179                                     Class _class = type._class.registered;
5180                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5181                                     {
5182                                        void (*Set)(void *, void *) = (void *)prop.Set;
5183                                        Set(inst.data, value.instance.data);
5184                                        PopulateInstance(inst);
5185                                     }
5186                                  }
5187                               }
5188                               else if(value.type == constantExp)
5189                               {
5190                                  switch(type.kind)
5191                                  {
5192                                     case doubleType:
5193                                     {
5194                                        void (*Set)(void *, double) = (void *)prop.Set;
5195                                        Set(inst.data, strtod(value.constant, null) );
5196                                        break;
5197                                     }
5198                                     case floatType:
5199                                     {
5200                                        void (*Set)(void *, float) = (void *)prop.Set;
5201                                        Set(inst.data, (float)(strtod(value.constant, null)));
5202                                        break;
5203                                     }
5204                                     case intType:
5205                                     {
5206                                        void (*Set)(void *, int) = (void *)prop.Set;
5207                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5208                                        break;
5209                                     }
5210                                     case int64Type:
5211                                     {
5212                                        void (*Set)(void *, int64) = (void *)prop.Set;
5213                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5214                                        break;
5215                                     }
5216                                     case intPtrType:
5217                                     {
5218                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5219                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5220                                        break;
5221                                     }
5222                                     case intSizeType:
5223                                     {
5224                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5225                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5226                                        break;
5227                                     }
5228                                  }
5229                               }
5230                               else if(value.type == stringExp)
5231                               {
5232                                  char temp[1024];
5233                                  ReadString(temp, value.string);
5234                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5235                               }
5236                            }
5237                         }
5238                         else if(!deepMember && type && _class.type == unitClass)
5239                         {
5240                            if(prop)
5241                            {
5242                               // Only support converting units to units for now...
5243                               if(value.type == constantExp)
5244                               {
5245                                  if(type.kind == classType)
5246                                  {
5247                                     Class _class = type._class.registered;
5248                                     if(_class.type == unitClass)
5249                                     {
5250                                        if(!_class.dataType)
5251                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5252                                        type = _class.dataType;
5253                                     }
5254                                  }
5255                                  // TODO: Assuming same base type for units...
5256                                  switch(type.kind)
5257                                  {
5258                                     case floatType:
5259                                     {
5260                                        float fValue;
5261                                        float (*Set)(float) = (void *)prop.Set;
5262                                        GetFloat(member.initializer.exp, &fValue);
5263                                        exp.constant = PrintFloat(Set(fValue));
5264                                        exp.type = constantExp;
5265                                        break;
5266                                     }
5267                                     case doubleType:
5268                                     {
5269                                        double dValue;
5270                                        double (*Set)(double) = (void *)prop.Set;
5271                                        GetDouble(member.initializer.exp, &dValue);
5272                                        exp.constant = PrintDouble(Set(dValue));
5273                                        exp.type = constantExp;
5274                                        break;
5275                                     }
5276                                  }
5277                               }
5278                            }
5279                         }
5280                         else if(!deepMember && type && _class.type == bitClass)
5281                         {
5282                            if(prop)
5283                            {
5284                               if(value.type == instanceExp && value.instance.data)
5285                               {
5286                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5287                                  bits = Set(value.instance.data);
5288                               }
5289                               else if(value.type == constantExp)
5290                               {
5291                               }
5292                            }
5293                            else if(dataMember)
5294                            {
5295                               BitMember bitMember = (BitMember) dataMember;
5296                               Type type;
5297                               uint64 part = 0;
5298                               bits = (bits & ~bitMember.mask);
5299                               if(!bitMember.dataType)
5300                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5301                               type = bitMember.dataType;
5302                               if(type.kind == classType && type._class && type._class.registered)
5303                               {
5304                                  if(!type._class.registered.dataType)
5305                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5306                                  type = type._class.registered.dataType;
5307                               }
5308                               switch(type.kind)
5309                               {
5310                                  case _BoolType:
5311                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5312                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5313                                  case intType:
5314                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5315                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5316                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5317                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5318                               }
5319                               bits |= part << bitMember.pos;
5320                            }
5321                         }
5322                      }
5323                      else
5324                      {
5325                         if(_class && _class.type == unitClass)
5326                         {
5327                            ComputeExpression(member.initializer.exp);
5328                            exp.constant = member.initializer.exp.constant;
5329                            exp.type = constantExp;
5330
5331                            member.initializer.exp.constant = null;
5332                         }
5333                      }
5334                   }
5335                }
5336                break;
5337             }
5338          }
5339       }
5340    }
5341    if(_class && _class.type == bitClass)
5342    {
5343       exp.constant = PrintHexUInt(bits);
5344       exp.type = constantExp;
5345    }
5346    if(exp.type != instanceExp)
5347    {
5348       FreeInstance(inst);
5349    }
5350 }
5351
5352 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5353 {
5354    bool result = false;
5355    switch(kind)
5356    {
5357       case shortType:
5358          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5359             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5360          break;
5361       case intType:
5362       case longType:
5363          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5364             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5365          break;
5366       case int64Type:
5367          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5368             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5369             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5370          break;
5371       case floatType:
5372          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5373             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5374             result = GetOpFloat(op, &op.f);
5375          break;
5376       case doubleType:
5377          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5378             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5379             result = GetOpDouble(op, &op.d);
5380          break;
5381       case pointerType:
5382          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5383             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5384             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5385          break;
5386       case enumType:
5387          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5388             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5389             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5390          break;
5391       case intPtrType:
5392          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5393             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5394          break;
5395       case intSizeType:
5396          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5397             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5398          break;
5399    }
5400    return result;
5401 }
5402
5403 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5404 {
5405    if(exp.op.op == SIZEOF)
5406    {
5407       FreeExpContents(exp);
5408       exp.type = constantExp;
5409       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5410    }
5411    else
5412    {
5413       if(!exp.op.exp1)
5414       {
5415          switch(exp.op.op)
5416          {
5417             // unary arithmetic
5418             case '+':
5419             {
5420                // Provide default unary +
5421                Expression exp2 = exp.op.exp2;
5422                exp.op.exp2 = null;
5423                FreeExpContents(exp);
5424                FreeType(exp.expType);
5425                FreeType(exp.destType);
5426                *exp = *exp2;
5427                delete exp2;
5428                break;
5429             }
5430             case '-':
5431                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5432                break;
5433             // unary arithmetic increment and decrement
5434                   //OPERATOR_ALL(UNARY, ++, Inc)
5435                   //OPERATOR_ALL(UNARY, --, Dec)
5436             // unary bitwise
5437             case '~':
5438                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5439                break;
5440             // unary logical negation
5441             case '!':
5442                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5443                break;
5444          }
5445       }
5446       else
5447       {
5448          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5449          {
5450             if(Promote(op2, op1.kind, op1.type.isSigned))
5451                op2.kind = op1.kind, op2.ops = op1.ops;
5452             else if(Promote(op1, op2.kind, op2.type.isSigned))
5453                op1.kind = op2.kind, op1.ops = op2.ops;
5454          }
5455          switch(exp.op.op)
5456          {
5457             // binary arithmetic
5458             case '+':
5459                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5460                break;
5461             case '-':
5462                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5463                break;
5464             case '*':
5465                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5466                break;
5467             case '/':
5468                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5469                break;
5470             case '%':
5471                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5472                break;
5473             // binary arithmetic assignment
5474                   //OPERATOR_ALL(BINARY, =, Asign)
5475                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5476                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5477                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5478                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5479                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5480             // binary bitwise
5481             case '&':
5482                if(exp.op.exp2)
5483                {
5484                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5485                }
5486                break;
5487             case '|':
5488                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5489                break;
5490             case '^':
5491                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5492                break;
5493             case LEFT_OP:
5494                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5495                break;
5496             case RIGHT_OP:
5497                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5498                break;
5499             // binary bitwise assignment
5500                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5501                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5502                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5503                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5504                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5505             // binary logical equality
5506             case EQ_OP:
5507                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5508                break;
5509             case NE_OP:
5510                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5511                break;
5512             // binary logical
5513             case AND_OP:
5514                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5515                break;
5516             case OR_OP:
5517                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5518                break;
5519             // binary logical relational
5520             case '>':
5521                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5522                break;
5523             case '<':
5524                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5525                break;
5526             case GE_OP:
5527                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5528                break;
5529             case LE_OP:
5530                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5531                break;
5532          }
5533       }
5534    }
5535 }
5536
5537 void ComputeExpression(Expression exp)
5538 {
5539 #ifdef _DEBUG
5540    char expString[10240];
5541    expString[0] = '\0';
5542    PrintExpression(exp, expString);
5543 #endif
5544
5545    switch(exp.type)
5546    {
5547       case identifierExp:
5548       {
5549          Identifier id = exp.identifier;
5550          if(id && exp.isConstant && !inCompiler && !inPreCompiler && !inDebugger)
5551          {
5552             Class c = (exp.expType && exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
5553             if(c && c.type == enumClass)
5554             {
5555                Class enumClass = eSystem_FindClass(privateModule, "enum");
5556                if(enumClass)
5557                {
5558                   NamedLink64 value;
5559                   EnumClassData e = ACCESS_CLASSDATA(c, enumClass);
5560                   for(value = e.values.first; value; value = value.next)
5561                   {
5562                      if(!strcmp(value.name, id.string))
5563                         break;
5564                   }
5565                   if(value)
5566                   {
5567                      const String dts = c.dataTypeString;
5568                      FreeExpContents(exp);
5569                      exp.type = constantExp;
5570                      exp.constant = (dts && (!strcmp(dts, "int") || !strcmp(dts, "int64") || !strcmp(dts, "short") || !strcmp(dts, "char"))) ? PrintInt64(value.data) : PrintUInt64(value.data);
5571                   }
5572                }
5573             }
5574          }
5575          break;
5576       }
5577       case instanceExp:
5578       {
5579          ComputeInstantiation(exp);
5580          break;
5581       }
5582       /*
5583       case constantExp:
5584          break;
5585       */
5586       case opExp:
5587       {
5588          Expression exp1, exp2 = null;
5589          Operand op1 { };
5590          Operand op2 { };
5591
5592          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5593          if(exp.op.exp2)
5594          {
5595             Expression e = exp.op.exp2;
5596
5597             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5598             {
5599                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5600                {
5601                   if(e.type == extensionCompoundExp)
5602                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5603                   else
5604                      e = e.list->last;
5605                }
5606             }
5607             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5608             {
5609                if(e.type == stringExp && e.string)
5610                {
5611                   char * string = e.string;
5612                   int len = strlen(string);
5613                   char * tmp = new char[len-2+1];
5614                   len = UnescapeString(tmp, string + 1, len - 2);
5615                   delete tmp;
5616                   FreeExpContents(exp);
5617                   exp.type = constantExp;
5618                   exp.constant = PrintUInt(len + 1);
5619                }
5620                else
5621                {
5622                   Type type = e.expType;
5623                   type.refCount++;
5624                   FreeExpContents(exp);
5625                   exp.type = constantExp;
5626                   exp.constant = PrintUInt(ComputeTypeSize(type));
5627                   FreeType(type);
5628                }
5629                break;
5630             }
5631             else
5632                ComputeExpression(exp.op.exp2);
5633          }
5634          if(exp.op.exp1)
5635          {
5636             ComputeExpression(exp.op.exp1);
5637             exp1 = exp.op.exp1;
5638             exp2 = exp.op.exp2;
5639             op1 = GetOperand(exp1);
5640             if(op1.type) op1.type.refCount++;
5641             if(exp2)
5642             {
5643                op2 = GetOperand(exp2);
5644                if(op2.type) op2.type.refCount++;
5645             }
5646          }
5647          else
5648          {
5649             exp1 = exp.op.exp2;
5650             op1 = GetOperand(exp1);
5651             if(op1.type) op1.type.refCount++;
5652          }
5653
5654          CallOperator(exp, exp1, exp2, op1, op2);
5655          /*
5656          switch(exp.op.op)
5657          {
5658             // Unary operators
5659             case '&':
5660                // Also binary
5661                if(exp.op.exp1 && exp.op.exp2)
5662                {
5663                   // Binary And
5664                   if(op1.ops.BitAnd)
5665                   {
5666                      FreeExpContents(exp);
5667                      op1.ops.BitAnd(exp, op1, op2);
5668                   }
5669                }
5670                break;
5671             case '*':
5672                if(exp.op.exp1)
5673                {
5674                   if(op1.ops.Mul)
5675                   {
5676                      FreeExpContents(exp);
5677                      op1.ops.Mul(exp, op1, op2);
5678                   }
5679                }
5680                break;
5681             case '+':
5682                if(exp.op.exp1)
5683                {
5684                   if(op1.ops.Add)
5685                   {
5686                      FreeExpContents(exp);
5687                      op1.ops.Add(exp, op1, op2);
5688                   }
5689                }
5690                else
5691                {
5692                   // Provide default unary +
5693                   Expression exp2 = exp.op.exp2;
5694                   exp.op.exp2 = null;
5695                   FreeExpContents(exp);
5696                   FreeType(exp.expType);
5697                   FreeType(exp.destType);
5698
5699                   *exp = *exp2;
5700                   delete exp2;
5701                }
5702                break;
5703             case '-':
5704                if(exp.op.exp1)
5705                {
5706                   if(op1.ops.Sub)
5707                   {
5708                      FreeExpContents(exp);
5709                      op1.ops.Sub(exp, op1, op2);
5710                   }
5711                }
5712                else
5713                {
5714                   if(op1.ops.Neg)
5715                   {
5716                      FreeExpContents(exp);
5717                      op1.ops.Neg(exp, op1);
5718                   }
5719                }
5720                break;
5721             case '~':
5722                if(op1.ops.BitNot)
5723                {
5724                   FreeExpContents(exp);
5725                   op1.ops.BitNot(exp, op1);
5726                }
5727                break;
5728             case '!':
5729                if(op1.ops.Not)
5730                {
5731                   FreeExpContents(exp);
5732                   op1.ops.Not(exp, op1);
5733                }
5734                break;
5735             // Binary only operators
5736             case '/':
5737                if(op1.ops.Div)
5738                {
5739                   FreeExpContents(exp);
5740                   op1.ops.Div(exp, op1, op2);
5741                }
5742                break;
5743             case '%':
5744                if(op1.ops.Mod)
5745                {
5746                   FreeExpContents(exp);
5747                   op1.ops.Mod(exp, op1, op2);
5748                }
5749                break;
5750             case LEFT_OP:
5751                break;
5752             case RIGHT_OP:
5753                break;
5754             case '<':
5755                if(exp.op.exp1)
5756                {
5757                   if(op1.ops.Sma)
5758                   {
5759                      FreeExpContents(exp);
5760                      op1.ops.Sma(exp, op1, op2);
5761                   }
5762                }
5763                break;
5764             case '>':
5765                if(exp.op.exp1)
5766                {
5767                   if(op1.ops.Grt)
5768                   {
5769                      FreeExpContents(exp);
5770                      op1.ops.Grt(exp, op1, op2);
5771                   }
5772                }
5773                break;
5774             case LE_OP:
5775                if(exp.op.exp1)
5776                {
5777                   if(op1.ops.SmaEqu)
5778                   {
5779                      FreeExpContents(exp);
5780                      op1.ops.SmaEqu(exp, op1, op2);
5781                   }
5782                }
5783                break;
5784             case GE_OP:
5785                if(exp.op.exp1)
5786                {
5787                   if(op1.ops.GrtEqu)
5788                   {
5789                      FreeExpContents(exp);
5790                      op1.ops.GrtEqu(exp, op1, op2);
5791                   }
5792                }
5793                break;
5794             case EQ_OP:
5795                if(exp.op.exp1)
5796                {
5797                   if(op1.ops.Equ)
5798                   {
5799                      FreeExpContents(exp);
5800                      op1.ops.Equ(exp, op1, op2);
5801                   }
5802                }
5803                break;
5804             case NE_OP:
5805                if(exp.op.exp1)
5806                {
5807                   if(op1.ops.Nqu)
5808                   {
5809                      FreeExpContents(exp);
5810                      op1.ops.Nqu(exp, op1, op2);
5811                   }
5812                }
5813                break;
5814             case '|':
5815                if(op1.ops.BitOr)
5816                {
5817                   FreeExpContents(exp);
5818                   op1.ops.BitOr(exp, op1, op2);
5819                }
5820                break;
5821             case '^':
5822                if(op1.ops.BitXor)
5823                {
5824                   FreeExpContents(exp);
5825                   op1.ops.BitXor(exp, op1, op2);
5826                }
5827                break;
5828             case AND_OP:
5829                break;
5830             case OR_OP:
5831                break;
5832             case SIZEOF:
5833                FreeExpContents(exp);
5834                exp.type = constantExp;
5835                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5836                break;
5837          }
5838          */
5839          if(op1.type) FreeType(op1.type);
5840          if(op2.type) FreeType(op2.type);
5841          break;
5842       }
5843       case bracketsExp:
5844       case extensionExpressionExp:
5845       {
5846          Expression e, n;
5847          for(e = exp.list->first; e; e = n)
5848          {
5849             n = e.next;
5850             if(!n)
5851             {
5852                OldList * list = exp.list;
5853                Expression prev = exp.prev;
5854                Expression next = exp.next;
5855                ComputeExpression(e);
5856                //FreeExpContents(exp);
5857                FreeType(exp.expType);
5858                FreeType(exp.destType);
5859                *exp = *e;
5860                exp.prev = prev;
5861                exp.next = next;
5862                delete e;
5863                delete list;
5864             }
5865             else
5866             {
5867                FreeExpression(e);
5868             }
5869          }
5870          break;
5871       }
5872       /*
5873
5874       case ExpIndex:
5875       {
5876          Expression e;
5877          exp.isConstant = true;
5878
5879          ComputeExpression(exp.index.exp);
5880          if(!exp.index.exp.isConstant)
5881             exp.isConstant = false;
5882
5883          for(e = exp.index.index->first; e; e = e.next)
5884          {
5885             ComputeExpression(e);
5886             if(!e.next)
5887             {
5888                // Check if this type is int
5889             }
5890             if(!e.isConstant)
5891                exp.isConstant = false;
5892          }
5893          exp.expType = Dereference(exp.index.exp.expType);
5894          break;
5895       }
5896       */
5897       case memberExp:
5898       {
5899          Expression memberExp = exp.member.exp;
5900          Identifier memberID = exp.member.member;
5901
5902          Type type;
5903          ComputeExpression(exp.member.exp);
5904          type = exp.member.exp.expType;
5905          if(type)
5906          {
5907             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);
5908             Property prop = null;
5909             DataMember member = null;
5910             Class convertTo = null;
5911             if(type.kind == subClassType && exp.member.exp.type == classExp)
5912                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5913
5914             if(!_class)
5915             {
5916                char string[256];
5917                Symbol classSym;
5918                string[0] = '\0';
5919                PrintTypeNoConst(type, string, false, true);
5920                classSym = FindClass(string);
5921                _class = classSym ? classSym.registered : null;
5922             }
5923
5924             if(exp.member.member)
5925             {
5926                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5927                if(!prop)
5928                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5929             }
5930             if(!prop && !member && _class && exp.member.member)
5931             {
5932                Symbol classSym = FindClass(exp.member.member.string);
5933                convertTo = _class;
5934                _class = classSym ? classSym.registered : null;
5935                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5936             }
5937
5938             if(prop)
5939             {
5940                if(prop.compiled)
5941                {
5942                   Type type = prop.dataType;
5943                   // TODO: Assuming same base type for units...
5944                   if(_class.type == unitClass)
5945                   {
5946                      if(type.kind == classType)
5947                      {
5948                         Class _class = type._class.registered;
5949                         if(_class.type == unitClass)
5950                         {
5951                            if(!_class.dataType)
5952                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5953                            type = _class.dataType;
5954                         }
5955                      }
5956                      switch(type.kind)
5957                      {
5958                         case floatType:
5959                         {
5960                            float value;
5961                            float (*Get)(float) = (void *)prop.Get;
5962                            GetFloat(exp.member.exp, &value);
5963                            exp.constant = PrintFloat(Get ? Get(value) : value);
5964                            exp.type = constantExp;
5965                            break;
5966                         }
5967                         case doubleType:
5968                         {
5969                            double value;
5970                            double (*Get)(double);
5971                            GetDouble(exp.member.exp, &value);
5972
5973                            if(convertTo)
5974                               Get = (void *)prop.Set;
5975                            else
5976                               Get = (void *)prop.Get;
5977                            exp.constant = PrintDouble(Get ? Get(value) : value);
5978                            exp.type = constantExp;
5979                            break;
5980                         }
5981                      }
5982                   }
5983                   else
5984                   {
5985                      if(convertTo)
5986                      {
5987                         Expression value = exp.member.exp;
5988                         Type type;
5989                         if(!prop.dataType)
5990                            ProcessPropertyType(prop);
5991
5992                         type = prop.dataType;
5993                         if(!type)
5994                         {
5995                             // printf("Investigate this\n");
5996                         }
5997                         else if(_class.type == structClass)
5998                         {
5999                            switch(type.kind)
6000                            {
6001                               case classType:
6002                               {
6003                                  Class propertyClass = type._class.registered;
6004                                  if(propertyClass.type == structClass && value.type == instanceExp)
6005                                  {
6006                                     void (*Set)(void *, void *) = (void *)prop.Set;
6007                                     exp.instance = Instantiation { };
6008                                     exp.instance.data = new0 byte[_class.structSize];
6009                                     exp.instance._class = MkSpecifierName(_class.fullName);
6010                                     exp.instance.loc = exp.loc;
6011                                     exp.type = instanceExp;
6012                                     Set(exp.instance.data, value.instance.data);
6013                                     PopulateInstance(exp.instance);
6014                                  }
6015                                  break;
6016                               }
6017                               case intType:
6018                               {
6019                                  int intValue;
6020                                  void (*Set)(void *, int) = (void *)prop.Set;
6021
6022                                  exp.instance = Instantiation { };
6023                                  exp.instance.data = new0 byte[_class.structSize];
6024                                  exp.instance._class = MkSpecifierName(_class.fullName);
6025                                  exp.instance.loc = exp.loc;
6026                                  exp.type = instanceExp;
6027
6028                                  GetInt(value, &intValue);
6029
6030                                  Set(exp.instance.data, intValue);
6031                                  PopulateInstance(exp.instance);
6032                                  break;
6033                               }
6034                               case int64Type:
6035                               {
6036                                  int64 intValue;
6037                                  void (*Set)(void *, int64) = (void *)prop.Set;
6038
6039                                  exp.instance = Instantiation { };
6040                                  exp.instance.data = new0 byte[_class.structSize];
6041                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
6042                                  exp.instance.loc = exp.loc;
6043                                  exp.type = instanceExp;
6044
6045                                  GetInt64(value, &intValue);
6046
6047                                  Set(exp.instance.data, intValue);
6048                                  PopulateInstance(exp.instance);
6049                                  break;
6050                               }
6051                               case intPtrType:
6052                               {
6053                                  // TOFIX:
6054                                  intptr intValue;
6055                                  void (*Set)(void *, intptr) = (void *)prop.Set;
6056
6057                                  exp.instance = Instantiation { };
6058                                  exp.instance.data = new0 byte[_class.structSize];
6059                                  exp.instance._class = MkSpecifierName(_class.fullName);
6060                                  exp.instance.loc = exp.loc;
6061                                  exp.type = instanceExp;
6062
6063                                  GetIntPtr(value, &intValue);
6064
6065                                  Set(exp.instance.data, intValue);
6066                                  PopulateInstance(exp.instance);
6067                                  break;
6068                               }
6069                               case intSizeType:
6070                               {
6071                                  // TOFIX:
6072                                  intsize intValue;
6073                                  void (*Set)(void *, intsize) = (void *)prop.Set;
6074
6075                                  exp.instance = Instantiation { };
6076                                  exp.instance.data = new0 byte[_class.structSize];
6077                                  exp.instance._class = MkSpecifierName(_class.fullName);
6078                                  exp.instance.loc = exp.loc;
6079                                  exp.type = instanceExp;
6080
6081                                  GetIntSize(value, &intValue);
6082
6083                                  Set(exp.instance.data, intValue);
6084                                  PopulateInstance(exp.instance);
6085                                  break;
6086                               }
6087                               case floatType:
6088                               {
6089                                  float floatValue;
6090                                  void (*Set)(void *, float) = (void *)prop.Set;
6091
6092                                  exp.instance = Instantiation { };
6093                                  exp.instance.data = new0 byte[_class.structSize];
6094                                  exp.instance._class = MkSpecifierName(_class.fullName);
6095                                  exp.instance.loc = exp.loc;
6096                                  exp.type = instanceExp;
6097
6098                                  GetFloat(value, &floatValue);
6099
6100                                  Set(exp.instance.data, floatValue);
6101                                  PopulateInstance(exp.instance);
6102                                  break;
6103                               }
6104                               case doubleType:
6105                               {
6106                                  double doubleValue;
6107                                  void (*Set)(void *, double) = (void *)prop.Set;
6108
6109                                  exp.instance = Instantiation { };
6110                                  exp.instance.data = new0 byte[_class.structSize];
6111                                  exp.instance._class = MkSpecifierName(_class.fullName);
6112                                  exp.instance.loc = exp.loc;
6113                                  exp.type = instanceExp;
6114
6115                                  GetDouble(value, &doubleValue);
6116
6117                                  Set(exp.instance.data, doubleValue);
6118                                  PopulateInstance(exp.instance);
6119                                  break;
6120                               }
6121                            }
6122                         }
6123                         else if(_class.type == bitClass)
6124                         {
6125                            switch(type.kind)
6126                            {
6127                               case classType:
6128                               {
6129                                  Class propertyClass = type._class.registered;
6130                                  if(propertyClass.type == structClass && value.instance.data)
6131                                  {
6132                                     unsigned int (*Set)(void *) = (void *)prop.Set;
6133                                     unsigned int bits = Set(value.instance.data);
6134                                     exp.constant = PrintHexUInt(bits);
6135                                     exp.type = constantExp;
6136                                     break;
6137                                  }
6138                                  else if(_class.type == bitClass)
6139                                  {
6140                                     unsigned int value;
6141                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
6142                                     unsigned int bits;
6143
6144                                     GetUInt(exp.member.exp, &value);
6145                                     bits = Set(value);
6146                                     exp.constant = PrintHexUInt(bits);
6147                                     exp.type = constantExp;
6148                                  }
6149                               }
6150                            }
6151                         }
6152                      }
6153                      else
6154                      {
6155                         if(_class.type == bitClass)
6156                         {
6157                            unsigned int value;
6158                            GetUInt(exp.member.exp, &value);
6159
6160                            switch(type.kind)
6161                            {
6162                               case classType:
6163                               {
6164                                  Class _class = type._class.registered;
6165                                  if(_class.type == structClass)
6166                                  {
6167                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6168
6169                                     exp.instance = Instantiation { };
6170                                     exp.instance.data = new0 byte[_class.structSize];
6171                                     exp.instance._class = MkSpecifierName(_class.fullName);
6172                                     exp.instance.loc = exp.loc;
6173                                     //exp.instance.fullSet = true;
6174                                     exp.type = instanceExp;
6175                                     Get(value, exp.instance.data);
6176                                     PopulateInstance(exp.instance);
6177                                  }
6178                                  else if(_class.type == bitClass)
6179                                  {
6180                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6181                                     uint64 bits = Get(value);
6182                                     exp.constant = PrintHexUInt64(bits);
6183                                     exp.type = constantExp;
6184                                  }
6185                                  break;
6186                               }
6187                            }
6188                         }
6189                         else if(_class.type == structClass)
6190                         {
6191                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6192                            switch(type.kind)
6193                            {
6194                               case classType:
6195                               {
6196                                  Class _class = type._class.registered;
6197                                  if(_class.type == structClass && value)
6198                                  {
6199                                     void (*Get)(void *, void *) = (void *)prop.Get;
6200
6201                                     exp.instance = Instantiation { };
6202                                     exp.instance.data = new0 byte[_class.structSize];
6203                                     exp.instance._class = MkSpecifierName(_class.fullName);
6204                                     exp.instance.loc = exp.loc;
6205                                     //exp.instance.fullSet = true;
6206                                     exp.type = instanceExp;
6207                                     Get(value, exp.instance.data);
6208                                     PopulateInstance(exp.instance);
6209                                  }
6210                                  break;
6211                               }
6212                            }
6213                         }
6214                         /*else
6215                         {
6216                            char * value = exp.member.exp.instance.data;
6217                            switch(type.kind)
6218                            {
6219                               case classType:
6220                               {
6221                                  Class _class = type._class.registered;
6222                                  if(_class.type == normalClass)
6223                                  {
6224                                     void *(*Get)(void *) = (void *)prop.Get;
6225
6226                                     exp.instance = Instantiation { };
6227                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6228                                     exp.type = instanceExp;
6229                                     exp.instance.data = Get(value, exp.instance.data);
6230                                  }
6231                                  break;
6232                               }
6233                            }
6234                         }
6235                         */
6236                      }
6237                   }
6238                }
6239                else
6240                {
6241                   exp.isConstant = false;
6242                }
6243             }
6244             else if(member)
6245             {
6246             }
6247          }
6248
6249          if(exp.type != ExpressionType::memberExp)
6250          {
6251             FreeExpression(memberExp);
6252             FreeIdentifier(memberID);
6253          }
6254          break;
6255       }
6256       case typeSizeExp:
6257       {
6258          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6259          FreeExpContents(exp);
6260          exp.constant = PrintUInt(ComputeTypeSize(type));
6261          exp.type = constantExp;
6262          FreeType(type);
6263          break;
6264       }
6265       case classSizeExp:
6266       {
6267          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6268          if(classSym && classSym.registered)
6269          {
6270             if(classSym.registered.fixed)
6271             {
6272                FreeSpecifier(exp._class);
6273                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6274                exp.type = constantExp;
6275             }
6276             else
6277             {
6278                char className[1024];
6279                strcpy(className, "__ecereClass_");
6280                FullClassNameCat(className, classSym.string, true);
6281                //MangleClassName(className);
6282
6283                DeclareClass(classSym, className);
6284
6285                FreeExpContents(exp);
6286                exp.type = pointerExp;
6287                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6288                exp.member.member = MkIdentifier("structSize");
6289             }
6290          }
6291          break;
6292       }
6293       case castExp:
6294       //case constantExp:
6295       {
6296          Type type;
6297          Expression e = exp;
6298          if(exp.type == castExp)
6299          {
6300             if(exp.cast.exp)
6301                ComputeExpression(exp.cast.exp);
6302             e = exp.cast.exp;
6303          }
6304          if(e && exp.expType)
6305          {
6306             /*if(exp.destType)
6307                type = exp.destType;
6308             else*/
6309                type = exp.expType;
6310             if(type.kind == classType)
6311             {
6312                Class _class = type._class.registered;
6313                if(_class && (_class.type == unitClass || _class.type == bitClass))
6314                {
6315                   if(!_class.dataType)
6316                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6317                   type = _class.dataType;
6318                }
6319             }
6320
6321             switch(type.kind)
6322             {
6323                case _BoolType:
6324                case charType:
6325                   if(type.isSigned)
6326                   {
6327                      char value = 0;
6328                      if(GetChar(e, &value))
6329                      {
6330                         FreeExpContents(exp);
6331                         exp.constant = PrintChar(value);
6332                         exp.type = constantExp;
6333                      }
6334                   }
6335                   else
6336                   {
6337                      unsigned char value = 0;
6338                      if(GetUChar(e, &value))
6339                      {
6340                         FreeExpContents(exp);
6341                         exp.constant = PrintUChar(value);
6342                         exp.type = constantExp;
6343                      }
6344                   }
6345                   break;
6346                case shortType:
6347                   if(type.isSigned)
6348                   {
6349                      short value = 0;
6350                      if(GetShort(e, &value))
6351                      {
6352                         FreeExpContents(exp);
6353                         exp.constant = PrintShort(value);
6354                         exp.type = constantExp;
6355                      }
6356                   }
6357                   else
6358                   {
6359                      unsigned short value = 0;
6360                      if(GetUShort(e, &value))
6361                      {
6362                         FreeExpContents(exp);
6363                         exp.constant = PrintUShort(value);
6364                         exp.type = constantExp;
6365                      }
6366                   }
6367                   break;
6368                case intType:
6369                   if(type.isSigned)
6370                   {
6371                      int value = 0;
6372                      if(GetInt(e, &value))
6373                      {
6374                         FreeExpContents(exp);
6375                         exp.constant = PrintInt(value);
6376                         exp.type = constantExp;
6377                      }
6378                   }
6379                   else
6380                   {
6381                      unsigned int value = 0;
6382                      if(GetUInt(e, &value))
6383                      {
6384                         FreeExpContents(exp);
6385                         exp.constant = PrintUInt(value);
6386                         exp.type = constantExp;
6387                      }
6388                   }
6389                   break;
6390                case int64Type:
6391                   if(type.isSigned)
6392                   {
6393                      int64 value = 0;
6394                      if(GetInt64(e, &value))
6395                      {
6396                         FreeExpContents(exp);
6397                         exp.constant = PrintInt64(value);
6398                         exp.type = constantExp;
6399                      }
6400                   }
6401                   else
6402                   {
6403                      uint64 value = 0;
6404                      if(GetUInt64(e, &value))
6405                      {
6406                         FreeExpContents(exp);
6407                         exp.constant = PrintUInt64(value);
6408                         exp.type = constantExp;
6409                      }
6410                   }
6411                   break;
6412                case intPtrType:
6413                   if(type.isSigned)
6414                   {
6415                      intptr value = 0;
6416                      if(GetIntPtr(e, &value))
6417                      {
6418                         FreeExpContents(exp);
6419                         exp.constant = PrintInt64((int64)value);
6420                         exp.type = constantExp;
6421                      }
6422                   }
6423                   else
6424                   {
6425                      uintptr value = 0;
6426                      if(GetUIntPtr(e, &value))
6427                      {
6428                         FreeExpContents(exp);
6429                         exp.constant = PrintUInt64((uint64)value);
6430                         exp.type = constantExp;
6431                      }
6432                   }
6433                   break;
6434                case intSizeType:
6435                   if(type.isSigned)
6436                   {
6437                      intsize value = 0;
6438                      if(GetIntSize(e, &value))
6439                      {
6440                         FreeExpContents(exp);
6441                         exp.constant = PrintInt64((int64)value);
6442                         exp.type = constantExp;
6443                      }
6444                   }
6445                   else
6446                   {
6447                      uintsize value = 0;
6448                      if(GetUIntSize(e, &value))
6449                      {
6450                         FreeExpContents(exp);
6451                         exp.constant = PrintUInt64((uint64)value);
6452                         exp.type = constantExp;
6453                      }
6454                   }
6455                   break;
6456                case floatType:
6457                {
6458                   float value = 0;
6459                   if(GetFloat(e, &value))
6460                   {
6461                      FreeExpContents(exp);
6462                      exp.constant = PrintFloat(value);
6463                      exp.type = constantExp;
6464                   }
6465                   break;
6466                }
6467                case doubleType:
6468                {
6469                   double value = 0;
6470                   if(GetDouble(e, &value))
6471                   {
6472                      FreeExpContents(exp);
6473                      exp.constant = PrintDouble(value);
6474                      exp.type = constantExp;
6475                   }
6476                   break;
6477                }
6478             }
6479          }
6480          break;
6481       }
6482       case conditionExp:
6483       {
6484          Operand op1 { };
6485          Operand op2 { };
6486          Operand op3 { };
6487
6488          if(exp.cond.exp)
6489             // Caring only about last expression for now...
6490             ComputeExpression(exp.cond.exp->last);
6491          if(exp.cond.elseExp)
6492             ComputeExpression(exp.cond.elseExp);
6493          if(exp.cond.cond)
6494             ComputeExpression(exp.cond.cond);
6495
6496          op1 = GetOperand(exp.cond.cond);
6497          if(op1.type) op1.type.refCount++;
6498          op2 = GetOperand(exp.cond.exp->last);
6499          if(op2.type) op2.type.refCount++;
6500          op3 = GetOperand(exp.cond.elseExp);
6501          if(op3.type) op3.type.refCount++;
6502
6503          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6504          if(op1.type) FreeType(op1.type);
6505          if(op2.type) FreeType(op2.type);
6506          if(op3.type) FreeType(op3.type);
6507          break;
6508       }
6509    }
6510 }
6511
6512 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6513 {
6514    bool result = true;
6515    if(destType)
6516    {
6517       OldList converts { };
6518       Conversion convert;
6519
6520       if(destType.kind == voidType)
6521          return false;
6522
6523       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6524          result = false;
6525       if(converts.count)
6526       {
6527          // for(convert = converts.last; convert; convert = convert.prev)
6528          for(convert = converts.first; convert; convert = convert.next)
6529          {
6530             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6531             if(!empty)
6532             {
6533                Expression newExp { };
6534                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6535
6536                // TODO: Check this...
6537                *newExp = *exp;
6538                newExp.prev = null;
6539                newExp.next = null;
6540                newExp.destType = null;
6541
6542                if(convert.isGet)
6543                {
6544                   // [exp].ColorRGB
6545                   exp.type = memberExp;
6546                   exp.addedThis = true;
6547                   exp.member.exp = newExp;
6548                   FreeType(exp.member.exp.expType);
6549
6550                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6551                   exp.member.exp.expType.classObjectType = objectType;
6552                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6553                   exp.member.memberType = propertyMember;
6554                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6555                   // TESTING THIS... for (int)degrees
6556                   exp.needCast = true;
6557                   if(exp.expType) exp.expType.refCount++;
6558                   ApplyAnyObjectLogic(exp.member.exp);
6559                }
6560                else
6561                {
6562
6563                   /*if(exp.isConstant)
6564                   {
6565                      // Color { ColorRGB = [exp] };
6566                      exp.type = instanceExp;
6567                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6568                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6569                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6570                   }
6571                   else*/
6572                   {
6573                      // If not constant, don't turn it yet into an instantiation
6574                      // (Go through the deep members system first)
6575                      exp.type = memberExp;
6576                      exp.addedThis = true;
6577                      exp.member.exp = newExp;
6578
6579                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6580                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6581                         newExp.expType._class.registered.type == noHeadClass)
6582                      {
6583                         newExp.byReference = true;
6584                      }
6585
6586                      FreeType(exp.member.exp.expType);
6587                      /*exp.member.exp.expType = convert.convert.dataType;
6588                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6589                      exp.member.exp.expType = null;
6590                      if(convert.convert.dataType)
6591                      {
6592                         exp.member.exp.expType = { };
6593                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6594                         exp.member.exp.expType.refCount = 1;
6595                         exp.member.exp.expType.classObjectType = objectType;
6596                         ApplyAnyObjectLogic(exp.member.exp);
6597                      }
6598
6599                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6600                      exp.member.memberType = reverseConversionMember;
6601                      exp.expType = convert.resultType ? convert.resultType :
6602                         MkClassType(convert.convert._class.fullName);
6603                      exp.needCast = true;
6604                      if(convert.resultType) convert.resultType.refCount++;
6605                   }
6606                }
6607             }
6608             else
6609             {
6610                FreeType(exp.expType);
6611                if(convert.isGet)
6612                {
6613                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6614                   if(exp.destType.casted)
6615                      exp.needCast = true;
6616                   if(exp.expType) exp.expType.refCount++;
6617                }
6618                else
6619                {
6620                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6621                   if(exp.destType.casted)
6622                      exp.needCast = true;
6623                   if(convert.resultType)
6624                      convert.resultType.refCount++;
6625                }
6626             }
6627          }
6628          if(exp.isConstant && inCompiler)
6629             ComputeExpression(exp);
6630
6631          converts.Free(FreeConvert);
6632       }
6633
6634       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6635       {
6636          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6637       }
6638       if(!result && exp.expType && exp.destType)
6639       {
6640          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6641              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6642             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6643             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6644             result = true;
6645       }
6646    }
6647    // if(result) CheckTemplateTypes(exp);
6648    return result;
6649 }
6650
6651 void CheckTemplateTypes(Expression exp)
6652 {
6653    Expression nbExp = GetNonBracketsExp(exp);
6654    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6655       (nbExp == exp || nbExp.type != castExp))
6656    {
6657       Expression newExp { };
6658       Context context;
6659       *newExp = *exp;
6660       if(exp.destType) exp.destType.refCount++;
6661       if(exp.expType)  exp.expType.refCount++;
6662       newExp.prev = null;
6663       newExp.next = null;
6664
6665       switch(exp.expType.kind)
6666       {
6667          case doubleType:
6668             if(exp.destType.classObjectType)
6669             {
6670                // We need to pass the address, just pass it along (Undo what was done above)
6671                if(exp.destType) exp.destType.refCount--;
6672                if(exp.expType)  exp.expType.refCount--;
6673                delete newExp;
6674             }
6675             else
6676             {
6677                // If we're looking for value:
6678                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6679                OldList * specs;
6680                OldList * unionDefs = MkList();
6681                OldList * statements = MkList();
6682                context = PushContext();
6683                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6684                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6685                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6686                exp.type = extensionCompoundExp;
6687                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6688                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6689                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6690                exp.compound.compound.context = context;
6691                PopContext(context);
6692             }
6693             break;
6694          default:
6695             exp.type = castExp;
6696             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6697             if(exp.expType.isPointerType)
6698                exp.cast.exp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), MkExpBrackets(MkListOne(newExp)));
6699             else
6700                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6701             exp.needCast = true;
6702             break;
6703       }
6704    }
6705    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6706    {
6707       Expression newExp { };
6708       Context context;
6709       *newExp = *exp;
6710       if(exp.destType) exp.destType.refCount++;
6711       if(exp.expType)  exp.expType.refCount++;
6712       newExp.prev = null;
6713       newExp.next = null;
6714
6715       switch(exp.expType.kind)
6716       {
6717          case doubleType:
6718             if(exp.destType.classObjectType)
6719             {
6720                // We need to pass the address, just pass it along (Undo what was done above)
6721                if(exp.destType) exp.destType.refCount--;
6722                if(exp.expType)  exp.expType.refCount--;
6723                delete newExp;
6724             }
6725             else
6726             {
6727                // If we're looking for value:
6728                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6729                OldList * specs;
6730                OldList * unionDefs = MkList();
6731                OldList * statements = MkList();
6732                context = PushContext();
6733                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6734                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6735                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6736                exp.type = extensionCompoundExp;
6737                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6738                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6739                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6740                exp.compound.compound.context = context;
6741                PopContext(context);
6742             }
6743             break;
6744          case classType:
6745          {
6746             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6747             {
6748                exp.type = bracketsExp;
6749
6750                if(exp.expType.isPointerType)
6751                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6752                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6753                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6754                ProcessExpressionType(exp.list->first);
6755                break;
6756             }
6757             else
6758             {
6759                exp.type = bracketsExp;
6760                if(exp.expType.isPointerType)
6761                {
6762                   exp.needTemplateCast = 2;
6763                   newExp.needCast = true;
6764                   newExp.needTemplateCast = 2;
6765                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6766                }
6767
6768                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6769                exp.needTemplateCast = 2;
6770                newExp.needCast = true;
6771                newExp.needTemplateCast = 2;
6772                ProcessExpressionType(exp.list->first);
6773                break;
6774             }
6775          }
6776          default:
6777          {
6778             if(exp.expType.kind == templateType)
6779             {
6780                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6781                if(type)
6782                {
6783                   FreeType(exp.destType);
6784                   FreeType(exp.expType);
6785                   delete newExp;
6786                   break;
6787                }
6788             }
6789             if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6790             {
6791                exp.type = opExp;
6792                exp.op.op = '*';
6793                exp.op.exp1 = null;
6794                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6795                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6796             }
6797             else
6798             {
6799                char typeString[1024];
6800                Declarator decl;
6801                OldList * specs = MkList();
6802                typeString[0] = '\0';
6803                PrintType(exp.expType, typeString, false, false);
6804                decl = SpecDeclFromString(typeString, specs, null);
6805
6806                exp.type = castExp;
6807                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6808                exp.cast.typeName = MkTypeName(specs, decl);
6809                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6810                exp.cast.exp.needCast = true;
6811             }
6812             break;
6813          }
6814       }
6815    }
6816 }
6817 // TODO: The Symbol tree should be reorganized by namespaces
6818 // Name Space:
6819 //    - Tree of all symbols within (stored without namespace)
6820 //    - Tree of sub-namespaces
6821
6822 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6823 {
6824    int nsLen = strlen(nameSpace);
6825    Symbol symbol;
6826    // Start at the name space prefix
6827    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6828    {
6829       char * s = symbol.string;
6830       if(!strncmp(s, nameSpace, nsLen))
6831       {
6832          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6833          int c;
6834          char * namePart;
6835          for(c = strlen(s)-1; c >= 0; c--)
6836             if(s[c] == ':')
6837                break;
6838
6839          namePart = s+c+1;
6840          if(!strcmp(namePart, name))
6841          {
6842             // TODO: Error on ambiguity
6843             return symbol;
6844          }
6845       }
6846       else
6847          break;
6848    }
6849    return null;
6850 }
6851
6852 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6853 {
6854    int c;
6855    char nameSpace[1024];
6856    const char * namePart;
6857    bool gotColon = false;
6858
6859    nameSpace[0] = '\0';
6860    for(c = strlen(name)-1; c >= 0; c--)
6861       if(name[c] == ':')
6862       {
6863          gotColon = true;
6864          break;
6865       }
6866
6867    namePart = name+c+1;
6868    while(c >= 0 && name[c] == ':') c--;
6869    if(c >= 0)
6870    {
6871       // Try an exact match first
6872       Symbol symbol = (Symbol)tree.FindString(name);
6873       if(symbol)
6874          return symbol;
6875
6876       // Namespace specified
6877       memcpy(nameSpace, name, c + 1);
6878       nameSpace[c+1] = 0;
6879
6880       return ScanWithNameSpace(tree, nameSpace, namePart);
6881    }
6882    else if(gotColon)
6883    {
6884       // Looking for a global symbol, e.g. ::Sleep()
6885       Symbol symbol = (Symbol)tree.FindString(namePart);
6886       return symbol;
6887    }
6888    else
6889    {
6890       // Name only (no namespace specified)
6891       Symbol symbol = (Symbol)tree.FindString(namePart);
6892       if(symbol)
6893          return symbol;
6894       return ScanWithNameSpace(tree, "", namePart);
6895    }
6896    return null;
6897 }
6898
6899 static void ProcessDeclaration(Declaration decl);
6900
6901 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6902 {
6903 #ifdef _DEBUG
6904    //Time startTime = GetTime();
6905 #endif
6906    // Optimize this later? Do this before/less?
6907    Context ctx;
6908    Symbol symbol = null;
6909    // First, check if the identifier is declared inside the function
6910    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6911
6912    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6913    {
6914       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6915       {
6916          symbol = null;
6917          if(thisNameSpace)
6918          {
6919             char curName[1024];
6920             strcpy(curName, thisNameSpace);
6921             strcat(curName, "::");
6922             strcat(curName, name);
6923             // Try to resolve in current namespace first
6924             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6925          }
6926          if(!symbol)
6927             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6928       }
6929       else
6930          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6931
6932       if(symbol || ctx == endContext) break;
6933    }
6934    if(inCompiler && curExternal && symbol && ctx == globalContext && curExternal.symbol && symbol.id > curExternal.symbol.idCode && symbol.pointerExternal)
6935    {
6936       if(symbol.pointerExternal.type == functionExternal)
6937       {
6938          FunctionDefinition function = symbol.pointerExternal.function;
6939
6940          // Modified this recently...
6941          Context tmpContext = curContext;
6942          curContext = null;
6943          symbol.pointerExternal = MkExternalDeclaration(MkDeclaration(CopyList(function.specifiers, CopySpecifier), MkListOne(MkInitDeclarator(CopyDeclarator(function.declarator), null))));
6944          curContext = tmpContext;
6945
6946          symbol.pointerExternal.symbol = symbol;
6947
6948          // TESTING THIS:
6949          DeclareType(symbol.type, true, true);
6950
6951          ast->Insert(curExternal.prev, symbol.pointerExternal);
6952
6953          symbol.id = curExternal.symbol.idCode;
6954
6955       }
6956       else if(symbol.pointerExternal.type == declarationExternal && curExternal.symbol.idCode < symbol.pointerExternal.symbol.id) // Added id comparison because Global Function prototypes were broken
6957       {
6958          ast->Move(symbol.pointerExternal, curExternal.prev);
6959          symbol.id = curExternal.symbol.idCode;
6960       }
6961    }
6962 #ifdef _DEBUG
6963    //findSymbolTotalTime += GetTime() - startTime;
6964 #endif
6965    return symbol;
6966 }
6967
6968 static void GetTypeSpecs(Type type, OldList * specs)
6969 {
6970    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6971    switch(type.kind)
6972    {
6973       case classType:
6974       {
6975          if(type._class.registered)
6976          {
6977             if(!type._class.registered.dataType)
6978                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6979             GetTypeSpecs(type._class.registered.dataType, specs);
6980          }
6981          break;
6982       }
6983       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6984       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6985       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6986       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6987       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6988       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6989       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6990       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6991       case intType:
6992       default:
6993          ListAdd(specs, MkSpecifier(INT)); break;
6994    }
6995 }
6996
6997 static void PrintArraySize(Type arrayType, char * string)
6998 {
6999    char size[256];
7000    size[0] = '\0';
7001    strcat(size, "[");
7002    if(arrayType.enumClass)
7003       strcat(size, arrayType.enumClass.string);
7004    else if(arrayType.arraySizeExp)
7005       PrintExpression(arrayType.arraySizeExp, size);
7006    strcat(size, "]");
7007    strcat(string, size);
7008 }
7009
7010 // WARNING : This function expects a null terminated string since it recursively concatenate...
7011 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
7012 {
7013    if(type)
7014    {
7015       if(printConst && type.constant)
7016          strcat(string, "const ");
7017       switch(type.kind)
7018       {
7019          case classType:
7020          {
7021             Symbol c = type._class;
7022             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
7023             //       look into merging with thisclass ?
7024             if(type.classObjectType == typedObject)
7025                strcat(string, "typed_object");
7026             else if(type.classObjectType == anyObject)
7027                strcat(string, "any_object");
7028             else
7029             {
7030                if(c && c.string)
7031                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
7032             }
7033             if(type.byReference)
7034                strcat(string, " &");
7035             break;
7036          }
7037          case voidType: strcat(string, "void"); break;
7038          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
7039          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
7040          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
7041          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
7042          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
7043          case _BoolType: strcat(string, "_Bool"); break;
7044          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
7045          case floatType: strcat(string, "float"); break;
7046          case doubleType: strcat(string, "double"); break;
7047          case structType:
7048             if(type.enumName)
7049             {
7050                strcat(string, "struct ");
7051                strcat(string, type.enumName);
7052             }
7053             else if(type.typeName)
7054                strcat(string, type.typeName);
7055             else
7056             {
7057                Type member;
7058                strcat(string, "struct { ");
7059                for(member = type.members.first; member; member = member.next)
7060                {
7061                   PrintType(member, string, true, fullName);
7062                   strcat(string,"; ");
7063                }
7064                strcat(string,"}");
7065             }
7066             break;
7067          case unionType:
7068             if(type.enumName)
7069             {
7070                strcat(string, "union ");
7071                strcat(string, type.enumName);
7072             }
7073             else if(type.typeName)
7074                strcat(string, type.typeName);
7075             else
7076             {
7077                strcat(string, "union ");
7078                strcat(string,"(unnamed)");
7079             }
7080             break;
7081          case enumType:
7082             if(type.enumName)
7083             {
7084                strcat(string, "enum ");
7085                strcat(string, type.enumName);
7086             }
7087             else if(type.typeName)
7088                strcat(string, type.typeName);
7089             else
7090                strcat(string, "int"); // "enum");
7091             break;
7092          case ellipsisType:
7093             strcat(string, "...");
7094             break;
7095          case subClassType:
7096             strcat(string, "subclass(");
7097             strcat(string, type._class ? type._class.string : "int");
7098             strcat(string, ")");
7099             break;
7100          case templateType:
7101             strcat(string, type.templateParameter.identifier.string);
7102             break;
7103          case thisClassType:
7104             strcat(string, "thisclass");
7105             break;
7106          case vaListType:
7107             strcat(string, "__builtin_va_list");
7108             break;
7109       }
7110    }
7111 }
7112
7113 static void PrintName(Type type, char * string, bool fullName)
7114 {
7115    if(type.name && type.name[0])
7116    {
7117       if(fullName)
7118          strcat(string, type.name);
7119       else
7120       {
7121          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
7122          if(name) name += 2; else name = type.name;
7123          strcat(string, name);
7124       }
7125    }
7126 }
7127
7128 static void PrintAttribs(Type type, char * string)
7129 {
7130    if(type)
7131    {
7132       if(type.dllExport)   strcat(string, "dllexport ");
7133       if(type.attrStdcall) strcat(string, "stdcall ");
7134    }
7135 }
7136
7137 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
7138 {
7139    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7140    {
7141       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
7142          PrintAttribs(type, string);
7143       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
7144          strcat(string, " const");
7145       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
7146       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7147          strcat(string, " (");
7148       if(type.kind == pointerType)
7149       {
7150          if(type.type.kind == functionType || type.type.kind == methodType)
7151             PrintAttribs(type.type, string);
7152       }
7153       if(type.kind == pointerType)
7154       {
7155          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7156             strcat(string, "*");
7157          else
7158             strcat(string, " *");
7159       }
7160       if(printConst && type.constant && type.kind == pointerType)
7161          strcat(string, " const");
7162    }
7163    else
7164       PrintTypeSpecs(type, string, fullName, printConst);
7165 }
7166
7167 static void PostPrintType(Type type, char * string, bool fullName)
7168 {
7169    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7170       strcat(string, ")");
7171    if(type.kind == arrayType)
7172       PrintArraySize(type, string);
7173    else if(type.kind == functionType)
7174    {
7175       Type param;
7176       strcat(string, "(");
7177       for(param = type.params.first; param; param = param.next)
7178       {
7179          PrintType(param, string, true, fullName);
7180          if(param.next) strcat(string, ", ");
7181       }
7182       strcat(string, ")");
7183    }
7184    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7185       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7186 }
7187
7188 // *****
7189 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7190 // *****
7191 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7192 {
7193    PrePrintType(type, string, fullName, null, printConst);
7194
7195    if(type.thisClass || (printName && type.name && type.name[0]))
7196       strcat(string, " ");
7197    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7198    {
7199       Symbol _class = type.thisClass;
7200       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7201       {
7202          if(type.classObjectType == classPointer)
7203             strcat(string, "class");
7204          else
7205             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7206       }
7207       else if(_class && _class.string)
7208       {
7209          String s = _class.string;
7210          if(fullName)
7211             strcat(string, s);
7212          else
7213          {
7214             char * name = RSearchString(s, "::", strlen(s), true, false);
7215             if(name) name += 2; else name = s;
7216             strcat(string, name);
7217          }
7218       }
7219       strcat(string, "::");
7220    }
7221
7222    if(printName && type.name)
7223       PrintName(type, string, fullName);
7224    PostPrintType(type, string, fullName);
7225    if(type.bitFieldCount)
7226    {
7227       char count[100];
7228       sprintf(count, ":%d", type.bitFieldCount);
7229       strcat(string, count);
7230    }
7231 }
7232
7233 void PrintType(Type type, char * string, bool printName, bool fullName)
7234 {
7235    _PrintType(type, string, printName, fullName, true);
7236 }
7237
7238 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7239 {
7240    _PrintType(type, string, printName, fullName, false);
7241 }
7242
7243 static Type FindMember(Type type, char * string)
7244 {
7245    Type memberType;
7246    for(memberType = type.members.first; memberType; memberType = memberType.next)
7247    {
7248       if(!memberType.name)
7249       {
7250          Type subType = FindMember(memberType, string);
7251          if(subType)
7252             return subType;
7253       }
7254       else if(!strcmp(memberType.name, string))
7255          return memberType;
7256    }
7257    return null;
7258 }
7259
7260 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7261 {
7262    Type memberType;
7263    for(memberType = type.members.first; memberType; memberType = memberType.next)
7264    {
7265       if(!memberType.name)
7266       {
7267          Type subType = FindMember(memberType, string);
7268          if(subType)
7269          {
7270             *offset += memberType.offset;
7271             return subType;
7272          }
7273       }
7274       else if(!strcmp(memberType.name, string))
7275       {
7276          *offset += memberType.offset;
7277          return memberType;
7278       }
7279    }
7280    return null;
7281 }
7282
7283 public bool GetParseError() { return parseError; }
7284
7285 Expression ParseExpressionString(char * expression)
7286 {
7287    parseError = false;
7288
7289    fileInput = TempFile { };
7290    fileInput.Write(expression, 1, strlen(expression));
7291    fileInput.Seek(0, start);
7292
7293    echoOn = false;
7294    parsedExpression = null;
7295    resetScanner();
7296    expression_yyparse();
7297    delete fileInput;
7298
7299    return parsedExpression;
7300 }
7301
7302 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7303 {
7304    Identifier id = exp.identifier;
7305    Method method = null;
7306    Property prop = null;
7307    DataMember member = null;
7308    ClassProperty classProp = null;
7309
7310    if(_class && _class.type == enumClass)
7311    {
7312       NamedLink64 value = null;
7313       Class enumClass = eSystem_FindClass(privateModule, "enum");
7314       if(enumClass)
7315       {
7316          Class baseClass;
7317          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7318          {
7319             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7320             for(value = e.values.first; value; value = value.next)
7321             {
7322                if(!strcmp(value.name, id.string))
7323                   break;
7324             }
7325             if(value)
7326             {
7327                exp.isConstant = true;
7328                if(inCompiler || inPreCompiler || inDebugger)
7329                {
7330                   char constant[256];
7331                   FreeExpContents(exp);
7332
7333                   exp.type = constantExp;
7334                   if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7335                      sprintf(constant, FORMAT64D, value.data);
7336                   else
7337                      sprintf(constant, FORMAT64HEX, value.data);
7338                   exp.constant = CopyString(constant);
7339                }
7340                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7341                exp.expType = MkClassType(baseClass.fullName);
7342                break;
7343             }
7344          }
7345       }
7346       if(value)
7347          return true;
7348    }
7349    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7350    {
7351       ProcessMethodType(method);
7352       exp.expType = Type
7353       {
7354          refCount = 1;
7355          kind = methodType;
7356          method = method;
7357          // Crash here?
7358          // TOCHECK: Put it back to what it was...
7359          // methodClass = _class;
7360          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7361       };
7362       //id._class = null;
7363       return true;
7364    }
7365    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7366    {
7367       if(!prop.dataType)
7368          ProcessPropertyType(prop);
7369       exp.expType = prop.dataType;
7370       if(prop.dataType) prop.dataType.refCount++;
7371       return true;
7372    }
7373    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7374    {
7375       if(!member.dataType)
7376          member.dataType = ProcessTypeString(member.dataTypeString, false);
7377       exp.expType = member.dataType;
7378       if(member.dataType) member.dataType.refCount++;
7379       return true;
7380    }
7381    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7382    {
7383       if(!classProp.dataType)
7384          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7385
7386       if(classProp.constant)
7387       {
7388          FreeExpContents(exp);
7389
7390          exp.isConstant = true;
7391          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7392          {
7393             //char constant[256];
7394             exp.type = stringExp;
7395             exp.constant = QMkString((char *)(uintptr)classProp.Get(_class));
7396          }
7397          else
7398          {
7399             char constant[256];
7400             exp.type = constantExp;
7401             sprintf(constant, "%d", (int)classProp.Get(_class));
7402             exp.constant = CopyString(constant);
7403          }
7404       }
7405       else
7406       {
7407          // TO IMPLEMENT...
7408       }
7409
7410       exp.expType = classProp.dataType;
7411       if(classProp.dataType) classProp.dataType.refCount++;
7412       return true;
7413    }
7414    return false;
7415 }
7416
7417 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7418 {
7419    BinaryTree * tree = &nameSpace.functions;
7420    GlobalData data = (GlobalData)tree->FindString(name);
7421    NameSpace * child;
7422    if(!data)
7423    {
7424       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7425       {
7426          data = ScanGlobalData(child, name);
7427          if(data)
7428             break;
7429       }
7430    }
7431    return data;
7432 }
7433
7434 static GlobalData FindGlobalData(char * name)
7435 {
7436    int start = 0, c;
7437    NameSpace * nameSpace;
7438    nameSpace = globalData;
7439    for(c = 0; name[c]; c++)
7440    {
7441       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7442       {
7443          NameSpace * newSpace;
7444          char * spaceName = new char[c - start + 1];
7445          strncpy(spaceName, name + start, c - start);
7446          spaceName[c-start] = '\0';
7447          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7448          delete spaceName;
7449          if(!newSpace)
7450             return null;
7451          nameSpace = newSpace;
7452          if(name[c] == ':') c++;
7453          start = c+1;
7454       }
7455    }
7456    if(c - start)
7457    {
7458       return ScanGlobalData(nameSpace, name + start);
7459    }
7460    return null;
7461 }
7462
7463 static int definedExpStackPos;
7464 static void * definedExpStack[512];
7465
7466 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7467 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7468 {
7469    Expression prev = checkedExp.prev, next = checkedExp.next;
7470
7471    FreeExpContents(checkedExp);
7472    FreeType(checkedExp.expType);
7473    FreeType(checkedExp.destType);
7474
7475    *checkedExp = *newExp;
7476
7477    delete newExp;
7478
7479    checkedExp.prev = prev;
7480    checkedExp.next = next;
7481 }
7482
7483 void ApplyAnyObjectLogic(Expression e)
7484 {
7485    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7486 #ifdef _DEBUG
7487    char debugExpString[4096];
7488    debugExpString[0] = '\0';
7489    PrintExpression(e, debugExpString);
7490 #endif
7491
7492    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7493    {
7494       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7495       //ellipsisDestType = destType;
7496       if(e && e.expType)
7497       {
7498          Type type = e.expType;
7499          Class _class = null;
7500          //Type destType = e.destType;
7501
7502          if(type.kind == classType && type._class && type._class.registered)
7503          {
7504             _class = type._class.registered;
7505          }
7506          else if(type.kind == subClassType)
7507          {
7508             _class = FindClass("ecere::com::Class").registered;
7509          }
7510          else
7511          {
7512             char string[1024] = "";
7513             Symbol classSym;
7514
7515             PrintTypeNoConst(type, string, false, true);
7516             classSym = FindClass(string);
7517             if(classSym) _class = classSym.registered;
7518          }
7519
7520          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...
7521             (!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))) ||
7522             destType.byReference)))
7523          {
7524             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7525             {
7526                Expression checkedExp = e, newExp;
7527
7528                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7529                {
7530                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7531                   {
7532                      if(checkedExp.type == extensionCompoundExp)
7533                      {
7534                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7535                      }
7536                      else
7537                         checkedExp = checkedExp.list->last;
7538                   }
7539                   else if(checkedExp.type == castExp)
7540                      checkedExp = checkedExp.cast.exp;
7541                }
7542
7543                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7544                {
7545                   newExp = checkedExp.op.exp2;
7546                   checkedExp.op.exp2 = null;
7547                   FreeExpContents(checkedExp);
7548
7549                   if(e.expType && e.expType.passAsTemplate)
7550                   {
7551                      char size[100];
7552                      ComputeTypeSize(e.expType);
7553                      sprintf(size, "%d", e.expType.size);
7554                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7555                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7556                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7557                   }
7558
7559                   ReplaceExpContents(checkedExp, newExp);
7560                   e.byReference = true;
7561                }
7562                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7563                {
7564                   Expression checkedExp; //, newExp;
7565
7566                   {
7567                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7568                      bool hasAddress =
7569                         e.type == identifierExp ||
7570                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7571                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7572                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7573                         e.type == indexExp;
7574
7575                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7576                      {
7577                         Context context = PushContext();
7578                         Declarator decl;
7579                         OldList * specs = MkList();
7580                         char typeString[1024];
7581                         Expression newExp { };
7582
7583                         typeString[0] = '\0';
7584                         *newExp = *e;
7585
7586                         //if(e.destType) e.destType.refCount++;
7587                         // if(exp.expType) exp.expType.refCount++;
7588                         newExp.prev = null;
7589                         newExp.next = null;
7590                         newExp.expType = null;
7591
7592                         PrintTypeNoConst(e.expType, typeString, false, true);
7593                         decl = SpecDeclFromString(typeString, specs, null);
7594                         newExp.destType = ProcessType(specs, decl);
7595
7596                         curContext = context;
7597
7598                         // We need a current compound for this
7599                         if(curCompound)
7600                         {
7601                            char name[100];
7602                            OldList * stmts = MkList();
7603                            e.type = extensionCompoundExp;
7604                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7605                            if(!curCompound.compound.declarations)
7606                               curCompound.compound.declarations = MkList();
7607                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7608                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7609                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7610                            e.compound = MkCompoundStmt(null, stmts);
7611                         }
7612                         else
7613                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7614
7615                         /*
7616                         e.compound = MkCompoundStmt(
7617                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7618                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7619
7620                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7621                         */
7622
7623                         {
7624                            Type type = e.destType;
7625                            e.destType = { };
7626                            CopyTypeInto(e.destType, type);
7627                            e.destType.refCount = 1;
7628                            e.destType.classObjectType = none;
7629                            FreeType(type);
7630                         }
7631
7632                         e.compound.compound.context = context;
7633                         PopContext(context);
7634                         curContext = context.parent;
7635                      }
7636                   }
7637
7638                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7639                   checkedExp = e;
7640                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7641                   {
7642                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7643                      {
7644                         if(checkedExp.type == extensionCompoundExp)
7645                         {
7646                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7647                         }
7648                         else
7649                            checkedExp = checkedExp.list->last;
7650                      }
7651                      else if(checkedExp.type == castExp)
7652                         checkedExp = checkedExp.cast.exp;
7653                   }
7654                   {
7655                      Expression operand { };
7656                      operand = *checkedExp;
7657                      checkedExp.Clear();
7658                      checkedExp.destType = ProcessTypeString("void *", false);
7659                      checkedExp.expType = checkedExp.destType;
7660                      checkedExp.destType.refCount++;
7661
7662                      checkedExp.type = opExp;
7663                      checkedExp.op.op = '&';
7664                      checkedExp.op.exp1 = null;
7665                      checkedExp.op.exp2 = operand;
7666
7667                      //newExp = MkExpOp(null, '&', checkedExp);
7668                   }
7669                   //ReplaceExpContents(checkedExp, newExp);
7670                }
7671             }
7672          }
7673       }
7674    }
7675    {
7676       // If expression type is a simple class, make it an address
7677       // FixReference(e, true);
7678    }
7679 //#if 0
7680    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7681       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7682          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7683    {
7684       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"))
7685       {
7686          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7687       }
7688       else
7689       {
7690          Expression thisExp { };
7691
7692          *thisExp = *e;
7693          thisExp.prev = null;
7694          thisExp.next = null;
7695          e.Clear();
7696
7697          e.type = bracketsExp;
7698          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7699          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7700             ((Expression)e.list->first).byReference = true;
7701
7702          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7703          {
7704             e.expType = thisExp.expType;
7705             e.expType.refCount++;
7706          }
7707          else*/
7708          {
7709             e.expType = { };
7710             CopyTypeInto(e.expType, thisExp.expType);
7711             e.expType.byReference = false;
7712             e.expType.refCount = 1;
7713
7714             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7715                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7716             {
7717                e.expType.classObjectType = none;
7718             }
7719          }
7720       }
7721    }
7722 // TOFIX: Try this for a nice IDE crash!
7723 //#endif
7724    // The other way around
7725    else
7726 //#endif
7727    if(destType && e.expType &&
7728          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7729          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7730          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7731    {
7732       if(destType.kind == ellipsisType)
7733       {
7734          Compiler_Error($"Unspecified type\n");
7735       }
7736       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7737       {
7738          bool byReference = e.expType.byReference;
7739          Expression thisExp { };
7740          Declarator decl;
7741          OldList * specs = MkList();
7742          char typeString[1024]; // Watch buffer overruns
7743          Type type;
7744          ClassObjectType backupClassObjectType;
7745          bool backupByReference;
7746
7747          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7748             type = e.expType;
7749          else
7750             type = destType;
7751
7752          backupClassObjectType = type.classObjectType;
7753          backupByReference = type.byReference;
7754
7755          type.classObjectType = none;
7756          type.byReference = false;
7757
7758          typeString[0] = '\0';
7759          PrintType(type, typeString, false, true);
7760          decl = SpecDeclFromString(typeString, specs, null);
7761
7762          type.classObjectType = backupClassObjectType;
7763          type.byReference = backupByReference;
7764
7765          *thisExp = *e;
7766          thisExp.prev = null;
7767          thisExp.next = null;
7768          e.Clear();
7769
7770          if( ( type.kind == classType && type._class && type._class.registered &&
7771                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7772                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7773              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7774              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7775          {
7776             e.type = opExp;
7777             e.op.op = '*';
7778             e.op.exp1 = null;
7779             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7780
7781             e.expType = { };
7782             CopyTypeInto(e.expType, type);
7783             e.expType.byReference = false;
7784             e.expType.refCount = 1;
7785          }
7786          else
7787          {
7788             e.type = castExp;
7789             e.cast.typeName = MkTypeName(specs, decl);
7790             e.cast.exp = thisExp;
7791             e.byReference = true;
7792             e.expType = type;
7793             type.refCount++;
7794          }
7795          e.destType = destType;
7796          destType.refCount++;
7797       }
7798    }
7799 }
7800
7801 void ApplyLocation(Expression exp, Location loc)
7802 {
7803    exp.loc = loc;
7804    switch(exp.type)
7805    {
7806       case opExp:
7807          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7808          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7809          break;
7810       case bracketsExp:
7811          if(exp.list)
7812          {
7813             Expression e;
7814             for(e = exp.list->first; e; e = e.next)
7815                ApplyLocation(e, loc);
7816          }
7817          break;
7818       case indexExp:
7819          if(exp.index.index)
7820          {
7821             Expression e;
7822             for(e = exp.index.index->first; e; e = e.next)
7823                ApplyLocation(e, loc);
7824          }
7825          if(exp.index.exp)
7826             ApplyLocation(exp.index.exp, loc);
7827          break;
7828       case callExp:
7829          if(exp.call.arguments)
7830          {
7831             Expression arg;
7832             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7833                ApplyLocation(arg, loc);
7834          }
7835          if(exp.call.exp)
7836             ApplyLocation(exp.call.exp, loc);
7837          break;
7838       case memberExp:
7839       case pointerExp:
7840          if(exp.member.exp)
7841             ApplyLocation(exp.member.exp, loc);
7842          break;
7843       case castExp:
7844          if(exp.cast.exp)
7845             ApplyLocation(exp.cast.exp, loc);
7846          break;
7847       case conditionExp:
7848          if(exp.cond.exp)
7849          {
7850             Expression e;
7851             for(e = exp.cond.exp->first; e; e = e.next)
7852                ApplyLocation(e, loc);
7853          }
7854          if(exp.cond.cond)
7855             ApplyLocation(exp.cond.cond, loc);
7856          if(exp.cond.elseExp)
7857             ApplyLocation(exp.cond.elseExp, loc);
7858          break;
7859       case vaArgExp:
7860          if(exp.vaArg.exp)
7861             ApplyLocation(exp.vaArg.exp, loc);
7862          break;
7863       default:
7864          break;
7865    }
7866 }
7867
7868 void ProcessExpressionType(Expression exp)
7869 {
7870    bool unresolved = false;
7871    Location oldyylloc = yylloc;
7872    bool notByReference = false;
7873 #ifdef _DEBUG
7874    char debugExpString[4096];
7875    debugExpString[0] = '\0';
7876    PrintExpression(exp, debugExpString);
7877 #endif
7878    if(!exp || exp.expType)
7879       return;
7880
7881    //eSystem_Logf("%s\n", expString);
7882
7883    // Testing this here
7884    yylloc = exp.loc;
7885    switch(exp.type)
7886    {
7887       case identifierExp:
7888       {
7889          Identifier id = exp.identifier;
7890          if(!id || !topContext) return;
7891
7892          // DOING THIS LATER NOW...
7893          if(id._class && id._class.name)
7894          {
7895             id.classSym = id._class.symbol; // FindClass(id._class.name);
7896             /* TODO: Name Space Fix ups
7897             if(!id.classSym)
7898                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7899             */
7900          }
7901
7902          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7903          {
7904             exp.expType = ProcessTypeString("Module", true);
7905             break;
7906          }
7907          else */
7908          if(!strcmp(id.string, "__runtimePlatform"))
7909          {
7910             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7911             break;
7912          }
7913          else if(strstr(id.string, "__ecereClass") == id.string)
7914          {
7915             exp.expType = ProcessTypeString("ecere::com::Class", true);
7916             break;
7917          }
7918          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7919          {
7920             // Added this here as well
7921             ReplaceClassMembers(exp, thisClass);
7922             if(exp.type != identifierExp)
7923             {
7924                ProcessExpressionType(exp);
7925                break;
7926             }
7927
7928             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7929                break;
7930          }
7931          else
7932          {
7933             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7934             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7935             if(!symbol/* && exp.destType*/)
7936             {
7937                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7938                   break;
7939                else
7940                {
7941                   if(thisClass)
7942                   {
7943                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7944                      if(exp.type != identifierExp)
7945                      {
7946                         ProcessExpressionType(exp);
7947                         break;
7948                      }
7949                   }
7950                   // Static methods called from inside the _class
7951                   else if(currentClass && !id._class)
7952                   {
7953                      if(ResolveIdWithClass(exp, currentClass, true))
7954                         break;
7955                   }
7956                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7957                }
7958             }
7959
7960             // If we manage to resolve this symbol
7961             if(symbol)
7962             {
7963                Type type = symbol.type;
7964                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7965
7966                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7967                {
7968                   Context context = SetupTemplatesContext(_class);
7969                   type = ReplaceThisClassType(_class);
7970                   FinishTemplatesContext(context);
7971                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7972                }
7973
7974                FreeSpecifier(id._class);
7975                id._class = null;
7976                delete id.string;
7977                id.string = CopyString(symbol.string);
7978
7979                id.classSym = null;
7980                exp.expType = type;
7981                if(type)
7982                   type.refCount++;
7983
7984                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7985                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7986                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7987                   // Add missing cases here... enum Classes...
7988                   exp.isConstant = true;
7989
7990                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7991                if(symbol.isParam || !strcmp(id.string, "this"))
7992                {
7993                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7994                      exp.byReference = true;
7995
7996                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7997                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7998                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7999                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
8000                   {
8001                      Identifier id = exp.identifier;
8002                      exp.type = bracketsExp;
8003                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
8004                   }*/
8005                }
8006
8007                if(symbol.isIterator)
8008                {
8009                   if(symbol.isIterator == 3)
8010                   {
8011                      exp.type = bracketsExp;
8012                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
8013                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
8014                      exp.expType = null;
8015                      ProcessExpressionType(exp);
8016                   }
8017                   else if(symbol.isIterator != 4)
8018                   {
8019                      exp.type = memberExp;
8020                      exp.member.exp = MkExpIdentifier(exp.identifier);
8021                      exp.member.exp.expType = exp.expType;
8022                      /*if(symbol.isIterator == 6)
8023                         exp.member.member = MkIdentifier("key");
8024                      else*/
8025                         exp.member.member = MkIdentifier("data");
8026                      exp.expType = null;
8027                      ProcessExpressionType(exp);
8028                   }
8029                }
8030                break;
8031             }
8032             else
8033             {
8034                DefinedExpression definedExp = null;
8035                if(thisNameSpace && !(id._class && !id._class.name))
8036                {
8037                   char name[1024];
8038                   strcpy(name, thisNameSpace);
8039                   strcat(name, "::");
8040                   strcat(name, id.string);
8041                   definedExp = eSystem_FindDefine(privateModule, name);
8042                }
8043                if(!definedExp)
8044                   definedExp = eSystem_FindDefine(privateModule, id.string);
8045                if(definedExp)
8046                {
8047                   int c;
8048                   for(c = 0; c<definedExpStackPos; c++)
8049                      if(definedExpStack[c] == definedExp)
8050                         break;
8051                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
8052                   {
8053                      Location backupYylloc = yylloc;
8054                      File backInput = fileInput;
8055                      definedExpStack[definedExpStackPos++] = definedExp;
8056
8057                      fileInput = TempFile { };
8058                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
8059                      fileInput.Seek(0, start);
8060
8061                      echoOn = false;
8062                      parsedExpression = null;
8063                      resetScanner();
8064                      expression_yyparse();
8065                      delete fileInput;
8066                      if(backInput)
8067                         fileInput = backInput;
8068
8069                      yylloc = backupYylloc;
8070
8071                      if(parsedExpression)
8072                      {
8073                         FreeIdentifier(id);
8074                         exp.type = bracketsExp;
8075                         exp.list = MkListOne(parsedExpression);
8076                         ApplyLocation(parsedExpression, yylloc);
8077                         ProcessExpressionType(exp);
8078                         definedExpStackPos--;
8079                         return;
8080                      }
8081                      definedExpStackPos--;
8082                   }
8083                   else
8084                   {
8085                      if(inCompiler)
8086                      {
8087                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
8088                      }
8089                   }
8090                }
8091                else
8092                {
8093                   GlobalData data = null;
8094                   if(thisNameSpace && !(id._class && !id._class.name))
8095                   {
8096                      char name[1024];
8097                      strcpy(name, thisNameSpace);
8098                      strcat(name, "::");
8099                      strcat(name, id.string);
8100                      data = FindGlobalData(name);
8101                   }
8102                   if(!data)
8103                      data = FindGlobalData(id.string);
8104                   if(data)
8105                   {
8106                      DeclareGlobalData(data);
8107                      exp.expType = data.dataType;
8108                      if(data.dataType) data.dataType.refCount++;
8109
8110                      delete id.string;
8111                      id.string = CopyString(data.fullName);
8112                      FreeSpecifier(id._class);
8113                      id._class = null;
8114
8115                      break;
8116                   }
8117                   else
8118                   {
8119                      GlobalFunction function = null;
8120                      if(thisNameSpace && !(id._class && !id._class.name))
8121                      {
8122                         char name[1024];
8123                         strcpy(name, thisNameSpace);
8124                         strcat(name, "::");
8125                         strcat(name, id.string);
8126                         function = eSystem_FindFunction(privateModule, name);
8127                      }
8128                      if(!function)
8129                         function = eSystem_FindFunction(privateModule, id.string);
8130                      if(function)
8131                      {
8132                         char name[1024];
8133                         delete id.string;
8134                         id.string = CopyString(function.name);
8135                         name[0] = 0;
8136
8137                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8138                            strcpy(name, "__ecereFunction_");
8139                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8140                         if(DeclareFunction(function, name))
8141                         {
8142                            delete id.string;
8143                            id.string = CopyString(name);
8144                         }
8145                         exp.expType = function.dataType;
8146                         if(function.dataType) function.dataType.refCount++;
8147
8148                         FreeSpecifier(id._class);
8149                         id._class = null;
8150
8151                         break;
8152                      }
8153                   }
8154                }
8155             }
8156          }
8157          unresolved = true;
8158          break;
8159       }
8160       case instanceExp:
8161       {
8162          // Class _class;
8163          // Symbol classSym;
8164
8165          if(!exp.instance._class)
8166          {
8167             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8168             {
8169                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8170             }
8171          }
8172
8173          //classSym = FindClass(exp.instance._class.fullName);
8174          //_class = classSym ? classSym.registered : null;
8175
8176          ProcessInstantiationType(exp.instance);
8177
8178          exp.isConstant = exp.instance.isConstant;
8179
8180          /*
8181          if(_class.type == unitClass && _class.base.type != systemClass)
8182          {
8183             {
8184                Type destType = exp.destType;
8185
8186                exp.destType = MkClassType(_class.base.fullName);
8187                exp.expType = MkClassType(_class.fullName);
8188                CheckExpressionType(exp, exp.destType, true);
8189
8190                exp.destType = destType;
8191             }
8192             exp.expType = MkClassType(_class.fullName);
8193          }
8194          else*/
8195          if(exp.instance._class)
8196          {
8197             exp.expType = MkClassType(exp.instance._class.name);
8198             /*if(exp.expType._class && exp.expType._class.registered &&
8199                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8200                exp.expType.byReference = true;*/
8201          }
8202          break;
8203       }
8204       case constantExp:
8205       {
8206          if(!exp.expType)
8207          {
8208             char * constant = exp.constant;
8209             Type type
8210             {
8211                refCount = 1;
8212                constant = true;
8213             };
8214             exp.expType = type;
8215
8216             if(constant[0] == '\'')
8217             {
8218                if((int)((byte *)constant)[1] > 127)
8219                {
8220                   int nb;
8221                   unichar ch = UTF8GetChar(constant + 1, &nb);
8222                   if(nb < 2) ch = constant[1];
8223                   delete constant;
8224                   exp.constant = PrintUInt(ch);
8225                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8226                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8227                   type._class = FindClass("unichar");
8228
8229                   type.isSigned = false;
8230                }
8231                else
8232                {
8233                   type.kind = charType;
8234                   type.isSigned = true;
8235                }
8236             }
8237             else
8238             {
8239                char * dot = strchr(constant, '.');
8240                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8241                char * exponent;
8242                if(isHex)
8243                {
8244                   exponent = strchr(constant, 'p');
8245                   if(!exponent) exponent = strchr(constant, 'P');
8246                }
8247                else
8248                {
8249                   exponent = strchr(constant, 'e');
8250                   if(!exponent) exponent = strchr(constant, 'E');
8251                }
8252
8253                if(dot || exponent)
8254                {
8255                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8256                      type.kind = floatType;
8257                   else
8258                      type.kind = doubleType;
8259                   type.isSigned = true;
8260                }
8261                else
8262                {
8263                   bool isSigned = constant[0] == '-';
8264                   char * endP = null;
8265                   int64 i64 = strtoll(constant, &endP, 0);
8266                   uint64 ui64 = strtoull(constant, &endP, 0);
8267                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll"));
8268                   if(isSigned)
8269                   {
8270                      if(i64 < MININT)
8271                         is64Bit = true;
8272                   }
8273                   else
8274                   {
8275                      if(ui64 > MAXINT)
8276                      {
8277                         if(ui64 > MAXDWORD)
8278                         {
8279                            is64Bit = true;
8280                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8281                               isSigned = true;
8282                         }
8283                      }
8284                      else if(constant[0] != '0' || !constant[1])
8285                         isSigned = true;
8286                   }
8287                   type.kind = is64Bit ? int64Type : intType;
8288                   type.isSigned = isSigned;
8289                }
8290             }
8291             exp.isConstant = true;
8292             if(exp.destType && exp.destType.kind == doubleType)
8293                type.kind = doubleType;
8294             else if(exp.destType && exp.destType.kind == floatType)
8295                type.kind = floatType;
8296             else if(exp.destType && exp.destType.kind == int64Type)
8297                type.kind = int64Type;
8298          }
8299          break;
8300       }
8301       case stringExp:
8302       {
8303          exp.isConstant = true;      // Why wasn't this constant?
8304          exp.expType = Type
8305          {
8306             refCount = 1;
8307             kind = pointerType;
8308             type = Type
8309             {
8310                refCount = 1;
8311                kind = exp.wideString ? shortType : charType;
8312                constant = true;
8313                isSigned = exp.wideString ? false : true;
8314             }
8315          };
8316          break;
8317       }
8318       case newExp:
8319       case new0Exp:
8320          ProcessExpressionType(exp._new.size);
8321          exp.expType = Type
8322          {
8323             refCount = 1;
8324             kind = pointerType;
8325             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8326          };
8327          DeclareType(exp.expType.type, false, false);
8328          break;
8329       case renewExp:
8330       case renew0Exp:
8331          ProcessExpressionType(exp._renew.size);
8332          ProcessExpressionType(exp._renew.exp);
8333          exp.expType = Type
8334          {
8335             refCount = 1;
8336             kind = pointerType;
8337             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8338          };
8339          DeclareType(exp.expType.type, false, false);
8340          break;
8341       case opExp:
8342       {
8343          bool assign = false, boolResult = false, boolOps = false;
8344          Type type1 = null, type2 = null;
8345          bool useDestType = false, useSideType = false;
8346          Location oldyylloc = yylloc;
8347          bool useSideUnit = false;
8348          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8349
8350          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8351          Type dummy
8352          {
8353             count = 1;
8354             refCount = 1;
8355          };
8356
8357          switch(exp.op.op)
8358          {
8359             // Assignment Operators
8360             case '=':
8361             case MUL_ASSIGN:
8362             case DIV_ASSIGN:
8363             case MOD_ASSIGN:
8364             case ADD_ASSIGN:
8365             case SUB_ASSIGN:
8366             case LEFT_ASSIGN:
8367             case RIGHT_ASSIGN:
8368             case AND_ASSIGN:
8369             case XOR_ASSIGN:
8370             case OR_ASSIGN:
8371                assign = true;
8372                break;
8373             // boolean Operators
8374             case '!':
8375                // Expect boolean operators
8376                //boolOps = true;
8377                //boolResult = true;
8378                break;
8379             case AND_OP:
8380             case OR_OP:
8381                // Expect boolean operands
8382                boolOps = true;
8383                boolResult = true;
8384                break;
8385             // Comparisons
8386             case EQ_OP:
8387             case '<':
8388             case '>':
8389             case LE_OP:
8390             case GE_OP:
8391             case NE_OP:
8392                // Gives boolean result
8393                boolResult = true;
8394                useSideType = true;
8395                break;
8396             case '+':
8397             case '-':
8398                useSideUnit = true;
8399                useSideType = true;
8400                useDestType = true;
8401                break;
8402
8403             case LEFT_OP:
8404             case RIGHT_OP:
8405                useSideType = true;
8406                useDestType = true;
8407                break;
8408
8409             case '|':
8410             case '^':
8411                useSideType = true;
8412                useDestType = true;
8413                break;
8414
8415             case '/':
8416             case '%':
8417                useSideType = true;
8418                useDestType = true;
8419                break;
8420             case '&':
8421             case '*':
8422                if(exp.op.exp1)
8423                {
8424                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8425                   useSideType = true;
8426                   useDestType = true;
8427                }
8428                break;
8429
8430             /*// Implement speed etc.
8431             case '*':
8432             case '/':
8433                break;
8434             */
8435          }
8436          if(exp.op.op == '&')
8437          {
8438             // Added this here earlier for Iterator address as key
8439             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8440             {
8441                Identifier id = exp.op.exp2.identifier;
8442                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8443                if(symbol && symbol.isIterator == 2)
8444                {
8445                   exp.type = memberExp;
8446                   exp.member.exp = exp.op.exp2;
8447                   exp.member.member = MkIdentifier("key");
8448                   exp.expType = null;
8449                   exp.op.exp2.expType = symbol.type;
8450                   symbol.type.refCount++;
8451                   ProcessExpressionType(exp);
8452                   FreeType(dummy);
8453                   break;
8454                }
8455                // exp.op.exp2.usage.usageRef = true;
8456             }
8457          }
8458
8459          //dummy.kind = TypeDummy;
8460          if(exp.op.exp1)
8461          {
8462             // Added this check here to use the dest type only for units derived from the base unit
8463             // So that untyped units will use the side unit as opposed to the untyped destination unit
8464             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8465             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8466                useDestType = false;
8467
8468             if(destClass && useDestType &&
8469               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8470
8471               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8472             {
8473                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8474                exp.op.exp1.destType = exp.destType;
8475                exp.op.exp1.opDestType = true;
8476                if(exp.destType)
8477                   exp.destType.refCount++;
8478             }
8479             else if(!assign)
8480             {
8481                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8482                exp.op.exp1.destType = dummy;
8483                dummy.refCount++;
8484             }
8485
8486             // TESTING THIS HERE...
8487             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8488                ProcessExpressionType(exp.op.exp1);
8489             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8490
8491             exp.op.exp1.opDestType = false;
8492
8493             // Fix for unit and ++ / --
8494             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8495                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8496             {
8497                exp.op.exp2 = MkExpConstant("1");
8498                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8499                assign = true;
8500             }
8501
8502             if(exp.op.exp1.destType == dummy)
8503             {
8504                FreeType(dummy);
8505                exp.op.exp1.destType = null;
8506             }
8507             type1 = exp.op.exp1.expType;
8508          }
8509
8510          if(exp.op.exp2)
8511          {
8512             char expString[10240];
8513             expString[0] = '\0';
8514             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8515             {
8516                if(exp.op.exp1)
8517                {
8518                   exp.op.exp2.destType = exp.op.exp1.expType;
8519                   if(exp.op.exp1.expType)
8520                      exp.op.exp1.expType.refCount++;
8521                }
8522                else
8523                {
8524                   exp.op.exp2.destType = exp.destType;
8525                   if(!exp.op.exp1 || exp.op.op != '&')
8526                      exp.op.exp2.opDestType = true;
8527                   if(exp.destType)
8528                      exp.destType.refCount++;
8529                }
8530
8531                if(type1) type1.refCount++;
8532                exp.expType = type1;
8533             }
8534             else if(assign)
8535             {
8536                if(inCompiler)
8537                   PrintExpression(exp.op.exp2, expString);
8538
8539                if(type1 && type1.kind == pointerType)
8540                {
8541                   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 ||
8542                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8543                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8544                   else if(exp.op.op == '=')
8545                   {
8546                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8547                      exp.op.exp2.destType = type1;
8548                      if(type1)
8549                         type1.refCount++;
8550                   }
8551                }
8552                else
8553                {
8554                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8555                   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/* ||
8556                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8557                   else
8558                   {
8559                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8560                      exp.op.exp2.destType = type1;
8561                      if(type1)
8562                         type1.refCount++;
8563                   }
8564                }
8565                if(type1) type1.refCount++;
8566                exp.expType = type1;
8567             }
8568             else if(destClass &&
8569                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8570                   (destClass.type == enumClass && useDestType)))
8571             {
8572                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8573                exp.op.exp2.destType = exp.destType;
8574                if(exp.op.op != '&')
8575                   exp.op.exp2.opDestType = true;
8576                if(exp.destType)
8577                   exp.destType.refCount++;
8578             }
8579             else
8580             {
8581                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8582                exp.op.exp2.destType = dummy;
8583                dummy.refCount++;
8584             }
8585
8586             // TESTING THIS HERE... (DANGEROUS)
8587             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8588                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8589             {
8590                FreeType(exp.op.exp2.destType);
8591                exp.op.exp2.destType = type1;
8592                type1.refCount++;
8593             }
8594             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8595             // Cannot lose the cast on a sizeof
8596             if(exp.op.op == SIZEOF)
8597             {
8598                Expression e = exp.op.exp2;
8599                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8600                {
8601                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8602                   {
8603                      if(e.type == extensionCompoundExp)
8604                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8605                      else
8606                         e = e.list->last;
8607                   }
8608                }
8609                if(e.type == castExp && e.cast.exp)
8610                   e.cast.exp.needCast = true;
8611             }
8612             ProcessExpressionType(exp.op.exp2);
8613             exp.op.exp2.opDestType = false;
8614             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8615
8616             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8617             {
8618                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)
8619                {
8620                   if(exp.op.op != '=' && type1.type.kind == voidType)
8621                      Compiler_Error($"void *: unknown size\n");
8622                }
8623                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||
8624                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8625                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8626                               exp.op.exp2.expType._class.registered.type == structClass ||
8627                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8628                {
8629                   if(exp.op.op == ADD_ASSIGN)
8630                      Compiler_Error($"cannot add two pointers\n");
8631                }
8632                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8633                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8634                {
8635                   if(exp.op.op == ADD_ASSIGN)
8636                      Compiler_Error($"cannot add two pointers\n");
8637                }
8638                else if(inCompiler)
8639                {
8640                   char type1String[1024];
8641                   char type2String[1024];
8642                   type1String[0] = '\0';
8643                   type2String[0] = '\0';
8644
8645                   PrintType(exp.op.exp2.expType, type1String, false, true);
8646                   PrintType(type1, type2String, false, true);
8647                   ChangeCh(expString, '\n', ' ');
8648                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8649                }
8650             }
8651
8652             if(exp.op.exp2.destType == dummy)
8653             {
8654                FreeType(dummy);
8655                exp.op.exp2.destType = null;
8656             }
8657
8658             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8659             {
8660                type2 = { };
8661                type2.refCount = 1;
8662                CopyTypeInto(type2, exp.op.exp2.expType);
8663                type2.isSigned = true;
8664             }
8665             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8666             {
8667                type2 = { kind = intType };
8668                type2.refCount = 1;
8669                type2.isSigned = true;
8670             }
8671             else
8672             {
8673                type2 = exp.op.exp2.expType;
8674                if(type2) type2.refCount++;
8675             }
8676          }
8677
8678          dummy.kind = voidType;
8679
8680          if(exp.op.op == SIZEOF)
8681          {
8682             exp.expType = Type
8683             {
8684                refCount = 1;
8685                kind = intSizeType;
8686             };
8687             exp.isConstant = true;
8688          }
8689          // Get type of dereferenced pointer
8690          else if(exp.op.op == '*' && !exp.op.exp1)
8691          {
8692             exp.expType = Dereference(type2);
8693             if(type2 && type2.kind == classType)
8694                notByReference = true;
8695          }
8696          else if(exp.op.op == '&' && !exp.op.exp1)
8697             exp.expType = Reference(type2);
8698          else if(!assign)
8699          {
8700             if(boolOps)
8701             {
8702                if(exp.op.exp1)
8703                {
8704                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8705                   exp.op.exp1.destType = MkClassType("bool");
8706                   exp.op.exp1.destType.truth = true;
8707                   if(!exp.op.exp1.expType)
8708                      ProcessExpressionType(exp.op.exp1);
8709                   else
8710                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8711                   FreeType(exp.op.exp1.expType);
8712                   exp.op.exp1.expType = MkClassType("bool");
8713                   exp.op.exp1.expType.truth = true;
8714                }
8715                if(exp.op.exp2)
8716                {
8717                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8718                   exp.op.exp2.destType = MkClassType("bool");
8719                   exp.op.exp2.destType.truth = true;
8720                   if(!exp.op.exp2.expType)
8721                      ProcessExpressionType(exp.op.exp2);
8722                   else
8723                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8724                   FreeType(exp.op.exp2.expType);
8725                   exp.op.exp2.expType = MkClassType("bool");
8726                   exp.op.exp2.expType.truth = true;
8727                }
8728             }
8729             else if(exp.op.exp1 && exp.op.exp2 &&
8730                ((useSideType /*&&
8731                      (useSideUnit ||
8732                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8733                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8734                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8735                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8736             {
8737                if(type1 && type2 &&
8738                   // If either both are class or both are not class
8739                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8740                {
8741                   // Added this check for enum subtraction to result in an int type:
8742                   if(exp.op.op == '-' &&
8743                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8744                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8745                   {
8746                      Type intType;
8747                      if(!type1._class.registered.dataType)
8748                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8749                      if(!type2._class.registered.dataType)
8750                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8751
8752                      intType = ProcessTypeString(
8753                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8754
8755                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8756                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8757                      exp.op.exp1.destType = intType;
8758                      exp.op.exp2.destType = intType;
8759                      intType.refCount++;
8760                   }
8761                   else
8762                   {
8763                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8764                      exp.op.exp2.destType = type1;
8765                      type1.refCount++;
8766                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8767                      exp.op.exp1.destType = type2;
8768                      type2.refCount++;
8769                   }
8770
8771                   // Warning here for adding Radians + Degrees with no destination type
8772                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8773                      type1._class.registered && type1._class.registered.type == unitClass &&
8774                      type2._class.registered && type2._class.registered.type == unitClass &&
8775                      type1._class.registered != type2._class.registered)
8776                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8777                         type1._class.string, type2._class.string, type1._class.string);
8778
8779                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8780                   {
8781                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8782                      if(argExp)
8783                      {
8784                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8785
8786                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8787                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8788                            exp.op.exp1)));
8789
8790                         ProcessExpressionType(exp.op.exp1);
8791
8792                         if(type2.kind != pointerType)
8793                         {
8794                            ProcessExpressionType(classExp);
8795
8796                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8797
8798                            if(!exp.op.exp2.expType)
8799                            {
8800                               if(type2)
8801                                  FreeType(type2);
8802                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8803                               type2.refCount++;
8804                            }
8805
8806                            ProcessExpressionType(exp.op.exp2);
8807                         }
8808                      }
8809                   }
8810
8811                   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)))
8812                   {
8813                      if(type1.kind != classType && type1.type.kind == voidType)
8814                         Compiler_Error($"void *: unknown size\n");
8815                      exp.expType = type1;
8816                      if(type1) type1.refCount++;
8817                   }
8818                   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)))
8819                   {
8820                      if(type2.kind != classType && type2.type.kind == voidType)
8821                         Compiler_Error($"void *: unknown size\n");
8822                      exp.expType = type2;
8823                      if(type2) type2.refCount++;
8824                   }
8825                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8826                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8827                   {
8828                      Compiler_Warning($"different levels of indirection\n");
8829                   }
8830                   else
8831                   {
8832                      bool success = false;
8833                      if(type1.kind == pointerType && type2.kind == pointerType)
8834                      {
8835                         if(exp.op.op == '+')
8836                            Compiler_Error($"cannot add two pointers\n");
8837                         else if(exp.op.op == '-')
8838                         {
8839                            // Pointer Subtraction gives integer
8840                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8841                            {
8842                               exp.expType = Type
8843                               {
8844                                  kind = intType;
8845                                  refCount = 1;
8846                               };
8847                               success = true;
8848
8849                               if(type1.type.kind == templateType)
8850                               {
8851                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8852                                  if(argExp)
8853                                  {
8854                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8855
8856                                     ProcessExpressionType(classExp);
8857
8858                                     exp.type = bracketsExp;
8859                                     exp.list = MkListOne(MkExpOp(
8860                                        MkExpBrackets(MkListOne(MkExpOp(
8861                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8862                                              , exp.op.op,
8863                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8864                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8865
8866                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8867                                     FreeType(dummy);
8868                                     return;
8869                                  }
8870                               }
8871                            }
8872                         }
8873                      }
8874
8875                      if(!success && exp.op.exp1.type == constantExp)
8876                      {
8877                         // If first expression is constant, try to match that first
8878                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8879                         {
8880                            if(exp.expType) FreeType(exp.expType);
8881                            exp.expType = exp.op.exp1.destType;
8882                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8883                            success = true;
8884                         }
8885                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8886                         {
8887                            if(exp.expType) FreeType(exp.expType);
8888                            exp.expType = exp.op.exp2.destType;
8889                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8890                            success = true;
8891                         }
8892                      }
8893                      else if(!success)
8894                      {
8895                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8896                         {
8897                            if(exp.expType) FreeType(exp.expType);
8898                            exp.expType = exp.op.exp2.destType;
8899                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8900                            success = true;
8901                         }
8902                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8903                         {
8904                            if(exp.expType) FreeType(exp.expType);
8905                            exp.expType = exp.op.exp1.destType;
8906                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8907                            success = true;
8908                         }
8909                      }
8910                      if(!success)
8911                      {
8912                         char expString1[10240];
8913                         char expString2[10240];
8914                         char type1[1024];
8915                         char type2[1024];
8916                         expString1[0] = '\0';
8917                         expString2[0] = '\0';
8918                         type1[0] = '\0';
8919                         type2[0] = '\0';
8920                         if(inCompiler)
8921                         {
8922                            PrintExpression(exp.op.exp1, expString1);
8923                            ChangeCh(expString1, '\n', ' ');
8924                            PrintExpression(exp.op.exp2, expString2);
8925                            ChangeCh(expString2, '\n', ' ');
8926                            PrintType(exp.op.exp1.expType, type1, false, true);
8927                            PrintType(exp.op.exp2.expType, type2, false, true);
8928                         }
8929
8930                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8931                      }
8932                   }
8933                }
8934                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8935                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8936                {
8937                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8938                   // Convert e.g. / 4 into / 4.0
8939                   exp.op.exp1.destType = type2._class.registered.dataType;
8940                   if(type2._class.registered.dataType)
8941                      type2._class.registered.dataType.refCount++;
8942                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8943                   exp.expType = type2;
8944                   if(type2) type2.refCount++;
8945                }
8946                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8947                {
8948                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8949                   // Convert e.g. / 4 into / 4.0
8950                   exp.op.exp2.destType = type1._class.registered.dataType;
8951                   if(type1._class.registered.dataType)
8952                      type1._class.registered.dataType.refCount++;
8953                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8954                   exp.expType = type1;
8955                   if(type1) type1.refCount++;
8956                }
8957                else if(type1)
8958                {
8959                   bool valid = false;
8960
8961                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8962                   {
8963                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8964
8965                      if(!type1._class.registered.dataType)
8966                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8967                      exp.op.exp2.destType = type1._class.registered.dataType;
8968                      exp.op.exp2.destType.refCount++;
8969
8970                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8971                      if(type2)
8972                         FreeType(type2);
8973                      type2 = exp.op.exp2.destType;
8974                      if(type2) type2.refCount++;
8975
8976                      exp.expType = type2;
8977                      type2.refCount++;
8978                   }
8979
8980                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8981                   {
8982                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8983
8984                      if(!type2._class.registered.dataType)
8985                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8986                      exp.op.exp1.destType = type2._class.registered.dataType;
8987                      exp.op.exp1.destType.refCount++;
8988
8989                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8990                      type1 = exp.op.exp1.destType;
8991                      exp.expType = type1;
8992                      type1.refCount++;
8993                   }
8994
8995                   // TESTING THIS NEW CODE
8996                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8997                   {
8998                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8999                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
9000                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
9001                      {
9002                         // Convert the enum to an int instead for these operators
9003                         if(op1IsEnum && exp.op.exp2.expType)
9004                         {
9005                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
9006                            {
9007                               if(exp.expType) FreeType(exp.expType);
9008                               exp.expType = exp.op.exp2.expType;
9009                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9010                               valid = true;
9011                            }
9012                         }
9013                         else if(op2IsEnum && exp.op.exp1.expType)
9014                         {
9015                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
9016                            {
9017                               if(exp.expType) FreeType(exp.expType);
9018                               exp.expType = exp.op.exp1.expType;
9019                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9020                               valid = true;
9021                            }
9022                         }
9023                      }
9024                      else
9025                      {
9026                         if(op1IsEnum && exp.op.exp2.expType)
9027                         {
9028                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
9029                            {
9030                               if(exp.expType) FreeType(exp.expType);
9031                               exp.expType = exp.op.exp1.expType;
9032                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9033                               valid = true;
9034                            }
9035                         }
9036                         else if(op2IsEnum && exp.op.exp1.expType)
9037                         {
9038                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
9039                            {
9040                               if(exp.expType) FreeType(exp.expType);
9041                               exp.expType = exp.op.exp2.expType;
9042                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9043                               valid = true;
9044                            }
9045                         }
9046                      }
9047                   }
9048
9049                   if(!valid)
9050                   {
9051                      // 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
9052                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
9053                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
9054                      {
9055                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9056                         exp.op.exp1.destType = type2;
9057                         type2.refCount++;
9058
9059                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9060                         {
9061                            if(exp.expType) FreeType(exp.expType);
9062                            exp.expType = exp.op.exp1.destType;
9063                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9064                         }
9065                      }
9066                      else
9067                      {
9068                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9069                         exp.op.exp2.destType = type1;
9070                         type1.refCount++;
9071
9072                      /*
9073                      // Maybe this was meant to be an enum...
9074                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9075                      {
9076                         Type oldType = exp.op.exp2.expType;
9077                         exp.op.exp2.expType = null;
9078                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
9079                            FreeType(oldType);
9080                         else
9081                            exp.op.exp2.expType = oldType;
9082                      }
9083                      */
9084
9085                      /*
9086                      // TESTING THIS HERE... LATEST ADDITION
9087                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9088                      {
9089                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9090                         exp.op.exp2.destType = type2._class.registered.dataType;
9091                         if(type2._class.registered.dataType)
9092                            type2._class.registered.dataType.refCount++;
9093                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9094
9095                         //exp.expType = type2._class.registered.dataType; //type2;
9096                         //if(type2) type2.refCount++;
9097                      }
9098
9099                      // TESTING THIS HERE... LATEST ADDITION
9100                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9101                      {
9102                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9103                         exp.op.exp1.destType = type1._class.registered.dataType;
9104                         if(type1._class.registered.dataType)
9105                            type1._class.registered.dataType.refCount++;
9106                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9107                         exp.expType = type1._class.registered.dataType; //type1;
9108                         if(type1) type1.refCount++;
9109                      }
9110                      */
9111
9112                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9113                         {
9114                            if(exp.expType) FreeType(exp.expType);
9115                            exp.expType = exp.op.exp2.destType;
9116                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9117                         }
9118                         else if(type1 && type2)
9119                         {
9120                            char expString1[10240];
9121                            char expString2[10240];
9122                            char type1String[1024];
9123                            char type2String[1024];
9124                            expString1[0] = '\0';
9125                            expString2[0] = '\0';
9126                            type1String[0] = '\0';
9127                            type2String[0] = '\0';
9128                            if(inCompiler)
9129                            {
9130                               PrintExpression(exp.op.exp1, expString1);
9131                               ChangeCh(expString1, '\n', ' ');
9132                               PrintExpression(exp.op.exp2, expString2);
9133                               ChangeCh(expString2, '\n', ' ');
9134                               PrintType(exp.op.exp1.expType, type1String, false, true);
9135                               PrintType(exp.op.exp2.expType, type2String, false, true);
9136                            }
9137
9138                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9139
9140                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9141                            {
9142                               exp.expType = exp.op.exp1.expType;
9143                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9144                            }
9145                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9146                            {
9147                               exp.expType = exp.op.exp2.expType;
9148                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9149                            }
9150                         }
9151                      }
9152                   }
9153                }
9154                else if(type2)
9155                {
9156                   // Maybe this was meant to be an enum...
9157                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9158                   {
9159                      Type oldType = exp.op.exp1.expType;
9160                      exp.op.exp1.expType = null;
9161                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9162                         FreeType(oldType);
9163                      else
9164                         exp.op.exp1.expType = oldType;
9165                   }
9166
9167                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9168                   exp.op.exp1.destType = type2;
9169                   type2.refCount++;
9170                   /*
9171                   // TESTING THIS HERE... LATEST ADDITION
9172                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9173                   {
9174                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9175                      exp.op.exp1.destType = type1._class.registered.dataType;
9176                      if(type1._class.registered.dataType)
9177                         type1._class.registered.dataType.refCount++;
9178                   }
9179
9180                   // TESTING THIS HERE... LATEST ADDITION
9181                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9182                   {
9183                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9184                      exp.op.exp2.destType = type2._class.registered.dataType;
9185                      if(type2._class.registered.dataType)
9186                         type2._class.registered.dataType.refCount++;
9187                   }
9188                   */
9189
9190                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9191                   {
9192                      if(exp.expType) FreeType(exp.expType);
9193                      exp.expType = exp.op.exp1.destType;
9194                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9195                   }
9196                }
9197             }
9198             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9199             {
9200                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9201                {
9202                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9203                   // Convert e.g. / 4 into / 4.0
9204                   exp.op.exp1.destType = type2._class.registered.dataType;
9205                   if(type2._class.registered.dataType)
9206                      type2._class.registered.dataType.refCount++;
9207                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9208                }
9209                if(exp.op.op == '!')
9210                {
9211                   exp.expType = MkClassType("bool");
9212                   exp.expType.truth = true;
9213                }
9214                else
9215                {
9216                   exp.expType = type2;
9217                   if(type2) type2.refCount++;
9218                }
9219             }
9220             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9221             {
9222                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9223                {
9224                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9225                   // Convert e.g. / 4 into / 4.0
9226                   exp.op.exp2.destType = type1._class.registered.dataType;
9227                   if(type1._class.registered.dataType)
9228                      type1._class.registered.dataType.refCount++;
9229                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9230                }
9231                exp.expType = type1;
9232                if(type1) type1.refCount++;
9233             }
9234          }
9235
9236          yylloc = exp.loc;
9237          if(exp.op.exp1 && !exp.op.exp1.expType)
9238          {
9239             char expString[10000];
9240             expString[0] = '\0';
9241             if(inCompiler)
9242             {
9243                PrintExpression(exp.op.exp1, expString);
9244                ChangeCh(expString, '\n', ' ');
9245             }
9246             if(expString[0])
9247                Compiler_Error($"couldn't determine type of %s\n", expString);
9248          }
9249          if(exp.op.exp2 && !exp.op.exp2.expType)
9250          {
9251             char expString[10240];
9252             expString[0] = '\0';
9253             if(inCompiler)
9254             {
9255                PrintExpression(exp.op.exp2, expString);
9256                ChangeCh(expString, '\n', ' ');
9257             }
9258             if(expString[0])
9259                Compiler_Error($"couldn't determine type of %s\n", expString);
9260          }
9261
9262          if(boolResult)
9263          {
9264             FreeType(exp.expType);
9265             exp.expType = MkClassType("bool");
9266             exp.expType.truth = true;
9267          }
9268
9269          if(exp.op.op != SIZEOF)
9270             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9271                (!exp.op.exp2 || exp.op.exp2.isConstant);
9272
9273          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9274          {
9275             DeclareType(exp.op.exp2.expType, false, false);
9276          }
9277
9278          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9279             Compiler_Warning($"deleting const qualified object\n");
9280
9281          yylloc = oldyylloc;
9282
9283          FreeType(dummy);
9284          if(type2)
9285             FreeType(type2);
9286          break;
9287       }
9288       case bracketsExp:
9289       case extensionExpressionExp:
9290       {
9291          Expression e;
9292          exp.isConstant = true;
9293          for(e = exp.list->first; e; e = e.next)
9294          {
9295             bool inced = false;
9296             if(!e.next)
9297             {
9298                FreeType(e.destType);
9299                e.opDestType = exp.opDestType;
9300                e.destType = exp.destType;
9301                if(e.destType) { exp.destType.refCount++; e.destType.count++; inced = true; }
9302             }
9303             ProcessExpressionType(e);
9304             if(inced)
9305                exp.destType.count--;
9306             if(!exp.expType && !e.next)
9307             {
9308                exp.expType = e.expType;
9309                if(e.expType) e.expType.refCount++;
9310             }
9311             if(!e.isConstant)
9312                exp.isConstant = false;
9313          }
9314
9315          // In case a cast became a member...
9316          e = exp.list->first;
9317          if(!e.next && e.type == memberExp)
9318          {
9319             // Preserve prev, next
9320             Expression next = exp.next, prev = exp.prev;
9321
9322
9323             FreeType(exp.expType);
9324             FreeType(exp.destType);
9325             delete exp.list;
9326
9327             *exp = *e;
9328
9329             exp.prev = prev;
9330             exp.next = next;
9331
9332             delete e;
9333
9334             ProcessExpressionType(exp);
9335          }
9336          break;
9337       }
9338       case indexExp:
9339       {
9340          Expression e;
9341          exp.isConstant = true;
9342
9343          ProcessExpressionType(exp.index.exp);
9344          if(!exp.index.exp.isConstant)
9345             exp.isConstant = false;
9346
9347          if(exp.index.exp.expType)
9348          {
9349             Type source = exp.index.exp.expType;
9350             if(source.kind == classType && source._class && source._class.registered)
9351             {
9352                Class _class = source._class.registered;
9353                Class c = _class.templateClass ? _class.templateClass : _class;
9354                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9355                {
9356                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9357
9358                   if(exp.index.index && exp.index.index->last)
9359                   {
9360                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9361
9362                      if(type.kind == classType) type.constant = true;
9363                      else if(type.kind == pointerType)
9364                      {
9365                         Type t = type;
9366                         while(t.kind == pointerType) t = t.type;
9367                         t.constant = true;
9368                      }
9369
9370                      ((Expression)exp.index.index->last).destType = type;
9371                   }
9372                }
9373             }
9374          }
9375
9376          for(e = exp.index.index->first; e; e = e.next)
9377          {
9378             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9379             {
9380                if(e.destType) FreeType(e.destType);
9381                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9382             }
9383             ProcessExpressionType(e);
9384             if(!e.next)
9385             {
9386                // Check if this type is int
9387             }
9388             if(!e.isConstant)
9389                exp.isConstant = false;
9390          }
9391
9392          if(!exp.expType)
9393             exp.expType = Dereference(exp.index.exp.expType);
9394          if(exp.expType)
9395             DeclareType(exp.expType, false, false);
9396          break;
9397       }
9398       case callExp:
9399       {
9400          Expression e;
9401          Type functionType;
9402          Type methodType = null;
9403          char name[1024];
9404          name[0] = '\0';
9405
9406          if(inCompiler)
9407          {
9408             PrintExpression(exp.call.exp,  name);
9409             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9410             {
9411                //exp.call.exp.expType = null;
9412                PrintExpression(exp.call.exp,  name);
9413             }
9414          }
9415          if(exp.call.exp.type == identifierExp)
9416          {
9417             Expression idExp = exp.call.exp;
9418             Identifier id = idExp.identifier;
9419             if(!strcmp(id.string, "__builtin_frame_address"))
9420             {
9421                exp.expType = ProcessTypeString("void *", true);
9422                if(exp.call.arguments && exp.call.arguments->first)
9423                   ProcessExpressionType(exp.call.arguments->first);
9424                break;
9425             }
9426             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9427             {
9428                exp.expType = ProcessTypeString("int", true);
9429                if(exp.call.arguments && exp.call.arguments->first)
9430                   ProcessExpressionType(exp.call.arguments->first);
9431                break;
9432             }
9433             else if(!strcmp(id.string, "Max") ||
9434                !strcmp(id.string, "Min") ||
9435                !strcmp(id.string, "Sgn") ||
9436                !strcmp(id.string, "Abs"))
9437             {
9438                Expression a = null;
9439                Expression b = null;
9440                Expression tempExp1 = null, tempExp2 = null;
9441                if((!strcmp(id.string, "Max") ||
9442                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9443                {
9444                   a = exp.call.arguments->first;
9445                   b = exp.call.arguments->last;
9446                   tempExp1 = a;
9447                   tempExp2 = b;
9448                }
9449                else if(exp.call.arguments->count == 1)
9450                {
9451                   a = exp.call.arguments->first;
9452                   tempExp1 = a;
9453                }
9454
9455                if(a)
9456                {
9457                   exp.call.arguments->Clear();
9458                   idExp.identifier = null;
9459
9460                   FreeExpContents(exp);
9461
9462                   ProcessExpressionType(a);
9463                   if(b)
9464                      ProcessExpressionType(b);
9465
9466                   exp.type = bracketsExp;
9467                   exp.list = MkList();
9468
9469                   if(a.expType && (!b || b.expType))
9470                   {
9471                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9472                      {
9473                         // Use the simpleStruct name/ids for now...
9474                         if(inCompiler)
9475                         {
9476                            OldList * specs = MkList();
9477                            OldList * decls = MkList();
9478                            Declaration decl;
9479                            char temp1[1024], temp2[1024];
9480
9481                            GetTypeSpecs(a.expType, specs);
9482
9483                            if(a && !a.isConstant && a.type != identifierExp)
9484                            {
9485                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9486                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9487                               tempExp1 = QMkExpId(temp1);
9488                               tempExp1.expType = a.expType;
9489                               if(a.expType)
9490                                  a.expType.refCount++;
9491                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9492                            }
9493                            if(b && !b.isConstant && b.type != identifierExp)
9494                            {
9495                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9496                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9497                               tempExp2 = QMkExpId(temp2);
9498                               tempExp2.expType = b.expType;
9499                               if(b.expType)
9500                                  b.expType.refCount++;
9501                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9502                            }
9503
9504                            decl = MkDeclaration(specs, decls);
9505                            if(!curCompound.compound.declarations)
9506                               curCompound.compound.declarations = MkList();
9507                            curCompound.compound.declarations->Insert(null, decl);
9508                         }
9509                      }
9510                   }
9511
9512                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9513                   {
9514                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9515                      ListAdd(exp.list,
9516                         MkExpCondition(MkExpBrackets(MkListOne(
9517                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9518                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9519                      exp.expType = a.expType;
9520                      if(a.expType)
9521                         a.expType.refCount++;
9522                   }
9523                   else if(!strcmp(id.string, "Abs"))
9524                   {
9525                      ListAdd(exp.list,
9526                         MkExpCondition(MkExpBrackets(MkListOne(
9527                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9528                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9529                      exp.expType = a.expType;
9530                      if(a.expType)
9531                         a.expType.refCount++;
9532                   }
9533                   else if(!strcmp(id.string, "Sgn"))
9534                   {
9535                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9536                      ListAdd(exp.list,
9537                         MkExpCondition(MkExpBrackets(MkListOne(
9538                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9539                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9540                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9541                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9542                      exp.expType = ProcessTypeString("int", false);
9543                   }
9544
9545                   FreeExpression(tempExp1);
9546                   if(tempExp2) FreeExpression(tempExp2);
9547
9548                   FreeIdentifier(id);
9549                   break;
9550                }
9551             }
9552          }
9553
9554          {
9555             Type dummy
9556             {
9557                count = 1;
9558                refCount = 1;
9559             };
9560             if(!exp.call.exp.destType)
9561             {
9562                exp.call.exp.destType = dummy;
9563                dummy.refCount++;
9564             }
9565             ProcessExpressionType(exp.call.exp);
9566             if(exp.call.exp.destType == dummy)
9567             {
9568                FreeType(dummy);
9569                exp.call.exp.destType = null;
9570             }
9571             FreeType(dummy);
9572          }
9573
9574          // Check argument types against parameter types
9575          functionType = exp.call.exp.expType;
9576
9577          if(functionType && functionType.kind == TypeKind::methodType)
9578          {
9579             methodType = functionType;
9580             functionType = methodType.method.dataType;
9581
9582             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9583             // TOCHECK: Instead of doing this here could this be done per param?
9584             if(exp.call.exp.expType.usedClass)
9585             {
9586                char typeString[1024];
9587                typeString[0] = '\0';
9588                {
9589                   Symbol back = functionType.thisClass;
9590                   // Do not output class specifier here (thisclass was added to this)
9591                   functionType.thisClass = null;
9592                   PrintType(functionType, typeString, true, true);
9593                   functionType.thisClass = back;
9594                }
9595                if(strstr(typeString, "thisclass"))
9596                {
9597                   OldList * specs = MkList();
9598                   Declarator decl;
9599                   {
9600                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9601
9602                      decl = SpecDeclFromString(typeString, specs, null);
9603
9604                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9605                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9606                         exp.call.exp.expType.usedClass))
9607                         thisClassParams = false;
9608
9609                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9610                      {
9611                         Class backupThisClass = thisClass;
9612                         thisClass = exp.call.exp.expType.usedClass;
9613                         ProcessDeclarator(decl);
9614                         thisClass = backupThisClass;
9615                      }
9616
9617                      thisClassParams = true;
9618
9619                      functionType = ProcessType(specs, decl);
9620                      functionType.refCount = 0;
9621                      FinishTemplatesContext(context);
9622
9623                      // Mark parameters that were 'thisclass'
9624                      /*{
9625                         Type p, op;
9626                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9627                            p.wasThisClass = op.kind == thisClassType;
9628                      }*/
9629                   }
9630
9631                   FreeList(specs, FreeSpecifier);
9632                   FreeDeclarator(decl);
9633                 }
9634             }
9635          }
9636          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9637          {
9638             Type type = functionType.type;
9639             if(!functionType.refCount)
9640             {
9641                functionType.type = null;
9642                FreeType(functionType);
9643             }
9644             //methodType = functionType;
9645             functionType = type;
9646          }
9647          if(functionType && functionType.kind != TypeKind::functionType)
9648          {
9649             Compiler_Error($"called object %s is not a function\n", name);
9650          }
9651          else if(functionType)
9652          {
9653             bool emptyParams = false, noParams = false;
9654             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9655             Type type = functionType.params.first;
9656             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9657             int extra = 0;
9658             Location oldyylloc = yylloc;
9659
9660             if(!type) emptyParams = true;
9661
9662             // WORKING ON THIS:
9663             if(functionType.extraParam && e && functionType.thisClass)
9664             {
9665                e.destType = MkClassType(functionType.thisClass.string);
9666                e = e.next;
9667             }
9668
9669             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9670             // Fixed #141 by adding '&& !functionType.extraParam'
9671             if(!functionType.staticMethod && !functionType.extraParam)
9672             {
9673                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9674                   memberExp.member.exp.expType._class)
9675                {
9676                   type = MkClassType(memberExp.member.exp.expType._class.string);
9677                   if(e)
9678                   {
9679                      e.destType = type;
9680                      e = e.next;
9681                      type = functionType.params.first;
9682                   }
9683                   else
9684                      type.refCount = 0;
9685                }
9686                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9687                {
9688                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9689                   type.byReference = functionType.byReference;
9690                   type.typedByReference = functionType.typedByReference;
9691                   if(e)
9692                   {
9693                      // Allow manually passing a class for typed object
9694                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9695                         e = e.next;
9696                      e.destType = type;
9697                      e = e.next;
9698                      type = functionType.params.first;
9699                   }
9700                   else
9701                      type.refCount = 0;
9702                   //extra = 1;
9703                }
9704             }
9705
9706             if(type && type.kind == voidType)
9707             {
9708                noParams = true;
9709                if(!type.refCount) FreeType(type);
9710                type = null;
9711             }
9712
9713             for( ; e; e = e.next)
9714             {
9715                if(!type && !emptyParams)
9716                {
9717                   yylloc = e.loc;
9718                   if(methodType && methodType.methodClass)
9719                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9720                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9721                         noParams ? 0 : functionType.params.count);
9722                   else
9723                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9724                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9725                         noParams ? 0 : functionType.params.count);
9726                   break;
9727                }
9728
9729                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9730                {
9731                   Type templatedType = null;
9732                   Class _class = methodType.usedClass;
9733                   ClassTemplateParameter curParam = null;
9734                   int id = 0;
9735                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9736                   {
9737                      Class sClass;
9738                      for(sClass = _class; sClass; sClass = sClass.base)
9739                      {
9740                         if(sClass.templateClass) sClass = sClass.templateClass;
9741                         id = 0;
9742                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9743                         {
9744                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9745                            {
9746                               Class nextClass;
9747                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9748                               {
9749                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9750                                  id += nextClass.templateParams.count;
9751                               }
9752                               break;
9753                            }
9754                            id++;
9755                         }
9756                         if(curParam) break;
9757                      }
9758                   }
9759                   if(curParam && _class.templateArgs[id].dataTypeString)
9760                   {
9761                      bool constant = type.constant;
9762                      ClassTemplateArgument arg = _class.templateArgs[id];
9763                      {
9764                         Context context = SetupTemplatesContext(_class);
9765
9766                         /*if(!arg.dataType)
9767                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9768                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9769                         FinishTemplatesContext(context);
9770                      }
9771
9772                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9773                      else if(templatedType.kind == pointerType)
9774                      {
9775                         Type t = templatedType.type;
9776                         while(t.kind == pointerType) t = t.type;
9777                         if(constant) t.constant = constant;
9778                      }
9779
9780                      e.destType = templatedType;
9781                      if(templatedType)
9782                      {
9783                         templatedType.passAsTemplate = true;
9784                         // templatedType.refCount++;
9785                      }
9786                   }
9787                   else
9788                   {
9789                      e.destType = type;
9790                      if(type) type.refCount++;
9791                   }
9792                }
9793                else
9794                {
9795                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9796                   {
9797                      e.destType = type.prev;
9798                      e.destType.refCount++;
9799                   }
9800                   else
9801                   {
9802                      e.destType = type;
9803                      if(type) type.refCount++;
9804                   }
9805                }
9806                // Don't reach the end for the ellipsis
9807                if(type && type.kind != ellipsisType)
9808                {
9809                   Type next = type.next;
9810                   if(!type.refCount) FreeType(type);
9811                   type = next;
9812                }
9813             }
9814
9815             if(type && type.kind != ellipsisType)
9816             {
9817                if(methodType && methodType.methodClass)
9818                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9819                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9820                      functionType.params.count + extra);
9821                else
9822                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9823                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9824                      functionType.params.count + extra);
9825             }
9826             yylloc = oldyylloc;
9827             if(type && !type.refCount) FreeType(type);
9828          }
9829          else
9830          {
9831             functionType = Type
9832             {
9833                refCount = 0;
9834                kind = TypeKind::functionType;
9835             };
9836
9837             if(exp.call.exp.type == identifierExp)
9838             {
9839                char * string = exp.call.exp.identifier.string;
9840                if(inCompiler)
9841                {
9842                   Symbol symbol;
9843                   Location oldyylloc = yylloc;
9844
9845                   yylloc = exp.call.exp.identifier.loc;
9846                   if(strstr(string, "__builtin_") == string)
9847                   {
9848                      if(exp.destType)
9849                      {
9850                         functionType.returnType = exp.destType;
9851                         exp.destType.refCount++;
9852                      }
9853                   }
9854                   else
9855                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9856                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9857                   globalContext.symbols.Add((BTNode)symbol);
9858                   if(strstr(symbol.string, "::"))
9859                      globalContext.hasNameSpace = true;
9860
9861                   yylloc = oldyylloc;
9862                }
9863             }
9864             else if(exp.call.exp.type == memberExp)
9865             {
9866                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9867                   exp.call.exp.member.member.string);*/
9868             }
9869             else
9870                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9871
9872             if(!functionType.returnType)
9873             {
9874                functionType.returnType = Type
9875                {
9876                   refCount = 1;
9877                   kind = intType;
9878                };
9879             }
9880          }
9881          if(functionType && functionType.kind == TypeKind::functionType)
9882          {
9883             exp.expType = functionType.returnType;
9884
9885             if(functionType.returnType)
9886                functionType.returnType.refCount++;
9887
9888             if(!functionType.refCount)
9889                FreeType(functionType);
9890          }
9891
9892          if(exp.call.arguments)
9893          {
9894             for(e = exp.call.arguments->first; e; e = e.next)
9895                ProcessExpressionType(e);
9896          }
9897          break;
9898       }
9899       case memberExp:
9900       {
9901          Type type;
9902          Location oldyylloc = yylloc;
9903          bool thisPtr;
9904          Expression checkExp = exp.member.exp;
9905          while(checkExp)
9906          {
9907             if(checkExp.type == castExp)
9908                checkExp = checkExp.cast.exp;
9909             else if(checkExp.type == bracketsExp)
9910                checkExp = checkExp.list ? checkExp.list->first : null;
9911             else
9912                break;
9913          }
9914
9915          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9916          exp.thisPtr = thisPtr;
9917
9918          // DOING THIS LATER NOW...
9919          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9920          {
9921             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9922             /* TODO: Name Space Fix ups
9923             if(!exp.member.member.classSym)
9924                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9925             */
9926          }
9927
9928          ProcessExpressionType(exp.member.exp);
9929          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9930             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9931          {
9932             exp.isConstant = false;
9933          }
9934          else
9935             exp.isConstant = exp.member.exp.isConstant;
9936          type = exp.member.exp.expType;
9937
9938          yylloc = exp.loc;
9939
9940          if(type && (type.kind == templateType))
9941          {
9942             Class _class = thisClass ? thisClass : currentClass;
9943             ClassTemplateParameter param = null;
9944             if(_class)
9945             {
9946                for(param = _class.templateParams.first; param; param = param.next)
9947                {
9948                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9949                      break;
9950                }
9951             }
9952             if(param && param.defaultArg.member)
9953             {
9954                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9955                if(argExp)
9956                {
9957                   Expression expMember = exp.member.exp;
9958                   Declarator decl;
9959                   OldList * specs = MkList();
9960                   char thisClassTypeString[1024];
9961
9962                   FreeIdentifier(exp.member.member);
9963
9964                   ProcessExpressionType(argExp);
9965
9966                   {
9967                      char * colon = strstr(param.defaultArg.memberString, "::");
9968                      if(colon)
9969                      {
9970                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9971                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9972                      }
9973                      else
9974                         strcpy(thisClassTypeString, _class.fullName);
9975                   }
9976
9977                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9978
9979                   exp.expType = ProcessType(specs, decl);
9980                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9981                   {
9982                      Class expClass = exp.expType._class.registered;
9983                      Class cClass = null;
9984                      int paramCount = 0;
9985                      int lastParam = -1;
9986
9987                      char templateString[1024];
9988                      ClassTemplateParameter param;
9989                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9990                      for(cClass = expClass; cClass; cClass = cClass.base)
9991                      {
9992                         int p = 0;
9993                         for(param = cClass.templateParams.first; param; param = param.next)
9994                         {
9995                            int id = p;
9996                            Class sClass;
9997                            ClassTemplateArgument arg;
9998                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9999                            arg = expClass.templateArgs[id];
10000
10001                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
10002                            {
10003                               ClassTemplateParameter cParam;
10004                               //int p = numParams - sClass.templateParams.count;
10005                               int p = 0;
10006                               Class nextClass;
10007                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
10008
10009                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
10010                               {
10011                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
10012                                  {
10013                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10014                                     {
10015                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
10016                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
10017                                        break;
10018                                     }
10019                                  }
10020                               }
10021                            }
10022
10023                            {
10024                               char argument[256];
10025                               argument[0] = '\0';
10026                               /*if(arg.name)
10027                               {
10028                                  strcat(argument, arg.name.string);
10029                                  strcat(argument, " = ");
10030                               }*/
10031                               switch(param.type)
10032                               {
10033                                  case expression:
10034                                  {
10035                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10036                                     char expString[1024];
10037                                     OldList * specs = MkList();
10038                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10039                                     Expression exp;
10040                                     char * string = PrintHexUInt64(arg.expression.ui64);
10041                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10042                                     delete string;
10043
10044                                     ProcessExpressionType(exp);
10045                                     ComputeExpression(exp);
10046                                     expString[0] = '\0';
10047                                     PrintExpression(exp, expString);
10048                                     strcat(argument, expString);
10049                                     // delete exp;
10050                                     FreeExpression(exp);
10051                                     break;
10052                                  }
10053                                  case identifier:
10054                                  {
10055                                     strcat(argument, arg.member.name);
10056                                     break;
10057                                  }
10058                                  case TemplateParameterType::type:
10059                                  {
10060                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10061                                     {
10062                                        if(!strcmp(arg.dataTypeString, "thisclass"))
10063                                           strcat(argument, thisClassTypeString);
10064                                        else
10065                                           strcat(argument, arg.dataTypeString);
10066                                     }
10067                                     break;
10068                                  }
10069                               }
10070                               if(argument[0])
10071                               {
10072                                  if(paramCount) strcat(templateString, ", ");
10073                                  if(lastParam != p - 1)
10074                                  {
10075                                     strcat(templateString, param.name);
10076                                     strcat(templateString, " = ");
10077                                  }
10078                                  strcat(templateString, argument);
10079                                  paramCount++;
10080                                  lastParam = p;
10081                               }
10082                               p++;
10083                            }
10084                         }
10085                      }
10086                      {
10087                         int len = strlen(templateString);
10088                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10089                         templateString[len++] = '>';
10090                         templateString[len++] = '\0';
10091                      }
10092                      {
10093                         Context context = SetupTemplatesContext(_class);
10094                         FreeType(exp.expType);
10095                         exp.expType = ProcessTypeString(templateString, false);
10096                         FinishTemplatesContext(context);
10097                      }
10098                   }
10099
10100                   if(!expMember.expType.isPointerType)
10101                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10102                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10103                   exp.type = bracketsExp;
10104                   exp.list = MkListOne(MkExpOp(null, '*',
10105                   /*opExp;
10106                   exp.op.op = '*';
10107                   exp.op.exp1 = null;
10108                   exp.op.exp2 = */
10109                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10110                      MkExpBrackets(MkListOne(
10111                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10112                            expMember))),
10113                               '+',
10114                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10115                               '+',
10116                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10117
10118                            ));
10119                }
10120             }
10121             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10122                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10123             {
10124                type = ProcessTemplateParameterType(type.templateParameter);
10125             }
10126          }
10127          // TODO: *** This seems to be where we should add method support for all basic types ***
10128          if(type && (type.kind == templateType));
10129          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10130                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10131                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10132                           (type.kind == pointerType && type.type.kind == charType)))
10133          {
10134             Identifier id = exp.member.member;
10135             TypeKind typeKind = type.kind;
10136             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10137             if(typeKind == subClassType && exp.member.exp.type == classExp)
10138             {
10139                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10140                typeKind = classType;
10141             }
10142
10143             if(id)
10144             {
10145                if(typeKind == intType || typeKind == enumType)
10146                   _class = eSystem_FindClass(privateModule, "int");
10147                else if(!_class)
10148                {
10149                   if(type.kind == classType && type._class && type._class.registered)
10150                   {
10151                      _class = type._class.registered;
10152                   }
10153                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10154                   {
10155                      _class = FindClass("char *").registered;
10156                   }
10157                   else if(type.kind == pointerType)
10158                   {
10159                      _class = eSystem_FindClass(privateModule, "uintptr");
10160                      FreeType(exp.expType);
10161                      exp.expType = ProcessTypeString("uintptr", false);
10162                      exp.byReference = true;
10163                   }
10164                   else
10165                   {
10166                      char string[1024] = "";
10167                      Symbol classSym;
10168                      PrintTypeNoConst(type, string, false, true);
10169                      classSym = FindClass(string);
10170                      if(classSym) _class = classSym.registered;
10171                   }
10172                }
10173             }
10174
10175             if(_class && id)
10176             {
10177                /*bool thisPtr =
10178                   (exp.member.exp.type == identifierExp &&
10179                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10180                Property prop = null;
10181                Method method = null;
10182                DataMember member = null;
10183                Property revConvert = null;
10184                ClassProperty classProp = null;
10185
10186                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10187                   exp.member.memberType = propertyMember;
10188
10189                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10190                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10191
10192                if(typeKind != subClassType)
10193                {
10194                   // Prioritize data members over properties for "this"
10195                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10196                   {
10197                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10198                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10199                      {
10200                         prop = eClass_FindProperty(_class, id.string, privateModule);
10201                         if(prop)
10202                            member = null;
10203                      }
10204                      if(!member && !prop)
10205                         prop = eClass_FindProperty(_class, id.string, privateModule);
10206                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10207                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10208                         exp.member.thisPtr = true;
10209                   }
10210                   // Prioritize properties over data members otherwise
10211                   else
10212                   {
10213                      bool useMemberForNonConst = false;
10214                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10215                      if(!id.classSym)
10216                      {
10217                         prop = eClass_FindProperty(_class, id.string, null);
10218
10219                         useMemberForNonConst = prop && exp.destType &&
10220                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10221                               !strncmp(prop.dataTypeString, "const ", 6);
10222
10223                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10224                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10225                      }
10226
10227                      if((!prop || useMemberForNonConst) && !member)
10228                      {
10229                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10230                         if(!method)
10231                         {
10232                            prop = eClass_FindProperty(_class, id.string, privateModule);
10233
10234                            useMemberForNonConst |= prop && exp.destType &&
10235                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10236                                  !strncmp(prop.dataTypeString, "const ", 6);
10237
10238                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10239                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10240                         }
10241                      }
10242
10243                      if(member && prop)
10244                      {
10245                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10246                            prop = null;
10247                         else
10248                            member = null;
10249                      }
10250                   }
10251                }
10252                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10253                   method = eClass_FindMethod(_class, id.string, privateModule);
10254                if(!prop && !member && !method)
10255                {
10256                   if(typeKind == subClassType)
10257                   {
10258                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10259                      if(classProp)
10260                      {
10261                         exp.member.memberType = classPropertyMember;
10262                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10263                      }
10264                      else
10265                      {
10266                         // Assume this is a class_data member
10267                         char structName[1024];
10268                         Identifier id = exp.member.member;
10269                         Expression classExp = exp.member.exp;
10270                         type.refCount++;
10271
10272                         FreeType(classExp.expType);
10273                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10274
10275                         strcpy(structName, "__ecereClassData_");
10276                         FullClassNameCat(structName, type._class.string, false);
10277                         exp.type = pointerExp;
10278                         exp.member.member = id;
10279
10280                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10281                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10282                               MkExpBrackets(MkListOne(MkExpOp(
10283                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10284                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10285                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10286                                  )));
10287
10288                         FreeType(type);
10289
10290                         ProcessExpressionType(exp);
10291                         return;
10292                      }
10293                   }
10294                   else
10295                   {
10296                      // Check for reverse conversion
10297                      // (Convert in an instantiation later, so that we can use
10298                      //  deep properties system)
10299                      Symbol classSym = FindClass(id.string);
10300                      if(classSym)
10301                      {
10302                         Class convertClass = classSym.registered;
10303                         if(convertClass)
10304                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10305                      }
10306                   }
10307                }
10308
10309                //if(!exp.member.exp.destType)
10310                if(exp.member.exp.destType)
10311                   FreeType(exp.member.exp.destType);
10312                {
10313                   if(method && !method._class.symbol)
10314                      method._class.symbol = FindClass(method._class.fullName);
10315                   if(prop && !prop._class.symbol)
10316                      prop._class.symbol = FindClass(prop._class.fullName);
10317
10318                   exp.member.exp.destType = Type
10319                   {
10320                      refCount = 1;
10321                      kind = classType;
10322                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10323                      // wasThisClass = type ? type.wasThisClass : false;
10324                   };
10325                }
10326
10327                if(prop)
10328                {
10329                   exp.member.memberType = propertyMember;
10330                   if(!prop.dataType)
10331                      ProcessPropertyType(prop);
10332                   exp.expType = prop.dataType;
10333                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10334                   {
10335                      Type type { };
10336                      CopyTypeInto(type, exp.expType);
10337                      type.refCount = 1;
10338                      type.constant = true;
10339                      exp.expType = type;
10340                   }
10341                   else if(prop.dataType)
10342                      prop.dataType.refCount++;
10343                }
10344                else if(member)
10345                {
10346                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10347                   {
10348                      FreeExpContents(exp);
10349                      exp.type = identifierExp;
10350                      exp.identifier = MkIdentifier("class");
10351                      ProcessExpressionType(exp);
10352                      return;
10353                   }
10354
10355                   exp.member.memberType = dataMember;
10356                   DeclareStruct(_class.fullName, false);
10357                   if(!member.dataType)
10358                   {
10359                      Context context = SetupTemplatesContext(_class);
10360                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10361                      FinishTemplatesContext(context);
10362                   }
10363                   exp.expType = member.dataType;
10364                   if(member.dataType) member.dataType.refCount++;
10365                }
10366                else if(revConvert)
10367                {
10368                   exp.member.memberType = reverseConversionMember;
10369                   exp.expType = MkClassType(revConvert._class.fullName);
10370                }
10371                else if(method)
10372                {
10373                   //if(inCompiler)
10374                   {
10375                      /*if(id._class)
10376                      {
10377                         exp.type = identifierExp;
10378                         exp.identifier = exp.member.member;
10379                      }
10380                      else*/
10381                         exp.member.memberType = methodMember;
10382                   }
10383                   if(!method.dataType)
10384                      ProcessMethodType(method);
10385                   exp.expType = Type
10386                   {
10387                      refCount = 1;
10388                      kind = methodType;
10389                      method = method;
10390                   };
10391
10392                   // Tricky spot here... To use instance versus class virtual table
10393                   // Put it back to what it was... What did we break?
10394
10395                   // Had to put it back for overriding Main of Thread global instance
10396
10397                   //exp.expType.methodClass = _class;
10398                   exp.expType.methodClass = (id && id._class) ? _class : null;
10399
10400                   // Need the actual class used for templated classes
10401                   exp.expType.usedClass = _class;
10402                }
10403                else if(!classProp)
10404                {
10405                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10406                   {
10407                      FreeExpContents(exp);
10408                      exp.type = identifierExp;
10409                      exp.identifier = MkIdentifier("class");
10410                      FreeType(exp.expType);
10411                      exp.expType = MkClassType("ecere::com::Class");
10412                      return;
10413                   }
10414                   yylloc = exp.member.member.loc;
10415                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10416                   if(inCompiler)
10417                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10418                }
10419
10420                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10421                {
10422                   Class tClass;
10423
10424                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10425                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10426
10427                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10428                   {
10429                      int id = 0;
10430                      ClassTemplateParameter curParam = null;
10431                      Class sClass;
10432
10433                      for(sClass = tClass; sClass; sClass = sClass.base)
10434                      {
10435                         id = 0;
10436                         if(sClass.templateClass) sClass = sClass.templateClass;
10437                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10438                         {
10439                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10440                            {
10441                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10442                                  id += sClass.templateParams.count;
10443                               break;
10444                            }
10445                            id++;
10446                         }
10447                         if(curParam) break;
10448                      }
10449
10450                      if(curParam && tClass.templateArgs[id].dataTypeString)
10451                      {
10452                         ClassTemplateArgument arg = tClass.templateArgs[id];
10453                         Context context = SetupTemplatesContext(tClass);
10454                         bool constant = exp.expType.constant;
10455                         /*if(!arg.dataType)
10456                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10457                         FreeType(exp.expType);
10458
10459                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10460                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10461                         else if(exp.expType.kind == pointerType)
10462                         {
10463                            Type t = exp.expType.type;
10464                            while(t.kind == pointerType) t = t.type;
10465                            if(constant) t.constant = constant;
10466                         }
10467                         if(exp.expType)
10468                         {
10469                            if(exp.expType.kind == thisClassType)
10470                            {
10471                               FreeType(exp.expType);
10472                               exp.expType = ReplaceThisClassType(_class);
10473                            }
10474
10475                            if(tClass.templateClass && (exp.expType.kind != templateType || (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType))))
10476                               exp.expType.passAsTemplate = true;
10477                            //exp.expType.refCount++;
10478                            if(!exp.destType)
10479                            {
10480                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10481                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10482                               else if(exp.destType.kind == pointerType)
10483                               {
10484                                  Type t = exp.destType.type;
10485                                  while(t.kind == pointerType) t = t.type;
10486                                  if(constant) t.constant = constant;
10487                               }
10488
10489                               //exp.destType.refCount++;
10490
10491                               if(exp.destType.kind == thisClassType)
10492                               {
10493                                  FreeType(exp.destType);
10494                                  exp.destType = ReplaceThisClassType(_class);
10495                               }
10496                            }
10497                         }
10498                         FinishTemplatesContext(context);
10499                      }
10500                   }
10501                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10502                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10503                   {
10504                      int id = 0;
10505                      ClassTemplateParameter curParam = null;
10506                      Class sClass;
10507
10508                      for(sClass = tClass; sClass; sClass = sClass.base)
10509                      {
10510                         id = 0;
10511                         if(sClass.templateClass) sClass = sClass.templateClass;
10512                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10513                         {
10514                            if(curParam.type == TemplateParameterType::type &&
10515                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10516                            {
10517                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10518                                  id += sClass.templateParams.count;
10519                               break;
10520                            }
10521                            id++;
10522                         }
10523                         if(curParam) break;
10524                      }
10525
10526                      if(curParam)
10527                      {
10528                         ClassTemplateArgument arg = tClass.templateArgs[id];
10529                         Context context = SetupTemplatesContext(tClass);
10530                         Type basicType;
10531                         /*if(!arg.dataType)
10532                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10533
10534                         basicType = ProcessTypeString(arg.dataTypeString, false);
10535                         if(basicType)
10536                         {
10537                            if(basicType.kind == thisClassType)
10538                            {
10539                               FreeType(basicType);
10540                               basicType = ReplaceThisClassType(_class);
10541                            }
10542
10543                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10544                            if(tClass.templateClass)
10545                               basicType.passAsTemplate = true;
10546                            */
10547
10548                            FreeType(exp.expType);
10549
10550                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10551                            //exp.expType.refCount++;
10552                            if(!exp.destType)
10553                            {
10554                               exp.destType = exp.expType;
10555                               exp.destType.refCount++;
10556                            }
10557
10558                            {
10559                               Expression newExp { };
10560                               OldList * specs = MkList();
10561                               Declarator decl;
10562                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10563                               *newExp = *exp;
10564                               if(exp.destType) exp.destType.refCount++;
10565                               if(exp.expType)  exp.expType.refCount++;
10566                               exp.type = castExp;
10567                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10568                               exp.cast.exp = newExp;
10569                               //FreeType(exp.expType);
10570                               //exp.expType = null;
10571                               //ProcessExpressionType(sourceExp);
10572                            }
10573                         }
10574                         FinishTemplatesContext(context);
10575                      }
10576                   }
10577                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10578                   {
10579                      Class expClass = exp.expType._class.registered;
10580                      if(expClass)
10581                      {
10582                         Class cClass = null;
10583                         int p = 0;
10584                         int paramCount = 0;
10585                         int lastParam = -1;
10586                         char templateString[1024];
10587                         ClassTemplateParameter param;
10588                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10589                         while(cClass != expClass)
10590                         {
10591                            Class sClass;
10592                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10593                            cClass = sClass;
10594
10595                            for(param = cClass.templateParams.first; param; param = param.next)
10596                            {
10597                               Class cClassCur = null;
10598                               int cp = 0;
10599                               ClassTemplateParameter paramCur = null;
10600                               ClassTemplateArgument arg;
10601                               while(cClassCur != tClass && !paramCur)
10602                               {
10603                                  Class sClassCur;
10604                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10605                                  cClassCur = sClassCur;
10606
10607                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10608                                  {
10609                                     if(!strcmp(paramCur.name, param.name))
10610                                     {
10611
10612                                        break;
10613                                     }
10614                                     cp++;
10615                                  }
10616                               }
10617                               if(paramCur && paramCur.type == TemplateParameterType::type)
10618                                  arg = tClass.templateArgs[cp];
10619                               else
10620                                  arg = expClass.templateArgs[p];
10621
10622                               {
10623                                  char argument[256];
10624                                  argument[0] = '\0';
10625                                  /*if(arg.name)
10626                                  {
10627                                     strcat(argument, arg.name.string);
10628                                     strcat(argument, " = ");
10629                                  }*/
10630                                  switch(param.type)
10631                                  {
10632                                     case expression:
10633                                     {
10634                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10635                                        char expString[1024];
10636                                        OldList * specs = MkList();
10637                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10638                                        Expression exp;
10639                                        char * string = PrintHexUInt64(arg.expression.ui64);
10640                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10641                                        delete string;
10642
10643                                        ProcessExpressionType(exp);
10644                                        ComputeExpression(exp);
10645                                        expString[0] = '\0';
10646                                        PrintExpression(exp, expString);
10647                                        strcat(argument, expString);
10648                                        // delete exp;
10649                                        FreeExpression(exp);
10650                                        break;
10651                                     }
10652                                     case identifier:
10653                                     {
10654                                        strcat(argument, arg.member.name);
10655                                        break;
10656                                     }
10657                                     case TemplateParameterType::type:
10658                                     {
10659                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10660                                           strcat(argument, arg.dataTypeString);
10661                                        break;
10662                                     }
10663                                  }
10664                                  if(argument[0])
10665                                  {
10666                                     if(paramCount) strcat(templateString, ", ");
10667                                     if(lastParam != p - 1)
10668                                     {
10669                                        strcat(templateString, param.name);
10670                                        strcat(templateString, " = ");
10671                                     }
10672                                     strcat(templateString, argument);
10673                                     paramCount++;
10674                                     lastParam = p;
10675                                  }
10676                               }
10677                               p++;
10678                            }
10679                         }
10680                         {
10681                            int len = strlen(templateString);
10682                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10683                            templateString[len++] = '>';
10684                            templateString[len++] = '\0';
10685                         }
10686
10687                         FreeType(exp.expType);
10688                         {
10689                            Context context = SetupTemplatesContext(tClass);
10690                            exp.expType = ProcessTypeString(templateString, false);
10691                            FinishTemplatesContext(context);
10692                         }
10693                      }
10694                   }
10695                }
10696             }
10697             else
10698                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10699          }
10700          else if(type && (type.kind == structType || type.kind == unionType))
10701          {
10702             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10703             if(memberType)
10704             {
10705                exp.expType = memberType;
10706                if(memberType)
10707                   memberType.refCount++;
10708             }
10709          }
10710          else
10711          {
10712             char expString[10240];
10713             expString[0] = '\0';
10714             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10715             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10716          }
10717
10718          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10719          {
10720             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10721             {
10722                Identifier id = exp.member.member;
10723                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10724                if(_class)
10725                {
10726                   FreeType(exp.expType);
10727                   exp.expType = ReplaceThisClassType(_class);
10728                }
10729             }
10730          }
10731          yylloc = oldyylloc;
10732          break;
10733       }
10734       // Convert x->y into (*x).y
10735       case pointerExp:
10736       {
10737          Type destType = exp.destType;
10738
10739          // DOING THIS LATER NOW...
10740          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10741          {
10742             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10743             /* TODO: Name Space Fix ups
10744             if(!exp.member.member.classSym)
10745                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10746             */
10747          }
10748
10749          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10750          exp.type = memberExp;
10751          if(destType)
10752             destType.count++;
10753          ProcessExpressionType(exp);
10754          if(destType)
10755             destType.count--;
10756          break;
10757       }
10758       case classSizeExp:
10759       {
10760          //ComputeExpression(exp);
10761
10762          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10763          if(classSym && classSym.registered)
10764          {
10765             if(classSym.registered.type == noHeadClass)
10766             {
10767                char name[1024];
10768                name[0] = '\0';
10769                DeclareStruct(classSym.string, false);
10770                FreeSpecifier(exp._class);
10771                exp.type = typeSizeExp;
10772                FullClassNameCat(name, classSym.string, false);
10773                exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10774             }
10775             else
10776             {
10777                if(classSym.registered.fixed)
10778                {
10779                   FreeSpecifier(exp._class);
10780                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10781                   exp.type = constantExp;
10782                }
10783                else
10784                {
10785                   char className[1024];
10786                   strcpy(className, "__ecereClass_");
10787                   FullClassNameCat(className, classSym.string, true);
10788                   //MangleClassName(className);
10789
10790                   DeclareClass(classSym, className);
10791
10792                   FreeExpContents(exp);
10793                   exp.type = pointerExp;
10794                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10795                   exp.member.member = MkIdentifier("structSize");
10796                }
10797             }
10798          }
10799
10800          exp.expType = Type
10801          {
10802             refCount = 1;
10803             kind = intSizeType;
10804          };
10805          // exp.isConstant = true;
10806          break;
10807       }
10808       case typeSizeExp:
10809       {
10810          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10811
10812          exp.expType = Type
10813          {
10814             refCount = 1;
10815             kind = intSizeType;
10816          };
10817          exp.isConstant = true;
10818
10819          DeclareType(type, false, false);
10820          FreeType(type);
10821          break;
10822       }
10823       case castExp:
10824       {
10825          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10826          type.count = 1;
10827          FreeType(exp.cast.exp.destType);
10828          exp.cast.exp.destType = type;
10829          type.refCount++;
10830          type.casted = true;
10831          ProcessExpressionType(exp.cast.exp);
10832          type.casted = false;
10833          type.count = 0;
10834          exp.expType = type;
10835          //type.refCount++;
10836
10837          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10838          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10839          {
10840             void * prev = exp.prev, * next = exp.next;
10841             Type expType = exp.cast.exp.destType;
10842             Expression castExp = exp.cast.exp;
10843             Type destType = exp.destType;
10844
10845             if(expType) expType.refCount++;
10846
10847             //FreeType(exp.destType);
10848             FreeType(exp.expType);
10849             FreeTypeName(exp.cast.typeName);
10850
10851             *exp = *castExp;
10852             FreeType(exp.expType);
10853             FreeType(exp.destType);
10854
10855             exp.expType = expType;
10856             exp.destType = destType;
10857
10858             delete castExp;
10859
10860             exp.prev = prev;
10861             exp.next = next;
10862
10863          }
10864          else
10865          {
10866             exp.isConstant = exp.cast.exp.isConstant;
10867          }
10868          //FreeType(type);
10869          break;
10870       }
10871       case extensionInitializerExp:
10872       {
10873          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10874          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10875          // ProcessInitializer(exp.initializer.initializer, type);
10876          exp.expType = type;
10877          break;
10878       }
10879       case vaArgExp:
10880       {
10881          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10882          ProcessExpressionType(exp.vaArg.exp);
10883          exp.expType = type;
10884          break;
10885       }
10886       case conditionExp:
10887       {
10888          Expression e;
10889          exp.isConstant = true;
10890
10891          FreeType(exp.cond.cond.destType);
10892          exp.cond.cond.destType = MkClassType("bool");
10893          exp.cond.cond.destType.truth = true;
10894          ProcessExpressionType(exp.cond.cond);
10895          if(!exp.cond.cond.isConstant)
10896             exp.isConstant = false;
10897          for(e = exp.cond.exp->first; e; e = e.next)
10898          {
10899             if(!e.next)
10900             {
10901                FreeType(e.destType);
10902                e.destType = exp.destType;
10903                if(e.destType) e.destType.refCount++;
10904             }
10905             ProcessExpressionType(e);
10906             if(!e.next)
10907             {
10908                exp.expType = e.expType;
10909                if(e.expType) e.expType.refCount++;
10910             }
10911             if(!e.isConstant)
10912                exp.isConstant = false;
10913          }
10914
10915          FreeType(exp.cond.elseExp.destType);
10916          // Added this check if we failed to find an expType
10917          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10918
10919          // Reversed it...
10920          exp.cond.elseExp.destType = exp.destType ? exp.destType : exp.expType;
10921
10922          if(exp.cond.elseExp.destType)
10923             exp.cond.elseExp.destType.refCount++;
10924          ProcessExpressionType(exp.cond.elseExp);
10925
10926          // FIXED THIS: Was done before calling process on elseExp
10927          if(!exp.cond.elseExp.isConstant)
10928             exp.isConstant = false;
10929          break;
10930       }
10931       case extensionCompoundExp:
10932       {
10933          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10934          {
10935             Statement last = exp.compound.compound.statements->last;
10936             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10937             {
10938                ((Expression)last.expressions->last).destType = exp.destType;
10939                if(exp.destType)
10940                   exp.destType.refCount++;
10941             }
10942             ProcessStatement(exp.compound);
10943             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10944             if(exp.expType)
10945                exp.expType.refCount++;
10946          }
10947          break;
10948       }
10949       case classExp:
10950       {
10951          Specifier spec = exp._classExp.specifiers->first;
10952          if(spec && spec.type == nameSpecifier)
10953          {
10954             exp.expType = MkClassType(spec.name);
10955             exp.expType.kind = subClassType;
10956             exp.byReference = true;
10957          }
10958          else
10959          {
10960             exp.expType = MkClassType("ecere::com::Class");
10961             exp.byReference = true;
10962          }
10963          break;
10964       }
10965       case classDataExp:
10966       {
10967          Class _class = thisClass ? thisClass : currentClass;
10968          if(_class)
10969          {
10970             Identifier id = exp.classData.id;
10971             char structName[1024];
10972             Expression classExp;
10973             strcpy(structName, "__ecereClassData_");
10974             FullClassNameCat(structName, _class.fullName, false);
10975             exp.type = pointerExp;
10976             exp.member.member = id;
10977             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10978                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10979             else
10980                classExp = MkExpIdentifier(MkIdentifier("class"));
10981
10982             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10983                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10984                   MkExpBrackets(MkListOne(MkExpOp(
10985                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10986                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10987                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10988                      )));
10989
10990             ProcessExpressionType(exp);
10991             return;
10992          }
10993          break;
10994       }
10995       case arrayExp:
10996       {
10997          Type type = null;
10998          const char * typeString = null;
10999          char typeStringBuf[1024];
11000          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
11001             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
11002          {
11003             Class templateClass = exp.destType._class.registered;
11004             typeString = templateClass.templateArgs[2].dataTypeString;
11005          }
11006          else if(exp.list)
11007          {
11008             // Guess type from expressions in the array
11009             Expression e;
11010             for(e = exp.list->first; e; e = e.next)
11011             {
11012                ProcessExpressionType(e);
11013                if(e.expType)
11014                {
11015                   if(!type) { type = e.expType; type.refCount++; }
11016                   else
11017                   {
11018                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11019                      if(!MatchTypeExpression(e, type, null, false, true))
11020                      {
11021                         FreeType(type);
11022                         type = e.expType;
11023                         e.expType = null;
11024
11025                         e = exp.list->first;
11026                         ProcessExpressionType(e);
11027                         if(e.expType)
11028                         {
11029                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
11030                            if(!MatchTypeExpression(e, type, null, false, true))
11031                            {
11032                               FreeType(e.expType);
11033                               e.expType = null;
11034                               FreeType(type);
11035                               type = null;
11036                               break;
11037                            }
11038                         }
11039                      }
11040                   }
11041                   if(e.expType)
11042                   {
11043                      FreeType(e.expType);
11044                      e.expType = null;
11045                   }
11046                }
11047             }
11048             if(type)
11049             {
11050                typeStringBuf[0] = '\0';
11051                PrintTypeNoConst(type, typeStringBuf, false, true);
11052                typeString = typeStringBuf;
11053                FreeType(type);
11054                type = null;
11055             }
11056          }
11057          if(typeString)
11058          {
11059             /*
11060             (Container)& (struct BuiltInContainer)
11061             {
11062                ._vTbl = class(BuiltInContainer)._vTbl,
11063                ._class = class(BuiltInContainer),
11064                .refCount = 0,
11065                .data = (int[]){ 1, 7, 3, 4, 5 },
11066                .count = 5,
11067                .type = class(int),
11068             }
11069             */
11070             char templateString[1024];
11071             OldList * initializers = MkList();
11072             OldList * structInitializers = MkList();
11073             OldList * specs = MkList();
11074             Expression expExt;
11075             Declarator decl = SpecDeclFromString(typeString, specs, null);
11076             sprintf(templateString, "Container<%s>", typeString);
11077
11078             if(exp.list)
11079             {
11080                Expression e;
11081                type = ProcessTypeString(typeString, false);
11082                while((e = exp.list->first))
11083                {
11084                   exp.list->Remove(e);
11085                   e.destType = type;
11086                   type.refCount++;
11087                   ProcessExpressionType(e);
11088                   ListAdd(initializers, MkInitializerAssignment(e));
11089                }
11090                FreeType(type);
11091                delete exp.list;
11092             }
11093
11094             DeclareStruct("ecere::com::BuiltInContainer", false);
11095
11096             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11097                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11098             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11099                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11100             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11101                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11102             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11103                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11104                MkInitializerList(initializers))));
11105                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11106             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11107                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11108             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11109                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11110             exp.expType = ProcessTypeString(templateString, false);
11111             exp.type = bracketsExp;
11112             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11113                MkExpOp(null, '&',
11114                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11115                   MkInitializerList(structInitializers)))));
11116             ProcessExpressionType(expExt);
11117          }
11118          else
11119          {
11120             exp.expType = ProcessTypeString("Container", false);
11121             Compiler_Error($"Couldn't determine type of array elements\n");
11122          }
11123          break;
11124       }
11125    }
11126
11127    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11128    {
11129       FreeType(exp.expType);
11130       exp.expType = ReplaceThisClassType(thisClass);
11131    }
11132
11133    // Resolve structures here
11134    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11135    {
11136       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11137       // TODO: Fix members reference...
11138       if(symbol)
11139       {
11140          if(exp.expType.kind != enumType)
11141          {
11142             Type member;
11143             String enumName = CopyString(exp.expType.enumName);
11144
11145             // Fixed a memory leak on self-referencing C structs typedefs
11146             // by instantiating a new type rather than simply copying members
11147             // into exp.expType
11148             FreeType(exp.expType);
11149             exp.expType = Type { };
11150             exp.expType.kind = symbol.type.kind;
11151             exp.expType.refCount++;
11152             exp.expType.enumName = enumName;
11153
11154             exp.expType.members = symbol.type.members;
11155             for(member = symbol.type.members.first; member; member = member.next)
11156                member.refCount++;
11157          }
11158          else
11159          {
11160             NamedLink64 member;
11161             for(member = symbol.type.members.first; member; member = member.next)
11162             {
11163                NamedLink64 value { name = CopyString(member.name) };
11164                exp.expType.members.Add(value);
11165             }
11166          }
11167       }
11168    }
11169
11170    yylloc = exp.loc;
11171    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11172    else if(exp.destType && !exp.destType.keepCast)
11173    {
11174       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11175          exp.needTemplateCast = 1;
11176
11177       if(exp.destType.kind == voidType);
11178       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11179       {
11180          if(!exp.destType.count || unresolved)
11181          {
11182             if(!exp.expType)
11183             {
11184                yylloc = exp.loc;
11185                if(exp.destType.kind != ellipsisType)
11186                {
11187                   char type2[1024];
11188                   type2[0] = '\0';
11189                   if(inCompiler)
11190                   {
11191                      char expString[10240];
11192                      expString[0] = '\0';
11193
11194                      PrintType(exp.destType, type2, false, true);
11195
11196                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11197                      if(unresolved)
11198                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11199                      else if(exp.type != dummyExp)
11200                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11201                   }
11202                }
11203                else
11204                {
11205                   char expString[10240] ;
11206                   expString[0] = '\0';
11207                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11208
11209                   if(unresolved)
11210                      Compiler_Error($"unresolved identifier %s\n", expString);
11211                   else if(exp.type != dummyExp)
11212                      Compiler_Error($"couldn't determine type of %s\n", expString);
11213                }
11214             }
11215             else
11216             {
11217                char type1[1024];
11218                char type2[1024];
11219                type1[0] = '\0';
11220                type2[0] = '\0';
11221                if(inCompiler)
11222                {
11223                   PrintType(exp.expType, type1, false, true);
11224                   PrintType(exp.destType, type2, false, true);
11225                }
11226
11227                //CheckExpressionType(exp, exp.destType, false);
11228
11229                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11230                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11231                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11232                else
11233                {
11234                   char expString[10240];
11235                   expString[0] = '\0';
11236                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11237
11238 #ifdef _DEBUG
11239                   CheckExpressionType(exp, exp.destType, false, true);
11240 #endif
11241                   // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11242                   if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11243                                      !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11244                                      !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11245                                      !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11246                      Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11247
11248                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11249                   FreeType(exp.expType);
11250                   exp.destType.refCount++;
11251                   exp.expType = exp.destType;
11252                }
11253             }
11254          }
11255       }
11256       // Cast function pointers to void * as eC already checked compatibility
11257       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11258               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11259       {
11260          Expression nbExp = GetNonBracketsExp(exp);
11261          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11262          {
11263             Expression e = MoveExpContents(exp);
11264             exp.cast.exp = MkExpBrackets(MkListOne(e));
11265             exp.type = castExp;
11266             exp.cast.exp.destType = exp.destType;
11267             if(exp.destType) exp.destType.refCount++;
11268             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11269          }
11270       }
11271    }
11272    else if(unresolved)
11273    {
11274       if(exp.identifier._class && exp.identifier._class.name)
11275          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11276       else if(exp.identifier.string && exp.identifier.string[0])
11277          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11278    }
11279    else if(!exp.expType && exp.type != dummyExp)
11280    {
11281       char expString[10240];
11282       expString[0] = '\0';
11283       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11284       Compiler_Error($"couldn't determine type of %s\n", expString);
11285    }
11286
11287    // Let's try to support any_object & typed_object here:
11288    if(inCompiler)
11289       ApplyAnyObjectLogic(exp);
11290
11291    // Mark nohead classes as by reference, unless we're casting them to an integral type
11292    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11293       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11294          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11295           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11296    {
11297       exp.byReference = true;
11298    }
11299    yylloc = oldyylloc;
11300 }
11301
11302 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11303 {
11304    // THIS CODE WILL FIND NEXT MEMBER...
11305    if(*curMember)
11306    {
11307       *curMember = (*curMember).next;
11308
11309       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11310       {
11311          *curMember = subMemberStack[--(*subMemberStackPos)];
11312          *curMember = (*curMember).next;
11313       }
11314
11315       // SKIP ALL PROPERTIES HERE...
11316       while((*curMember) && (*curMember).isProperty)
11317          *curMember = (*curMember).next;
11318
11319       if(subMemberStackPos)
11320       {
11321          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11322          {
11323             subMemberStack[(*subMemberStackPos)++] = *curMember;
11324
11325             *curMember = (*curMember).members.first;
11326             while(*curMember && (*curMember).isProperty)
11327                *curMember = (*curMember).next;
11328          }
11329       }
11330    }
11331    while(!*curMember)
11332    {
11333       if(!*curMember)
11334       {
11335          if(subMemberStackPos && *subMemberStackPos)
11336          {
11337             *curMember = subMemberStack[--(*subMemberStackPos)];
11338             *curMember = (*curMember).next;
11339          }
11340          else
11341          {
11342             Class lastCurClass = *curClass;
11343
11344             if(*curClass == _class) break;     // REACHED THE END
11345
11346             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11347             *curMember = (*curClass).membersAndProperties.first;
11348          }
11349
11350          while((*curMember) && (*curMember).isProperty)
11351             *curMember = (*curMember).next;
11352          if(subMemberStackPos)
11353          {
11354             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11355             {
11356                subMemberStack[(*subMemberStackPos)++] = *curMember;
11357
11358                *curMember = (*curMember).members.first;
11359                while(*curMember && (*curMember).isProperty)
11360                   *curMember = (*curMember).next;
11361             }
11362          }
11363       }
11364    }
11365 }
11366
11367
11368 static void ProcessInitializer(Initializer init, Type type)
11369 {
11370    switch(init.type)
11371    {
11372       case expInitializer:
11373          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11374          {
11375             // TESTING THIS FOR SHUTTING = 0 WARNING
11376             if(init.exp && !init.exp.destType)
11377             {
11378                FreeType(init.exp.destType);
11379                init.exp.destType = type;
11380                if(type) type.refCount++;
11381             }
11382             if(init.exp)
11383             {
11384                ProcessExpressionType(init.exp);
11385                init.isConstant = init.exp.isConstant;
11386             }
11387             break;
11388          }
11389          else
11390          {
11391             Expression exp = init.exp;
11392             Instantiation inst = exp.instance;
11393             MembersInit members;
11394
11395             init.type = listInitializer;
11396             init.list = MkList();
11397
11398             if(inst.members)
11399             {
11400                for(members = inst.members->first; members; members = members.next)
11401                {
11402                   if(members.type == dataMembersInit)
11403                   {
11404                      MemberInit member;
11405                      for(member = members.dataMembers->first; member; member = member.next)
11406                      {
11407                         ListAdd(init.list, member.initializer);
11408                         member.initializer = null;
11409                      }
11410                   }
11411                   // Discard all MembersInitMethod
11412                }
11413             }
11414             FreeExpression(exp);
11415          }
11416       case listInitializer:
11417       {
11418          Initializer i;
11419          Type initializerType = null;
11420          Class curClass = null;
11421          DataMember curMember = null;
11422          DataMember subMemberStack[256];
11423          int subMemberStackPos = 0;
11424
11425          if(type && type.kind == arrayType)
11426             initializerType = Dereference(type);
11427          else if(type && (type.kind == structType || type.kind == unionType))
11428             initializerType = type.members.first;
11429
11430          for(i = init.list->first; i; i = i.next)
11431          {
11432             if(type && type.kind == classType && type._class && type._class.registered)
11433             {
11434                // 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)
11435                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11436                // TODO: Generate error on initializing a private data member this way from another module...
11437                if(curMember)
11438                {
11439                   if(!curMember.dataType)
11440                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11441                   initializerType = curMember.dataType;
11442                }
11443             }
11444             ProcessInitializer(i, initializerType);
11445             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11446                initializerType = initializerType.next;
11447             if(!i.isConstant)
11448                init.isConstant = false;
11449          }
11450
11451          if(type && type.kind == arrayType)
11452             FreeType(initializerType);
11453
11454          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11455          {
11456             Compiler_Error($"Assigning list initializer to non list\n");
11457          }
11458          break;
11459       }
11460    }
11461 }
11462
11463 static void ProcessSpecifier(Specifier spec, bool declareStruct)
11464 {
11465    switch(spec.type)
11466    {
11467       case baseSpecifier:
11468       {
11469          if(spec.specifier == THISCLASS)
11470          {
11471             if(thisClass)
11472             {
11473                spec.type = nameSpecifier;
11474                spec.name = ReplaceThisClass(thisClass);
11475                spec.symbol = FindClass(spec.name);
11476                ProcessSpecifier(spec, declareStruct);
11477             }
11478          }
11479          break;
11480       }
11481       case nameSpecifier:
11482       {
11483          Symbol symbol = FindType(curContext, spec.name);
11484          if(symbol)
11485             DeclareType(symbol.type, true, true);
11486          else if((symbol = spec.symbol /*FindClass(spec.name)*/) && symbol.registered && symbol.registered.type == structClass && declareStruct)
11487             DeclareStruct(spec.name, false);
11488          break;
11489       }
11490       case enumSpecifier:
11491       {
11492          Enumerator e;
11493          if(spec.list)
11494          {
11495             for(e = spec.list->first; e; e = e.next)
11496             {
11497                if(e.exp)
11498                   ProcessExpressionType(e.exp);
11499             }
11500          }
11501          // Fall through for IDE type processing
11502          if(inCompiler)
11503             break;
11504       }
11505       case structSpecifier:
11506       case unionSpecifier:
11507       {
11508          if(spec.definitions)
11509          {
11510             //ClassDef def;
11511             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11512             //if(symbol)
11513                ProcessClass(spec.definitions, symbol);
11514             /*else
11515             {
11516                for(def = spec.definitions->first; def; def = def.next)
11517                {
11518                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11519                      ProcessDeclaration(def.decl);
11520                }
11521             }*/
11522          }
11523          break;
11524       }
11525       /*
11526       case classSpecifier:
11527       {
11528          Symbol classSym = FindClass(spec.name);
11529          if(classSym && classSym.registered && classSym.registered.type == structClass)
11530             DeclareStruct(spec.name, false);
11531          break;
11532       }
11533       */
11534    }
11535 }
11536
11537
11538 static void ProcessDeclarator(Declarator decl)
11539 {
11540    switch(decl.type)
11541    {
11542       case identifierDeclarator:
11543          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11544          {
11545             FreeSpecifier(decl.identifier._class);
11546             decl.identifier._class = null;
11547          }
11548          break;
11549       case arrayDeclarator:
11550          if(decl.array.exp)
11551             ProcessExpressionType(decl.array.exp);
11552       case structDeclarator:
11553       case bracketsDeclarator:
11554       case functionDeclarator:
11555       case pointerDeclarator:
11556       case extendedDeclarator:
11557       case extendedDeclaratorEnd:
11558          if(decl.declarator)
11559             ProcessDeclarator(decl.declarator);
11560          if(decl.type == functionDeclarator)
11561          {
11562             Identifier id = GetDeclId(decl);
11563             if(id && id._class)
11564             {
11565                TypeName param
11566                {
11567                   qualifiers = MkListOne(id._class);
11568                   declarator = null;
11569                };
11570                if(!decl.function.parameters)
11571                   decl.function.parameters = MkList();
11572                decl.function.parameters->Insert(null, param);
11573                id._class = null;
11574             }
11575             if(decl.function.parameters)
11576             {
11577                TypeName param;
11578
11579                for(param = decl.function.parameters->first; param; param = param.next)
11580                {
11581                   if(param.qualifiers && param.qualifiers->first)
11582                   {
11583                      Specifier spec = param.qualifiers->first;
11584                      if(spec && spec.specifier == TYPED_OBJECT)
11585                      {
11586                         Declarator d = param.declarator;
11587                         TypeName newParam
11588                         {
11589                            qualifiers = MkListOne(MkSpecifier(VOID));
11590                            declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11591                         };
11592                         if(d.type != pointerDeclarator)
11593                            newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11594
11595                         FreeList(param.qualifiers, FreeSpecifier);
11596
11597                         param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11598                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11599
11600                         decl.function.parameters->Insert(param, newParam);
11601                         param = newParam;
11602                      }
11603                      else if(spec && spec.specifier == ANY_OBJECT)
11604                      {
11605                         Declarator d = param.declarator;
11606
11607                         FreeList(param.qualifiers, FreeSpecifier);
11608
11609                         param.qualifiers = MkListOne(MkSpecifier(VOID));
11610                         if(d.type != pointerDeclarator)
11611                            param.qualifiers->Insert(null, MkSpecifier(CONST));
11612                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11613                      }
11614                      else if(spec.specifier == THISCLASS)
11615                      {
11616                         if(thisClass)
11617                         {
11618                            spec.type = nameSpecifier;
11619                            spec.name = ReplaceThisClass(thisClass);
11620                            spec.symbol = FindClass(spec.name);
11621                            ProcessSpecifier(spec, false);
11622                         }
11623                      }
11624                   }
11625
11626                   if(param.declarator)
11627                      ProcessDeclarator(param.declarator);
11628                }
11629             }
11630          }
11631          break;
11632    }
11633 }
11634
11635 static void ProcessDeclaration(Declaration decl)
11636 {
11637    yylloc = decl.loc;
11638    switch(decl.type)
11639    {
11640       case initDeclaration:
11641       {
11642          bool declareStruct = false;
11643          /*
11644          lineNum = decl.pos.line;
11645          column = decl.pos.col;
11646          */
11647
11648          if(decl.declarators)
11649          {
11650             InitDeclarator d;
11651
11652             for(d = decl.declarators->first; d; d = d.next)
11653             {
11654                Type type, subType;
11655                ProcessDeclarator(d.declarator);
11656
11657                type = ProcessType(decl.specifiers, d.declarator);
11658
11659                if(d.initializer)
11660                {
11661                   ProcessInitializer(d.initializer, type);
11662
11663                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11664
11665                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11666                      d.initializer.exp.type == instanceExp)
11667                   {
11668                      if(type.kind == classType && type._class ==
11669                         d.initializer.exp.expType._class)
11670                      {
11671                         Instantiation inst = d.initializer.exp.instance;
11672                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11673
11674                         d.initializer.exp.instance = null;
11675                         if(decl.specifiers)
11676                            FreeList(decl.specifiers, FreeSpecifier);
11677                         FreeList(decl.declarators, FreeInitDeclarator);
11678
11679                         d = null;
11680
11681                         decl.type = instDeclaration;
11682                         decl.inst = inst;
11683                      }
11684                   }
11685                }
11686                for(subType = type; subType;)
11687                {
11688                   if(subType.kind == classType)
11689                   {
11690                      declareStruct = true;
11691                      break;
11692                   }
11693                   else if(subType.kind == pointerType)
11694                      break;
11695                   else if(subType.kind == arrayType)
11696                      subType = subType.arrayType;
11697                   else
11698                      break;
11699                }
11700
11701                FreeType(type);
11702                if(!d) break;
11703             }
11704          }
11705
11706          if(decl.specifiers)
11707          {
11708             Specifier s;
11709             for(s = decl.specifiers->first; s; s = s.next)
11710             {
11711                ProcessSpecifier(s, declareStruct);
11712             }
11713          }
11714          break;
11715       }
11716       case instDeclaration:
11717       {
11718          ProcessInstantiationType(decl.inst);
11719          break;
11720       }
11721       case structDeclaration:
11722       {
11723          Specifier spec;
11724          Declarator d;
11725          bool declareStruct = false;
11726
11727          if(decl.declarators)
11728          {
11729             for(d = decl.declarators->first; d; d = d.next)
11730             {
11731                Type type = ProcessType(decl.specifiers, d.declarator);
11732                Type subType;
11733                ProcessDeclarator(d);
11734                for(subType = type; subType;)
11735                {
11736                   if(subType.kind == classType)
11737                   {
11738                      declareStruct = true;
11739                      break;
11740                   }
11741                   else if(subType.kind == pointerType)
11742                      break;
11743                   else if(subType.kind == arrayType)
11744                      subType = subType.arrayType;
11745                   else
11746                      break;
11747                }
11748                FreeType(type);
11749             }
11750          }
11751          if(decl.specifiers)
11752          {
11753             for(spec = decl.specifiers->first; spec; spec = spec.next)
11754                ProcessSpecifier(spec, declareStruct);
11755          }
11756          break;
11757       }
11758    }
11759 }
11760
11761 static FunctionDefinition curFunction;
11762
11763 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11764 {
11765    char propName[1024], propNameM[1024];
11766    char getName[1024], setName[1024];
11767    OldList * args;
11768
11769    DeclareProperty(prop, setName, getName);
11770
11771    // eInstance_FireWatchers(object, prop);
11772    strcpy(propName, "__ecereProp_");
11773    FullClassNameCat(propName, prop._class.fullName, false);
11774    strcat(propName, "_");
11775    // strcat(propName, prop.name);
11776    FullClassNameCat(propName, prop.name, true);
11777    //MangleClassName(propName);
11778
11779    strcpy(propNameM, "__ecerePropM_");
11780    FullClassNameCat(propNameM, prop._class.fullName, false);
11781    strcat(propNameM, "_");
11782    // strcat(propNameM, prop.name);
11783    FullClassNameCat(propNameM, prop.name, true);
11784    //MangleClassName(propNameM);
11785
11786    if(prop.isWatchable)
11787    {
11788       args = MkList();
11789       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11790       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11791       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11792
11793       args = MkList();
11794       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11795       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11796       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11797    }
11798
11799
11800    {
11801       args = MkList();
11802       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11803       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11804       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11805
11806       args = MkList();
11807       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11808       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11809       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11810    }
11811
11812    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11813       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11814       curFunction.propSet.fireWatchersDone = true;
11815 }
11816
11817 static void ProcessStatement(Statement stmt)
11818 {
11819    yylloc = stmt.loc;
11820    /*
11821    lineNum = stmt.pos.line;
11822    column = stmt.pos.col;
11823    */
11824    switch(stmt.type)
11825    {
11826       case labeledStmt:
11827          ProcessStatement(stmt.labeled.stmt);
11828          break;
11829       case caseStmt:
11830          // This expression should be constant...
11831          if(stmt.caseStmt.exp)
11832          {
11833             FreeType(stmt.caseStmt.exp.destType);
11834             stmt.caseStmt.exp.destType = curSwitchType;
11835             if(curSwitchType) curSwitchType.refCount++;
11836             ProcessExpressionType(stmt.caseStmt.exp);
11837             ComputeExpression(stmt.caseStmt.exp);
11838          }
11839          if(stmt.caseStmt.stmt)
11840             ProcessStatement(stmt.caseStmt.stmt);
11841          break;
11842       case compoundStmt:
11843       {
11844          if(stmt.compound.context)
11845          {
11846             Declaration decl;
11847             Statement s;
11848
11849             Statement prevCompound = curCompound;
11850             Context prevContext = curContext;
11851
11852             if(!stmt.compound.isSwitch)
11853                curCompound = stmt;
11854             curContext = stmt.compound.context;
11855
11856             if(stmt.compound.declarations)
11857             {
11858                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
11859                   ProcessDeclaration(decl);
11860             }
11861             if(stmt.compound.statements)
11862             {
11863                for(s = stmt.compound.statements->first; s; s = s.next)
11864                   ProcessStatement(s);
11865             }
11866
11867             curContext = prevContext;
11868             curCompound = prevCompound;
11869          }
11870          break;
11871       }
11872       case expressionStmt:
11873       {
11874          Expression exp;
11875          if(stmt.expressions)
11876          {
11877             for(exp = stmt.expressions->first; exp; exp = exp.next)
11878                ProcessExpressionType(exp);
11879          }
11880          break;
11881       }
11882       case ifStmt:
11883       {
11884          Expression exp;
11885
11886          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
11887          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
11888          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
11889          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
11890          {
11891             ProcessExpressionType(exp);
11892          }
11893          if(stmt.ifStmt.stmt)
11894             ProcessStatement(stmt.ifStmt.stmt);
11895          if(stmt.ifStmt.elseStmt)
11896             ProcessStatement(stmt.ifStmt.elseStmt);
11897          break;
11898       }
11899       case switchStmt:
11900       {
11901          Type oldSwitchType = curSwitchType;
11902          if(stmt.switchStmt.exp)
11903          {
11904             Expression exp;
11905             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
11906             {
11907                if(!exp.next)
11908                {
11909                   /*
11910                   Type destType
11911                   {
11912                      kind = intType;
11913                      refCount = 1;
11914                   };
11915                   e.exp.destType = destType;
11916                   */
11917
11918                   ProcessExpressionType(exp);
11919                }
11920                if(!exp.next)
11921                   curSwitchType = exp.expType;
11922             }
11923          }
11924          ProcessStatement(stmt.switchStmt.stmt);
11925          curSwitchType = oldSwitchType;
11926          break;
11927       }
11928       case whileStmt:
11929       {
11930          if(stmt.whileStmt.exp)
11931          {
11932             Expression exp;
11933
11934             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
11935             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
11936             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
11937             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
11938             {
11939                ProcessExpressionType(exp);
11940             }
11941          }
11942          if(stmt.whileStmt.stmt)
11943             ProcessStatement(stmt.whileStmt.stmt);
11944          break;
11945       }
11946       case doWhileStmt:
11947       {
11948          if(stmt.doWhile.exp)
11949          {
11950             Expression exp;
11951
11952             if(stmt.doWhile.exp->last)
11953             {
11954                FreeType(((Expression)stmt.doWhile.exp->last).destType);
11955                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
11956                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
11957             }
11958             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
11959             {
11960                ProcessExpressionType(exp);
11961             }
11962          }
11963          if(stmt.doWhile.stmt)
11964             ProcessStatement(stmt.doWhile.stmt);
11965          break;
11966       }
11967       case forStmt:
11968       {
11969          Expression exp;
11970          if(stmt.forStmt.init)
11971             ProcessStatement(stmt.forStmt.init);
11972
11973          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
11974          {
11975             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
11976             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
11977             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
11978          }
11979
11980          if(stmt.forStmt.check)
11981             ProcessStatement(stmt.forStmt.check);
11982          if(stmt.forStmt.increment)
11983          {
11984             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
11985                ProcessExpressionType(exp);
11986          }
11987
11988          if(stmt.forStmt.stmt)
11989             ProcessStatement(stmt.forStmt.stmt);
11990          break;
11991       }
11992       case forEachStmt:
11993       {
11994          Identifier id = stmt.forEachStmt.id;
11995          OldList * exp = stmt.forEachStmt.exp;
11996          OldList * filter = stmt.forEachStmt.filter;
11997          Statement block = stmt.forEachStmt.stmt;
11998          char iteratorType[1024];
11999          Type source;
12000          Expression e;
12001          bool isBuiltin = exp && exp->last &&
12002             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12003               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12004          Expression arrayExp;
12005          const char * typeString = null;
12006          int builtinCount = 0;
12007
12008          for(e = exp ? exp->first : null; e; e = e.next)
12009          {
12010             if(!e.next)
12011             {
12012                FreeType(e.destType);
12013                e.destType = ProcessTypeString("Container", false);
12014             }
12015             if(!isBuiltin || e.next)
12016                ProcessExpressionType(e);
12017          }
12018
12019          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12020          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12021             eClass_IsDerived(source._class.registered, containerClass)))
12022          {
12023             Class _class = source ? source._class.registered : null;
12024             Symbol symbol;
12025             Expression expIt = null;
12026             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12027             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12028             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12029             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12030
12031             if(inCompiler)
12032             {
12033                stmt.type = compoundStmt;
12034
12035                stmt.compound.context = Context { };
12036                stmt.compound.context.parent = curContext;
12037                curContext = stmt.compound.context;
12038             }
12039
12040             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12041             {
12042                Class mapClass = eSystem_FindClass(privateModule, "Map");
12043                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12044                isCustomAVLTree = true;
12045                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12046                   isAVLTree = true;
12047                else */if(eClass_IsDerived(source._class.registered, mapClass))
12048                   isMap = true;
12049             }
12050             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12051             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12052             {
12053                Class listClass = eSystem_FindClass(privateModule, "List");
12054                isLinkList = true;
12055                isList = eClass_IsDerived(source._class.registered, listClass);
12056             }
12057
12058             if(inCompiler && isArray)
12059             {
12060                Declarator decl;
12061                OldList * specs = MkList();
12062                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12063                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12064                stmt.compound.declarations = MkListOne(
12065                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12066                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12067                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12068                      MkInitializerAssignment(MkExpBrackets(exp))))));
12069             }
12070             else if(isBuiltin)
12071             {
12072                Type type = null;
12073                char typeStringBuf[1024];
12074
12075                // TODO: Merge this code?
12076                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12077                if(((Expression)exp->last).type == castExp)
12078                {
12079                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12080                   if(typeName)
12081                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12082                }
12083
12084                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12085                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12086                   arrayExp.destType._class.registered.templateArgs)
12087                {
12088                   Class templateClass = arrayExp.destType._class.registered;
12089                   typeString = templateClass.templateArgs[2].dataTypeString;
12090                }
12091                else if(arrayExp.list)
12092                {
12093                   // Guess type from expressions in the array
12094                   Expression e;
12095                   for(e = arrayExp.list->first; e; e = e.next)
12096                   {
12097                      ProcessExpressionType(e);
12098                      if(e.expType)
12099                      {
12100                         if(!type) { type = e.expType; type.refCount++; }
12101                         else
12102                         {
12103                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12104                            if(!MatchTypeExpression(e, type, null, false, true))
12105                            {
12106                               FreeType(type);
12107                               type = e.expType;
12108                               e.expType = null;
12109
12110                               e = arrayExp.list->first;
12111                               ProcessExpressionType(e);
12112                               if(e.expType)
12113                               {
12114                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12115                                  if(!MatchTypeExpression(e, type, null, false, true))
12116                                  {
12117                                     FreeType(e.expType);
12118                                     e.expType = null;
12119                                     FreeType(type);
12120                                     type = null;
12121                                     break;
12122                                  }
12123                               }
12124                            }
12125                         }
12126                         if(e.expType)
12127                         {
12128                            FreeType(e.expType);
12129                            e.expType = null;
12130                         }
12131                      }
12132                   }
12133                   if(type)
12134                   {
12135                      typeStringBuf[0] = '\0';
12136                      PrintType(type, typeStringBuf, false, true);
12137                      typeString = typeStringBuf;
12138                      FreeType(type);
12139                   }
12140                }
12141                if(typeString)
12142                {
12143                   if(inCompiler)
12144                   {
12145                      OldList * initializers = MkList();
12146                      Declarator decl;
12147                      OldList * specs = MkList();
12148                      if(arrayExp.list)
12149                      {
12150                         Expression e;
12151
12152                         builtinCount = arrayExp.list->count;
12153                         type = ProcessTypeString(typeString, false);
12154                         while((e = arrayExp.list->first))
12155                         {
12156                            arrayExp.list->Remove(e);
12157                            e.destType = type;
12158                            type.refCount++;
12159                            ProcessExpressionType(e);
12160                            if(inCompiler)
12161                               ListAdd(initializers, MkInitializerAssignment(e));
12162                         }
12163                         FreeType(type);
12164                         delete arrayExp.list;
12165                      }
12166                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12167
12168                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12169                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12170
12171                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12172                         PlugDeclarator(
12173                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12174                            ), MkInitializerList(initializers)))));
12175                      FreeList(exp, FreeExpression);
12176                   }
12177                   else if(arrayExp.list)
12178                   {
12179                      Expression e;
12180                      type = ProcessTypeString(typeString, false);
12181                      for(e = arrayExp.list->first; e; e = e.next)
12182                      {
12183                         e.destType = type;
12184                         type.refCount++;
12185                         ProcessExpressionType(e);
12186                      }
12187                      FreeType(type);
12188                   }
12189                }
12190                else
12191                {
12192                   arrayExp.expType = ProcessTypeString("Container", false);
12193                   Compiler_Error($"Couldn't determine type of array elements\n");
12194                }
12195
12196                /*
12197                Declarator decl;
12198                OldList * specs = MkList();
12199
12200                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12201                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12202                stmt.compound.declarations = MkListOne(
12203                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12204                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12205                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12206                      MkInitializerAssignment(MkExpBrackets(exp))))));
12207                */
12208             }
12209             else if(inCompiler && isLinkList && !isList)
12210             {
12211                Declarator decl;
12212                OldList * specs = MkList();
12213                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12214                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12215                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12216                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12217                      MkInitializerAssignment(MkExpBrackets(exp))))));
12218             }
12219             /*else if(isCustomAVLTree)
12220             {
12221                Declarator decl;
12222                OldList * specs = MkList();
12223                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12224                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12225                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12226                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12227                      MkInitializerAssignment(MkExpBrackets(exp))))));
12228             }*/
12229             else if(inCompiler && _class.templateArgs)
12230             {
12231                if(isMap)
12232                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12233                else
12234                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12235
12236                stmt.compound.declarations = MkListOne(
12237                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12238                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12239                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12240             }
12241             if(inCompiler)
12242             {
12243                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12244
12245                if(block)
12246                {
12247                   // Reparent sub-contexts in this statement
12248                   switch(block.type)
12249                   {
12250                      case compoundStmt:
12251                         if(block.compound.context)
12252                            block.compound.context.parent = stmt.compound.context;
12253                         break;
12254                      case ifStmt:
12255                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12256                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12257                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12258                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12259                         break;
12260                      case switchStmt:
12261                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12262                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12263                         break;
12264                      case whileStmt:
12265                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12266                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12267                         break;
12268                      case doWhileStmt:
12269                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12270                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12271                         break;
12272                      case forStmt:
12273                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12274                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12275                         break;
12276                      case forEachStmt:
12277                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12278                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12279                         break;
12280                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12281                      case labeledStmt:
12282                      case caseStmt
12283                      case expressionStmt:
12284                      case gotoStmt:
12285                      case continueStmt:
12286                      case breakStmt
12287                      case returnStmt:
12288                      case asmStmt:
12289                      case badDeclarationStmt:
12290                      case fireWatchersStmt:
12291                      case stopWatchingStmt:
12292                      case watchStmt:
12293                      */
12294                   }
12295                }
12296
12297                if(filter)
12298                {
12299                   block = MkIfStmt(filter, block, null);
12300                }
12301                if(isArray)
12302                {
12303                   stmt.compound.statements = MkListOne(MkForStmt(
12304                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12305                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12306                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12307                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12308                      block));
12309                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12310                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12311                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12312                }
12313                else if(isBuiltin)
12314                {
12315                   char count[128];
12316                   //OldList * specs = MkList();
12317                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12318
12319                   sprintf(count, "%d", builtinCount);
12320
12321                   stmt.compound.statements = MkListOne(MkForStmt(
12322                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12323                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12324                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12325                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12326                      block));
12327
12328                   /*
12329                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12330                   stmt.compound.statements = MkListOne(MkForStmt(
12331                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12332                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12333                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12334                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12335                      block));
12336                  */
12337                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12338                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12339                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12340                }
12341                else if(isLinkList && !isList)
12342                {
12343                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12344                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12345                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12346                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12347                   {
12348                      stmt.compound.statements = MkListOne(MkForStmt(
12349                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12350                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12351                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12352                         block));
12353                   }
12354                   else
12355                   {
12356                      OldList * specs = MkList();
12357                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12358                      stmt.compound.statements = MkListOne(MkForStmt(
12359                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12360                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12361                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12362                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12363                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12364                         block));
12365                   }
12366                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12367                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12368                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12369                }
12370                /*else if(isCustomAVLTree)
12371                {
12372                   stmt.compound.statements = MkListOne(MkForStmt(
12373                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12374                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12375                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12376                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12377                      block));
12378
12379                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12380                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12381                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12382                }*/
12383                else
12384                {
12385                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12386                      MkIdentifier("Next")), null)), block));
12387                }
12388                ProcessExpressionType(expIt);
12389                if(stmt.compound.declarations->first)
12390                   ProcessDeclaration(stmt.compound.declarations->first);
12391
12392                if(symbol)
12393                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12394
12395                ProcessStatement(stmt);
12396             }
12397             else
12398                ProcessStatement(stmt.forEachStmt.stmt);
12399             if(inCompiler)
12400                curContext = stmt.compound.context.parent;
12401             break;
12402          }
12403          else
12404          {
12405             Compiler_Error($"Expression is not a container\n");
12406          }
12407          break;
12408       }
12409       case gotoStmt:
12410          break;
12411       case continueStmt:
12412          break;
12413       case breakStmt:
12414          break;
12415       case returnStmt:
12416       {
12417          Expression exp;
12418          if(stmt.expressions)
12419          {
12420             for(exp = stmt.expressions->first; exp; exp = exp.next)
12421             {
12422                if(!exp.next)
12423                {
12424                   if(curFunction && !curFunction.type)
12425                      curFunction.type = ProcessType(
12426                         curFunction.specifiers, curFunction.declarator);
12427                   FreeType(exp.destType);
12428                   // TODO: current property if not compiling
12429                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12430                   if(exp.destType) exp.destType.refCount++;
12431                }
12432                ProcessExpressionType(exp);
12433             }
12434          }
12435          break;
12436       }
12437       case badDeclarationStmt:
12438       {
12439          ProcessDeclaration(stmt.decl);
12440          break;
12441       }
12442       case asmStmt:
12443       {
12444          AsmField field;
12445          if(stmt.asmStmt.inputFields)
12446          {
12447             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12448                if(field.expression)
12449                   ProcessExpressionType(field.expression);
12450          }
12451          if(stmt.asmStmt.outputFields)
12452          {
12453             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12454                if(field.expression)
12455                   ProcessExpressionType(field.expression);
12456          }
12457          if(stmt.asmStmt.clobberedFields)
12458          {
12459             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12460             {
12461                if(field.expression)
12462                   ProcessExpressionType(field.expression);
12463             }
12464          }
12465          break;
12466       }
12467       case watchStmt:
12468       {
12469          PropertyWatch propWatch;
12470          OldList * watches = stmt._watch.watches;
12471          Expression object = stmt._watch.object;
12472          Expression watcher = stmt._watch.watcher;
12473          if(watcher)
12474             ProcessExpressionType(watcher);
12475          if(object)
12476             ProcessExpressionType(object);
12477
12478          if(inCompiler)
12479          {
12480             if(watcher || thisClass)
12481             {
12482                External external = curExternal;
12483                Context context = curContext;
12484
12485                stmt.type = expressionStmt;
12486                stmt.expressions = MkList();
12487
12488                curExternal = external.prev;
12489
12490                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12491                {
12492                   ClassFunction func;
12493                   char watcherName[1024];
12494                   Class watcherClass = watcher ?
12495                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12496                   External createdExternal;
12497
12498                   // Create a declaration above
12499                   External externalDecl = MkExternalDeclaration(null);
12500                   ast->Insert(curExternal.prev, externalDecl);
12501
12502                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12503                   if(propWatch.deleteWatch)
12504                      strcat(watcherName, "_delete");
12505                   else
12506                   {
12507                      Identifier propID;
12508                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12509                      {
12510                         strcat(watcherName, "_");
12511                         strcat(watcherName, propID.string);
12512                      }
12513                   }
12514
12515                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12516                   {
12517                      // TESTING THIS STUFF... BEWARE OF SYMBOL ID ISSUES
12518                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12519                         //MkListOne(MkTypeName(MkListOne(MkSpecifier(VOID)), null))), null);
12520                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12521                      ProcessClassFunctionBody(func, propWatch.compound);
12522                      propWatch.compound = null;
12523
12524                      //afterExternal = afterExternal ? afterExternal : curExternal;
12525
12526                      //createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal.prev);
12527                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12528                      // TESTING THIS...
12529                      createdExternal.symbol.idCode = external.symbol.idCode;
12530
12531                      curExternal = createdExternal;
12532                      ProcessFunction(createdExternal.function);
12533
12534
12535                      // Create a declaration above
12536                      {
12537                         Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
12538                            MkListOne(MkInitDeclarator(CopyDeclarator(createdExternal.function.declarator), null)));
12539                         externalDecl.declaration = decl;
12540                         if(decl.symbol && !decl.symbol.pointerExternal)
12541                            decl.symbol.pointerExternal = externalDecl;
12542                      }
12543
12544                      if(propWatch.deleteWatch)
12545                      {
12546                         OldList * args = MkList();
12547                         ListAdd(args, CopyExpression(object));
12548                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12549                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12550                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12551                      }
12552                      else
12553                      {
12554                         Class _class = object.expType._class.registered;
12555                         Identifier propID;
12556
12557                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12558                         {
12559                            char propName[1024];
12560                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12561                            if(prop)
12562                            {
12563                               char getName[1024], setName[1024];
12564                               OldList * args = MkList();
12565
12566                               DeclareProperty(prop, setName, getName);
12567
12568                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12569                               strcpy(propName, "__ecereProp_");
12570                               FullClassNameCat(propName, prop._class.fullName, false);
12571                               strcat(propName, "_");
12572                               // strcat(propName, prop.name);
12573                               FullClassNameCat(propName, prop.name, true);
12574
12575                               ListAdd(args, CopyExpression(object));
12576                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12577                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12578                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12579
12580                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12581                            }
12582                            else
12583                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12584                         }
12585                      }
12586                   }
12587                   else
12588                      Compiler_Error($"Invalid watched object\n");
12589                }
12590
12591                curExternal = external;
12592                curContext = context;
12593
12594                if(watcher)
12595                   FreeExpression(watcher);
12596                if(object)
12597                   FreeExpression(object);
12598                FreeList(watches, FreePropertyWatch);
12599             }
12600             else
12601                Compiler_Error($"No observer specified and not inside a _class\n");
12602          }
12603          else
12604          {
12605             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12606             {
12607                ProcessStatement(propWatch.compound);
12608             }
12609
12610          }
12611          break;
12612       }
12613       case fireWatchersStmt:
12614       {
12615          OldList * watches = stmt._watch.watches;
12616          Expression object = stmt._watch.object;
12617          Class _class;
12618          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12619          // printf("%X\n", watches);
12620          // printf("%X\n", stmt._watch.watches);
12621          if(object)
12622             ProcessExpressionType(object);
12623
12624          if(inCompiler)
12625          {
12626             _class = object ?
12627                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12628
12629             if(_class)
12630             {
12631                Identifier propID;
12632
12633                stmt.type = expressionStmt;
12634                stmt.expressions = MkList();
12635
12636                // Check if we're inside a property set
12637                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12638                {
12639                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12640                }
12641                else if(!watches)
12642                {
12643                   //Compiler_Error($"No property specified and not inside a property set\n");
12644                }
12645                if(watches)
12646                {
12647                   for(propID = watches->first; propID; propID = propID.next)
12648                   {
12649                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12650                      if(prop)
12651                      {
12652                         CreateFireWatcher(prop, object, stmt);
12653                      }
12654                      else
12655                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12656                   }
12657                }
12658                else
12659                {
12660                   // Fire all properties!
12661                   Property prop;
12662                   Class base;
12663                   for(base = _class; base; base = base.base)
12664                   {
12665                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12666                      {
12667                         if(prop.isProperty && prop.isWatchable)
12668                         {
12669                            CreateFireWatcher(prop, object, stmt);
12670                         }
12671                      }
12672                   }
12673                }
12674
12675                if(object)
12676                   FreeExpression(object);
12677                FreeList(watches, FreeIdentifier);
12678             }
12679             else
12680                Compiler_Error($"Invalid object specified and not inside a class\n");
12681          }
12682          break;
12683       }
12684       case stopWatchingStmt:
12685       {
12686          OldList * watches = stmt._watch.watches;
12687          Expression object = stmt._watch.object;
12688          Expression watcher = stmt._watch.watcher;
12689          Class _class;
12690          if(object)
12691             ProcessExpressionType(object);
12692          if(watcher)
12693             ProcessExpressionType(watcher);
12694          if(inCompiler)
12695          {
12696             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12697
12698             if(watcher || thisClass)
12699             {
12700                if(_class)
12701                {
12702                   Identifier propID;
12703
12704                   stmt.type = expressionStmt;
12705                   stmt.expressions = MkList();
12706
12707                   if(!watches)
12708                   {
12709                      OldList * args;
12710                      // eInstance_StopWatching(object, null, watcher);
12711                      args = MkList();
12712                      ListAdd(args, CopyExpression(object));
12713                      ListAdd(args, MkExpConstant("0"));
12714                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12715                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12716                   }
12717                   else
12718                   {
12719                      for(propID = watches->first; propID; propID = propID.next)
12720                      {
12721                         char propName[1024];
12722                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12723                         if(prop)
12724                         {
12725                            char getName[1024], setName[1024];
12726                            OldList * args = MkList();
12727
12728                            DeclareProperty(prop, setName, getName);
12729
12730                            // eInstance_StopWatching(object, prop, watcher);
12731                            strcpy(propName, "__ecereProp_");
12732                            FullClassNameCat(propName, prop._class.fullName, false);
12733                            strcat(propName, "_");
12734                            // strcat(propName, prop.name);
12735                            FullClassNameCat(propName, prop.name, true);
12736                            //MangleClassName(propName);
12737
12738                            ListAdd(args, CopyExpression(object));
12739                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12740                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12741                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12742                         }
12743                         else
12744                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12745                      }
12746                   }
12747
12748                   if(object)
12749                      FreeExpression(object);
12750                   if(watcher)
12751                      FreeExpression(watcher);
12752                   FreeList(watches, FreeIdentifier);
12753                }
12754                else
12755                   Compiler_Error($"Invalid object specified and not inside a class\n");
12756             }
12757             else
12758                Compiler_Error($"No observer specified and not inside a class\n");
12759          }
12760          break;
12761       }
12762    }
12763 }
12764
12765 static void ProcessFunction(FunctionDefinition function)
12766 {
12767    Identifier id = GetDeclId(function.declarator);
12768    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12769    Type type = symbol ? symbol.type : null;
12770    Class oldThisClass = thisClass;
12771    Context oldTopContext = topContext;
12772
12773    yylloc = function.loc;
12774    // Process thisClass
12775
12776    if(type && type.thisClass)
12777    {
12778       Symbol classSym = type.thisClass;
12779       Class _class = type.thisClass.registered;
12780       char className[1024];
12781       char structName[1024];
12782       Declarator funcDecl;
12783       Symbol thisSymbol;
12784
12785       bool typedObject = false;
12786
12787       if(_class && !_class.base)
12788       {
12789          _class = currentClass;
12790          if(_class && !_class.symbol)
12791             _class.symbol = FindClass(_class.fullName);
12792          classSym = _class ? _class.symbol : null;
12793          typedObject = true;
12794       }
12795
12796       thisClass = _class;
12797
12798       if(inCompiler && _class)
12799       {
12800          if(type.kind == functionType)
12801          {
12802             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12803             {
12804                //TypeName param = symbol.type.params.first;
12805                Type param = symbol.type.params.first;
12806                symbol.type.params.Remove(param);
12807                //FreeTypeName(param);
12808                FreeType(param);
12809             }
12810             if(type.classObjectType != classPointer)
12811             {
12812                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12813                symbol.type.staticMethod = true;
12814                symbol.type.thisClass = null;
12815
12816                // HIGH DANGER: VERIFYING THIS...
12817                symbol.type.extraParam = false;
12818             }
12819          }
12820
12821          strcpy(className, "__ecereClass_");
12822          FullClassNameCat(className, _class.fullName, true);
12823
12824          //MangleClassName(className);
12825
12826          structName[0] = 0;
12827          FullClassNameCat(structName, _class.fullName, false);
12828
12829          // [class] this
12830
12831
12832          funcDecl = GetFuncDecl(function.declarator);
12833          if(funcDecl)
12834          {
12835             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12836             {
12837                TypeName param = funcDecl.function.parameters->first;
12838                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12839                {
12840                   funcDecl.function.parameters->Remove(param);
12841                   FreeTypeName(param);
12842                }
12843             }
12844
12845             // DANGER: Watch for this... Check if it's a Conversion?
12846             // if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12847
12848             // WAS TRYING THIS FOR CONVERSION PROPERTIES ON NOHEAD CLASSES: if((_class.type == structClass) || function != (FunctionDefinition)symbol.externalSet)
12849             if(!function.propertyNoThis)
12850             {
12851                TypeName thisParam = null;
12852
12853                if(type.classObjectType != classPointer)
12854                {
12855                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12856                   if(!funcDecl.function.parameters)
12857                      funcDecl.function.parameters = MkList();
12858                   funcDecl.function.parameters->Insert(null, thisParam);
12859                }
12860
12861                if(typedObject)
12862                {
12863                   if(type.classObjectType != classPointer)
12864                   {
12865                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
12866                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
12867                   }
12868
12869                   thisParam = TypeName
12870                   {
12871                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
12872                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
12873                   };
12874                   funcDecl.function.parameters->Insert(null, thisParam);
12875                }
12876             }
12877          }
12878
12879          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12880          {
12881             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12882             funcDecl = GetFuncDecl(initDecl.declarator);
12883             if(funcDecl)
12884             {
12885                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12886                {
12887                   TypeName param = funcDecl.function.parameters->first;
12888                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12889                   {
12890                      funcDecl.function.parameters->Remove(param);
12891                      FreeTypeName(param);
12892                   }
12893                }
12894
12895                if(type.classObjectType != classPointer)
12896                {
12897                   // DANGER: Watch for this... Check if it's a Conversion?
12898                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12899                   {
12900                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12901
12902                      if(!funcDecl.function.parameters)
12903                         funcDecl.function.parameters = MkList();
12904                      funcDecl.function.parameters->Insert(null, thisParam);
12905                   }
12906                }
12907             }
12908          }
12909       }
12910
12911       // Add this to the context
12912       if(function.body)
12913       {
12914          if(type.classObjectType != classPointer)
12915          {
12916             thisSymbol = Symbol
12917             {
12918                string = CopyString("this");
12919                type = classSym ? MkClassType(classSym.string) : null; //_class.fullName);
12920             };
12921             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
12922
12923             if(typedObject && thisSymbol.type)
12924             {
12925                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
12926                thisSymbol.type.byReference = type.byReference;
12927                thisSymbol.type.typedByReference = type.byReference;
12928                /*
12929                thisSymbol = Symbol { string = CopyString("class") };
12930                function.body.compound.context.symbols.Add(thisSymbol);
12931                */
12932             }
12933          }
12934       }
12935
12936       // Pointer to class data
12937
12938       if(inCompiler && _class && (_class.type == normalClass /*|| _class.type == noHeadClass*/) && type.classObjectType != classPointer)
12939       {
12940          DataMember member = null;
12941          {
12942             Class base;
12943             for(base = _class; base && base.type != systemClass; base = base.next)
12944             {
12945                for(member = base.membersAndProperties.first; member; member = member.next)
12946                   if(!member.isProperty)
12947                      break;
12948                if(member)
12949                   break;
12950             }
12951          }
12952          for(member = _class.membersAndProperties.first; member; member = member.next)
12953             if(!member.isProperty)
12954                break;
12955          if(member)
12956          {
12957             char pointerName[1024];
12958
12959             Declaration decl;
12960             Initializer initializer;
12961             Expression exp, bytePtr;
12962
12963             strcpy(pointerName, "__ecerePointer_");
12964             FullClassNameCat(pointerName, _class.fullName, false);
12965             {
12966                char className[1024];
12967                strcpy(className, "__ecereClass_");
12968                FullClassNameCat(className, classSym.string, true);
12969                //MangleClassName(className);
12970
12971                // Testing This
12972                DeclareClass(classSym, className);
12973             }
12974
12975             // ((byte *) this)
12976             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
12977
12978             if(_class.fixed)
12979             {
12980                char string[256];
12981                sprintf(string, "%d", _class.offset);
12982                exp = QBrackets(MkExpOp(bytePtr, '+', MkExpConstant(string)));
12983             }
12984             else
12985             {
12986                // ([bytePtr] + [className]->offset)
12987                exp = QBrackets(MkExpOp(bytePtr, '+',
12988                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
12989             }
12990
12991             // (this ? [exp] : 0)
12992             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
12993             exp.expType = Type
12994             {
12995                refCount = 1;
12996                kind = pointerType;
12997                type = Type { refCount = 1, kind = voidType };
12998             };
12999
13000             if(function.body)
13001             {
13002                yylloc = function.body.loc;
13003                // ([structName] *) [exp]
13004                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13005                initializer = MkInitializerAssignment(
13006                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13007
13008                // [structName] * [pointerName] = [initializer];
13009                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13010
13011                {
13012                   Context prevContext = curContext;
13013                   OldList * list;
13014                   curContext = function.body.compound.context;
13015
13016                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13017                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13018                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13019
13020                   curContext = prevContext;
13021                }
13022
13023                // WHY?
13024                decl.symbol = null;
13025
13026                if(!function.body.compound.declarations)
13027                   function.body.compound.declarations = MkList();
13028                function.body.compound.declarations->Insert(null, decl);
13029             }
13030          }
13031       }
13032
13033
13034       // Loop through the function and replace undeclared identifiers
13035       // which are a member of the class (methods, properties or data)
13036       // by "this.[member]"
13037    }
13038    else
13039       thisClass = null;
13040
13041    if(id)
13042    {
13043       FreeSpecifier(id._class);
13044       id._class = null;
13045
13046       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13047       {
13048          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13049          id = GetDeclId(initDecl.declarator);
13050
13051          FreeSpecifier(id._class);
13052          id._class = null;
13053       }
13054    }
13055    if(function.body)
13056       topContext = function.body.compound.context;
13057    {
13058       FunctionDefinition oldFunction = curFunction;
13059       curFunction = function;
13060       if(function.body)
13061          ProcessStatement(function.body);
13062
13063       // If this is a property set and no firewatchers has been done yet, add one here
13064       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13065       {
13066          Statement prevCompound = curCompound;
13067          Context prevContext = curContext;
13068
13069          Statement fireWatchers = MkFireWatchersStmt(null, null);
13070          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13071          ListAdd(function.body.compound.statements, fireWatchers);
13072
13073          curCompound = function.body;
13074          curContext = function.body.compound.context;
13075
13076          ProcessStatement(fireWatchers);
13077
13078          curContext = prevContext;
13079          curCompound = prevCompound;
13080
13081       }
13082
13083       curFunction = oldFunction;
13084    }
13085
13086    if(function.declarator)
13087    {
13088       ProcessDeclarator(function.declarator);
13089    }
13090
13091    topContext = oldTopContext;
13092    thisClass = oldThisClass;
13093 }
13094
13095 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13096 static void ProcessClass(OldList definitions, Symbol symbol)
13097 {
13098    ClassDef def;
13099    External external = curExternal;
13100    Class regClass = symbol ? symbol.registered : null;
13101
13102    // Process all functions
13103    for(def = definitions.first; def; def = def.next)
13104    {
13105       if(def.type == functionClassDef)
13106       {
13107          if(def.function.declarator)
13108             curExternal = def.function.declarator.symbol.pointerExternal;
13109          else
13110             curExternal = external;
13111
13112          ProcessFunction((FunctionDefinition)def.function);
13113       }
13114       else if(def.type == declarationClassDef)
13115       {
13116          if(def.decl.type == instDeclaration)
13117          {
13118             thisClass = regClass;
13119             ProcessInstantiationType(def.decl.inst);
13120             thisClass = null;
13121          }
13122          // Testing this
13123          else
13124          {
13125             Class backThisClass = thisClass;
13126             if(regClass) thisClass = regClass;
13127             ProcessDeclaration(def.decl);
13128             thisClass = backThisClass;
13129          }
13130       }
13131       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13132       {
13133          MemberInit defProperty;
13134
13135          // Add this to the context
13136          Symbol thisSymbol = Symbol
13137          {
13138             string = CopyString("this");
13139             type = regClass ? MkClassType(regClass.fullName) : null;
13140          };
13141          globalContext.symbols.Add((BTNode)thisSymbol);
13142
13143          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13144          {
13145             thisClass = regClass;
13146             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13147             thisClass = null;
13148          }
13149
13150          globalContext.symbols.Remove((BTNode)thisSymbol);
13151          FreeSymbol(thisSymbol);
13152       }
13153       else if(def.type == propertyClassDef && def.propertyDef)
13154       {
13155          PropertyDef prop = def.propertyDef;
13156
13157          // Add this to the context
13158          /*
13159          Symbol thisSymbol = Symbol { string = CopyString("this"), type = MkClassType(regClass.fullName) };
13160          globalContext.symbols.Add(thisSymbol);
13161          */
13162
13163          thisClass = regClass;
13164          if(prop.setStmt)
13165          {
13166             if(regClass)
13167             {
13168                Symbol thisSymbol
13169                {
13170                   string = CopyString("this");
13171                   type = MkClassType(regClass.fullName);
13172                };
13173                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13174             }
13175
13176             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13177             ProcessStatement(prop.setStmt);
13178          }
13179          if(prop.getStmt)
13180          {
13181             if(regClass)
13182             {
13183                Symbol thisSymbol
13184                {
13185                   string = CopyString("this");
13186                   type = MkClassType(regClass.fullName);
13187                };
13188                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13189             }
13190
13191             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13192             ProcessStatement(prop.getStmt);
13193          }
13194          if(prop.issetStmt)
13195          {
13196             if(regClass)
13197             {
13198                Symbol thisSymbol
13199                {
13200                   string = CopyString("this");
13201                   type = MkClassType(regClass.fullName);
13202                };
13203                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13204             }
13205
13206             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13207             ProcessStatement(prop.issetStmt);
13208          }
13209
13210          thisClass = null;
13211
13212          /*
13213          globalContext.symbols.Remove(thisSymbol);
13214          FreeSymbol(thisSymbol);
13215          */
13216       }
13217       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13218       {
13219          PropertyWatch propertyWatch = def.propertyWatch;
13220
13221          thisClass = regClass;
13222          if(propertyWatch.compound)
13223          {
13224             Symbol thisSymbol
13225             {
13226                string = CopyString("this");
13227                type = regClass ? MkClassType(regClass.fullName) : null;
13228             };
13229
13230             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13231
13232             curExternal = null;
13233             ProcessStatement(propertyWatch.compound);
13234          }
13235          thisClass = null;
13236       }
13237    }
13238 }
13239
13240 void DeclareFunctionUtil(const String s)
13241 {
13242    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13243    if(function)
13244    {
13245       char name[1024];
13246       name[0] = 0;
13247       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13248          strcpy(name, "__ecereFunction_");
13249       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13250       DeclareFunction(function, name);
13251    }
13252 }
13253
13254 void ComputeDataTypes()
13255 {
13256    External external;
13257    External temp { };
13258    External after = null;
13259
13260    currentClass = null;
13261
13262    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13263
13264    for(external = ast->first; external; external = external.next)
13265    {
13266       if(external.type == declarationExternal)
13267       {
13268          Declaration decl = external.declaration;
13269          if(decl)
13270          {
13271             OldList * decls = decl.declarators;
13272             if(decls)
13273             {
13274                InitDeclarator initDecl = decls->first;
13275                if(initDecl)
13276                {
13277                   Declarator declarator = initDecl.declarator;
13278                   if(declarator && declarator.type == identifierDeclarator)
13279                   {
13280                      Identifier id = declarator.identifier;
13281                      if(id && id.string)
13282                      {
13283                         if(!strcmp(id.string, "uintptr_t") || !strcmp(id.string, "intptr_t") || !strcmp(id.string, "size_t") || !strcmp(id.string, "ssize_t"))
13284                         {
13285                            external.symbol.id = -1001, external.symbol.idCode = -1001;
13286                            after = external;
13287                         }
13288                      }
13289                   }
13290                }
13291             }
13292          }
13293        }
13294    }
13295
13296    {
13297       // Workaround until we have proper toposort for declarations reordering
13298       External e = MkExternalDeclaration(MkDeclaration(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Instance"), null)), null));
13299       ast->Insert(after, e);
13300       after = e;
13301    }
13302
13303    temp.symbol = Symbol { id = -1000, idCode = -1000 };
13304    ast->Insert(after, temp);
13305    curExternal = temp;
13306
13307    DeclareFunctionUtil("eSystem_New");
13308    DeclareFunctionUtil("eSystem_New0");
13309    DeclareFunctionUtil("eSystem_Renew");
13310    DeclareFunctionUtil("eSystem_Renew0");
13311    DeclareFunctionUtil("eSystem_Delete");
13312    DeclareFunctionUtil("eClass_GetProperty");
13313    DeclareFunctionUtil("eClass_SetProperty");
13314    DeclareFunctionUtil("eInstance_FireSelfWatchers");
13315    DeclareFunctionUtil("eInstance_SetMethod");
13316    DeclareFunctionUtil("eInstance_IncRef");
13317    DeclareFunctionUtil("eInstance_StopWatching");
13318    DeclareFunctionUtil("eInstance_Watch");
13319    DeclareFunctionUtil("eInstance_FireWatchers");
13320    if(memoryGuard)
13321    {
13322       DeclareFunctionUtil("MemoryGuard_PushLoc");
13323       DeclareFunctionUtil("MemoryGuard_PopLoc");
13324    }
13325
13326    DeclareStruct("ecere::com::Class", false);
13327    DeclareStruct("ecere::com::Instance", false);
13328    DeclareStruct("ecere::com::Property", false);
13329    DeclareStruct("ecere::com::DataMember", false);
13330    DeclareStruct("ecere::com::Method", false);
13331    DeclareStruct("ecere::com::SerialBuffer", false);
13332    DeclareStruct("ecere::com::ClassTemplateArgument", false);
13333
13334    ast->Remove(temp);
13335
13336    for(external = ast->first; external; external = external.next)
13337    {
13338       afterExternal = curExternal = external;
13339       if(external.type == functionExternal)
13340       {
13341          currentClass = external.function._class;
13342          ProcessFunction(external.function);
13343       }
13344       // There shouldn't be any _class member access here anyways...
13345       else if(external.type == declarationExternal)
13346       {
13347          currentClass = null;
13348          if(external.declaration)
13349             ProcessDeclaration(external.declaration);
13350       }
13351       else if(external.type == classExternal)
13352       {
13353          ClassDefinition _class = external._class;
13354          currentClass = external.symbol.registered;
13355          if(_class.definitions)
13356          {
13357             ProcessClass(_class.definitions, _class.symbol);
13358          }
13359          if(inCompiler)
13360          {
13361             // Free class data...
13362             ast->Remove(external);
13363             delete external;
13364          }
13365       }
13366       else if(external.type == nameSpaceExternal)
13367       {
13368          thisNameSpace = external.id.string;
13369       }
13370    }
13371    currentClass = null;
13372    thisNameSpace = null;
13373    curExternal = null;
13374
13375    delete temp.symbol;
13376    delete temp;
13377 }