compiler/libec: (#787, #826) Added support for C99 bool and complex numbers
[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
51       if(exp)
52          OutputExpression(exp, f);
53       f.Seek(0, start);
54       count = strlen(string);
55       count += f.Read(string + count, 1, 1023);
56       string[count] = '\0';
57       delete f;
58    }
59 }
60
61 Type ProcessTemplateParameterType(TemplateParameter param)
62 {
63    if(param && param.type == TemplateParameterType::type && (param.dataType || param.dataTypeString))
64    {
65       // TOFIX: Will need to free this Type
66       if(!param.baseType)
67       {
68          if(param.dataTypeString)
69             param.baseType = ProcessTypeString(param.dataTypeString, false);
70          else
71             param.baseType = ProcessType(param.dataType.specifiers, param.dataType.decl);
72       }
73       return param.baseType;
74    }
75    return null;
76 }
77
78 bool NeedCast(Type type1, Type type2)
79 {
80    if(!type1 || !type2 || type1.keepCast || type2.keepCast) return true;
81
82    if(type1.kind == templateType && type2.kind == int64Type && type2.passAsTemplate == false)
83    {
84       return false;
85    }
86
87    if(type1.kind == type2.kind)
88    {
89       switch(type1.kind)
90       {
91          case _BoolType:
92          case charType:
93          case shortType:
94          case intType:
95          case int64Type:
96          case intPtrType:
97          case intSizeType:
98             if(type1.passAsTemplate && !type2.passAsTemplate)
99                return true;
100             return type1.isSigned != type2.isSigned;
101          case classType:
102             return type1._class != type2._class;
103          case pointerType:
104             return NeedCast(type1.type, type2.type);
105          default:
106             return true; //false; ????
107       }
108    }
109    return true;
110 }
111
112 static void ReplaceClassMembers(Expression exp, Class _class)
113 {
114    if(exp.type == identifierExp && exp.identifier)
115    {
116       Identifier id = exp.identifier;
117       Context ctx;
118       Symbol symbol = null;
119       if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
120       {
121          // First, check if the identifier is declared inside the function
122          for(ctx = curContext; ctx != topContext.parent && !symbol; ctx = ctx.parent)
123          {
124             symbol = (Symbol)ctx.symbols.FindString(id.string);
125             if(symbol) break;
126          }
127       }
128
129       // If it is not, check if it is a member of the _class
130       if(!symbol && ((!id._class || (id._class.name && !strcmp(id._class.name, "property"))) || (id.classSym && eClass_IsDerived(_class, id.classSym.registered))))
131       {
132          Property prop = eClass_FindProperty(_class, id.string, privateModule);
133          Method method = null;
134          DataMember member = null;
135          ClassProperty classProp = null;
136          if(!prop)
137          {
138             method = eClass_FindMethod(_class, id.string, privateModule);
139          }
140          if(!prop && !method)
141             member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
142          if(!prop && !method && !member)
143          {
144             classProp = eClass_FindClassProperty(_class, id.string);
145          }
146          if(prop || method || member || classProp)
147          {
148             // Replace by this.[member]
149             exp.type = memberExp;
150             exp.member.member = id;
151             exp.member.memberType = unresolvedMember;
152             exp.member.exp = QMkExpId("this");
153             //exp.member.exp.loc = exp.loc;
154             exp.addedThis = true;
155          }
156          else if(_class && _class.templateParams.first)
157          {
158             Class sClass;
159             for(sClass = _class; sClass; sClass = sClass.base)
160             {
161                if(sClass.templateParams.first)
162                {
163                   ClassTemplateParameter param;
164                   for(param = sClass.templateParams.first; param; param = param.next)
165                   {
166                      if(param.type == expression && !strcmp(param.name, id.string))
167                      {
168                         Expression argExp = GetTemplateArgExpByName(param.name, _class, TemplateParameterType::expression);
169
170                         if(argExp)
171                         {
172                            Declarator decl;
173                            OldList * specs = MkList();
174
175                            FreeIdentifier(exp.member.member);
176
177                            ProcessExpressionType(argExp);
178
179                            decl = SpecDeclFromString(param.dataTypeString, specs, null);
180
181                            exp.expType = ProcessType(specs, decl);
182
183                            // *[expType] *[argExp]
184                            exp.type = bracketsExp;
185                            exp.list = MkListOne(MkExpOp(null, '*',
186                               MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpOp(null, '&', argExp))));
187                         }
188                      }
189                   }
190                }
191             }
192          }
193       }
194    }
195 }
196
197 ////////////////////////////////////////////////////////////////////////
198 // PRINTING ////////////////////////////////////////////////////////////
199 ////////////////////////////////////////////////////////////////////////
200
201 public char * PrintInt(int64 result)
202 {
203    char temp[100];
204    if(result > MAXINT64)
205       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
206    else
207       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
208    return CopyString(temp);
209 }
210
211 public char * PrintUInt(uint64 result)
212 {
213    char temp[100];
214    if(result > MAXDWORD)
215       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
216    else if(result > MAXINT)
217       sprintf(temp, FORMAT64HEX /*"0x%I64X"*/, result);
218    else
219       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
220    return CopyString(temp);
221 }
222
223 public char * PrintInt64(int64 result)
224 {
225    char temp[100];
226    sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
227    return CopyString(temp);
228 }
229
230 public char * PrintUInt64(uint64 result)
231 {
232    char temp[100];
233    if(result > MAXINT64)
234       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
235    else
236       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
237    return CopyString(temp);
238 }
239
240 public char * PrintHexUInt(uint64 result)
241 {
242    char temp[100];
243    if(result > MAXDWORD)
244       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
245    else
246       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
247    return CopyString(temp);
248 }
249
250 public char * PrintHexUInt64(uint64 result)
251 {
252    char temp[100];
253    if(result > MAXDWORD)
254       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
255    else
256       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
257    return CopyString(temp);
258 }
259
260 public char * PrintShort(short result)
261 {
262    char temp[100];
263    sprintf(temp, "%d", (unsigned short)result);
264    return CopyString(temp);
265 }
266
267 public char * PrintUShort(unsigned short result)
268 {
269    char temp[100];
270    if(result > 32767)
271       sprintf(temp, "0x%X", (int)result);
272    else
273       sprintf(temp, "%d", (int)result);
274    return CopyString(temp);
275 }
276
277 public char * PrintChar(char result)
278 {
279    char temp[100];
280    if(result > 0 && isprint(result))
281       sprintf(temp, "'%c'", result);
282    else if(result < 0)
283       sprintf(temp, "%d", (int)result);
284    else
285       //sprintf(temp, "%#X", result);
286       sprintf(temp, "0x%X", (unsigned char)result);
287    return CopyString(temp);
288 }
289
290 public char * PrintUChar(unsigned char result)
291 {
292    char temp[100];
293    sprintf(temp, "0x%X", result);
294    return CopyString(temp);
295 }
296
297 public char * PrintFloat(float result)
298 {
299    char temp[350];
300    sprintf(temp, "%.16ff", result);
301    return CopyString(temp);
302 }
303
304 public char * PrintDouble(double result)
305 {
306    char temp[350];
307    sprintf(temp, "%.16f", result);
308    return CopyString(temp);
309 }
310
311 ////////////////////////////////////////////////////////////////////////
312 ////////////////////////////////////////////////////////////////////////
313
314 //public Operand GetOperand(Expression exp);
315
316 #define GETVALUE(name, t) \
317    public bool Get##name(Expression exp, t * value2) \
318    {                                                        \
319       Operand op2 = GetOperand(exp);                        \
320       if(op2.kind == intType && op2.type.isSigned) *value2 = (t) op2.i; \
321       else if(op2.kind == intType) *value2 = (t) op2.ui;                 \
322       else if(op2.kind == int64Type && op2.type.isSigned) *value2 = (t) op2.i64; \
323       else if(op2.kind == int64Type) *value2 = (t) op2.ui64;                 \
324       else if(op2.kind == intSizeType && op2.type.isSigned) *value2 = (t) op2.i64; \
325       else if(op2.kind == intSizeType) *value2 = (t) op2.ui64; \
326       else if(op2.kind == intPtrType && op2.type.isSigned) *value2 = (t) op2.i64; \
327       else if(op2.kind == intPtrType) *value2 = (t) op2.ui64;                 \
328       else if(op2.kind == shortType && op2.type.isSigned) *value2 = (t) op2.s;   \
329       else if(op2.kind == shortType) *value2 = (t) op2.us;                        \
330       else if(op2.kind == charType && op2.type.isSigned) *value2 = (t) op2.c;    \
331       else if(op2.kind == _BoolType || op2.kind == charType) *value2 = (t) op2.uc; \
332       else if(op2.kind == floatType) *value2 = (t) op2.f;                         \
333       else if(op2.kind == doubleType) *value2 = (t) op2.d;                        \
334       else if(op2.kind == pointerType) *value2 = (t) op2.ui64;                    \
335       else                                                                          \
336          return false;                                                              \
337       return true;                                                                  \
338    }
339
340 // To help the deubugger currently not preprocessing...
341 #define HELP(x) x
342
343 GETVALUE(Int, HELP(int));
344 GETVALUE(UInt, HELP(unsigned int));
345 GETVALUE(Int64, HELP(int64));
346 GETVALUE(UInt64, HELP(uint64));
347 GETVALUE(IntPtr, HELP(intptr));
348 GETVALUE(UIntPtr, HELP(uintptr));
349 GETVALUE(IntSize, HELP(intsize));
350 GETVALUE(UIntSize, HELP(uintsize));
351 GETVALUE(Short, HELP(short));
352 GETVALUE(UShort, HELP(unsigned short));
353 GETVALUE(Char, HELP(char));
354 GETVALUE(UChar, HELP(unsigned char));
355 GETVALUE(Float, HELP(float));
356 GETVALUE(Double, HELP(double));
357
358 void ComputeExpression(Expression exp);
359
360 void ComputeClassMembers(Class _class, bool isMember)
361 {
362    DataMember member = isMember ? (DataMember) _class : null;
363    Context context = isMember ? null : SetupTemplatesContext(_class);
364    if(member || ((_class.type == bitClass || _class.type == normalClass || _class.type == structClass || _class.type == noHeadClass) &&
365                  (_class.type == bitClass || (!_class.structSize || _class.structSize == _class.offset)) && _class.computeSize))
366    {
367       int c;
368       int unionMemberOffset = 0;
369       int bitFields = 0;
370
371       /*
372       if(!member && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass) && _class.memberOffset && _class.memberOffset > _class.base.structSize)
373          _class.memberOffset = (_class.base && _class.base.type != systemClass) ? _class.base.structSize : 0;
374       */
375
376       if(member)
377       {
378          member.memberOffset = 0;
379          if(targetBits < sizeof(void *) * 8)
380             member.structAlignment = 0;
381       }
382       else if(targetBits < sizeof(void *) * 8)
383          _class.structAlignment = 0;
384
385       // Confusion here: non struct classes seem to have their memberOffset restart at 0 at each hierarchy level
386       if(!member && ((_class.type == normalClass || _class.type == noHeadClass) || (_class.type == structClass && _class.memberOffset && _class.memberOffset > _class.base.structSize)))
387          _class.memberOffset = (_class.base && _class.type == structClass) ? _class.base.structSize : 0;
388
389       if(!member && _class.destructionWatchOffset)
390          _class.memberOffset += sizeof(OldList);
391
392       // To avoid reentrancy...
393       //_class.structSize = -1;
394
395       {
396          DataMember dataMember;
397          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
398          {
399             if(!dataMember.isProperty)
400             {
401                if(dataMember.type == normalMember && dataMember.dataTypeString && !dataMember.dataType)
402                {
403                   dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
404                   /*if(!dataMember.dataType)
405                      dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
406                      */
407                }
408             }
409          }
410       }
411
412       {
413          DataMember dataMember;
414          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
415          {
416             if(!dataMember.isProperty && (dataMember.type != normalMember || dataMember.dataTypeString))
417             {
418                if(!isMember && _class.type == bitClass && dataMember.dataType)
419                {
420                   BitMember bitMember = (BitMember) dataMember;
421                   uint64 mask = 0;
422                   int d;
423
424                   ComputeTypeSize(dataMember.dataType);
425
426                   if(bitMember.pos == -1) bitMember.pos = _class.memberOffset;
427                   if(!bitMember.size) bitMember.size = dataMember.dataType.size * 8;
428
429                   _class.memberOffset = bitMember.pos + bitMember.size;
430                   for(d = 0; d<bitMember.size; d++)
431                   {
432                      if(d)
433                         mask <<= 1;
434                      mask |= 1;
435                   }
436                   bitMember.mask = mask << bitMember.pos;
437                }
438                else if(dataMember.type == normalMember && dataMember.dataType)
439                {
440                   int size;
441                   int alignment = 0;
442
443                   // Prevent infinite recursion
444                   if(dataMember.dataType.kind != classType ||
445                      ((!dataMember.dataType._class || !dataMember.dataType._class.registered || dataMember.dataType._class.registered != _class ||
446                      _class.type != structClass)))
447                      ComputeTypeSize(dataMember.dataType);
448
449                   if(dataMember.dataType.bitFieldCount)
450                   {
451                      bitFields += dataMember.dataType.bitFieldCount;
452                      size = 0;
453                   }
454                   else
455                   {
456                      if(bitFields)
457                      {
458                         int size = (bitFields + 7) / 8;
459
460                         if(isMember)
461                         {
462                            // TESTING THIS PADDING CODE
463                            if(alignment)
464                            {
465                               member.structAlignment = Max(member.structAlignment, alignment);
466
467                               if(member.memberOffset % alignment)
468                                  member.memberOffset += alignment - (member.memberOffset % alignment);
469                            }
470
471                            dataMember.offset = member.memberOffset;
472                            if(member.type == unionMember)
473                               unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
474                            else
475                            {
476                               member.memberOffset += size;
477                            }
478                         }
479                         else
480                         {
481                            // TESTING THIS PADDING CODE
482                            if(alignment)
483                            {
484                               _class.structAlignment = Max(_class.structAlignment, alignment);
485
486                               if(_class.memberOffset % alignment)
487                                  _class.memberOffset += alignment - (_class.memberOffset % alignment);
488                            }
489
490                            dataMember.offset = _class.memberOffset;
491                            _class.memberOffset += size;
492                         }
493                         bitFields = 0;
494                      }
495                      size = dataMember.dataType.size;
496                      alignment = dataMember.dataType.alignment;
497                   }
498
499                   if(isMember)
500                   {
501                      // TESTING THIS PADDING CODE
502                      if(alignment)
503                      {
504                         member.structAlignment = Max(member.structAlignment, alignment);
505
506                         if(member.memberOffset % alignment)
507                            member.memberOffset += alignment - (member.memberOffset % alignment);
508                      }
509
510                      dataMember.offset = member.memberOffset;
511                      if(member.type == unionMember)
512                         unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
513                      else
514                      {
515                         member.memberOffset += size;
516                      }
517                   }
518                   else
519                   {
520                      // TESTING THIS PADDING CODE
521                      if(alignment)
522                      {
523                         _class.structAlignment = Max(_class.structAlignment, alignment);
524
525                         if(_class.memberOffset % alignment)
526                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
527                      }
528
529                      dataMember.offset = _class.memberOffset;
530                      _class.memberOffset += size;
531                   }
532                }
533                else
534                {
535                   int alignment;
536
537                   ComputeClassMembers((Class)dataMember, true);
538                   alignment = dataMember.structAlignment;
539
540                   if(isMember)
541                   {
542                      if(alignment)
543                      {
544                         if(member.memberOffset % alignment)
545                            member.memberOffset += alignment - (member.memberOffset % alignment);
546
547                         member.structAlignment = Max(member.structAlignment, alignment);
548                      }
549                      dataMember.offset = member.memberOffset;
550                      if(member.type == unionMember)
551                         unionMemberOffset = Max(unionMemberOffset, dataMember.memberOffset);
552                      else
553                         member.memberOffset += dataMember.memberOffset;
554                   }
555                   else
556                   {
557                      if(alignment)
558                      {
559                         if(_class.memberOffset % alignment)
560                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
561                         _class.structAlignment = Max(_class.structAlignment, alignment);
562                      }
563                      dataMember.offset = _class.memberOffset;
564                      _class.memberOffset += dataMember.memberOffset;
565                   }
566                }
567             }
568          }
569          if(bitFields)
570          {
571             int alignment = 0;
572             int size = (bitFields + 7) / 8;
573
574             if(isMember)
575             {
576                // TESTING THIS PADDING CODE
577                if(alignment)
578                {
579                   member.structAlignment = Max(member.structAlignment, alignment);
580
581                   if(member.memberOffset % alignment)
582                      member.memberOffset += alignment - (member.memberOffset % alignment);
583                }
584
585                if(member.type == unionMember)
586                   unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
587                else
588                {
589                   member.memberOffset += size;
590                }
591             }
592             else
593             {
594                // TESTING THIS PADDING CODE
595                if(alignment)
596                {
597                   _class.structAlignment = Max(_class.structAlignment, alignment);
598
599                   if(_class.memberOffset % alignment)
600                      _class.memberOffset += alignment - (_class.memberOffset % alignment);
601                }
602                _class.memberOffset += size;
603             }
604             bitFields = 0;
605          }
606       }
607       if(member && member.type == unionMember)
608       {
609          member.memberOffset = unionMemberOffset;
610       }
611
612       if(!isMember)
613       {
614          /*if(_class.type == structClass)
615             _class.size = _class.memberOffset;
616          else
617          */
618
619          if(_class.type != bitClass)
620          {
621             int extra = 0;
622             if(_class.structAlignment)
623             {
624                if(_class.memberOffset % _class.structAlignment)
625                   extra += _class.structAlignment - (_class.memberOffset % _class.structAlignment);
626             }
627             _class.structSize = (_class.base ? (_class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize) : 0) + _class.memberOffset + extra;
628             if(!member)
629             {
630                Property prop;
631                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
632                {
633                   if(prop.isProperty && prop.isWatchable)
634                   {
635                      prop.watcherOffset = _class.structSize;
636                      _class.structSize += sizeof(OldList);
637                   }
638                }
639             }
640
641             // Fix Derivatives
642             {
643                OldLink derivative;
644                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
645                {
646                   Class deriv = derivative.data;
647
648                   if(deriv.computeSize)
649                   {
650                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
651                      deriv.offset = /*_class.offset + */_class.structSize;
652                      deriv.memberOffset = 0;
653                      // ----------------------
654
655                      deriv.structSize = deriv.offset;
656
657                      ComputeClassMembers(deriv, false);
658                   }
659                }
660             }
661          }
662       }
663    }
664    if(context)
665       FinishTemplatesContext(context);
666 }
667
668 public void ComputeModuleClasses(Module module)
669 {
670    Class _class;
671    OldLink subModule;
672
673    for(subModule = module.modules.first; subModule; subModule = subModule.next)
674       ComputeModuleClasses(subModule.data);
675    for(_class = module.classes.first; _class; _class = _class.next)
676       ComputeClassMembers(_class, false);
677 }
678
679
680 public int ComputeTypeSize(Type type)
681 {
682    uint size = type ? type.size : 0;
683    if(!size && type && !type.computing)
684    {
685       type.computing = true;
686       switch(type.kind)
687       {
688          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
689          case charType: type.alignment = size = sizeof(char); break;
690          case intType: type.alignment = size = sizeof(int); break;
691          case int64Type: type.alignment = size = sizeof(int64); break;
692          case intPtrType: type.alignment = size = targetBits / 8; break;
693          case intSizeType: type.alignment = size = targetBits / 8; break;
694          case longType: type.alignment = size = sizeof(long); break;
695          case shortType: type.alignment = size = sizeof(short); break;
696          case floatType: type.alignment = size = sizeof(float); break;
697          case doubleType: type.alignment = size = sizeof(double); break;
698          case classType:
699          {
700             Class _class = type._class ? type._class.registered : null;
701
702             if(_class && _class.type == structClass)
703             {
704                // Ensure all members are properly registered
705                ComputeClassMembers(_class, false);
706                type.alignment = _class.structAlignment;
707                size = _class.structSize;
708                if(type.alignment && size % type.alignment)
709                   size += type.alignment - (size % type.alignment);
710
711             }
712             else if(_class && (_class.type == unitClass ||
713                    _class.type == enumClass ||
714                    _class.type == bitClass))
715             {
716                if(!_class.dataType)
717                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
718                size = type.alignment = ComputeTypeSize(_class.dataType);
719             }
720             else
721                size = type.alignment = targetBits / 8; // sizeof(Instance *);
722             break;
723          }
724          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */break;
725          case arrayType:
726             if(type.arraySizeExp)
727             {
728                ProcessExpressionType(type.arraySizeExp);
729                ComputeExpression(type.arraySizeExp);
730                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType && type.arraySizeExp.expType.kind != enumType &&
731                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
732                {
733                   Location oldLoc = yylloc;
734                   // bool isConstant = type.arraySizeExp.isConstant;
735                   char expression[10240];
736                   expression[0] = '\0';
737                   type.arraySizeExp.expType = null;
738                   yylloc = type.arraySizeExp.loc;
739                   if(inCompiler)
740                      PrintExpression(type.arraySizeExp, expression);
741                   Compiler_Error($"Array size not constant int (%s)\n", expression);
742                   yylloc = oldLoc;
743                }
744                GetInt(type.arraySizeExp, &type.arraySize);
745             }
746             else if(type.enumClass)
747             {
748                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
749                {
750                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
751                }
752                else
753                   type.arraySize = 0;
754             }
755             else
756             {
757                // Unimplemented auto size
758                type.arraySize = 0;
759             }
760
761             size = ComputeTypeSize(type.type) * type.arraySize;
762             if(type.type)
763                type.alignment = type.type.alignment;
764
765             break;
766          case structType:
767          {
768             Type member;
769             for(member = type.members.first; member; member = member.next)
770             {
771                uint addSize = ComputeTypeSize(member);
772
773                member.offset = size;
774                if(member.alignment && size % member.alignment)
775                   member.offset += member.alignment - (size % member.alignment);
776                size = member.offset;
777
778                type.alignment = Max(type.alignment, member.alignment);
779                size += addSize;
780             }
781             if(type.alignment && size % type.alignment)
782                size += type.alignment - (size % type.alignment);
783             break;
784          }
785          case unionType:
786          {
787             Type member;
788             for(member = type.members.first; member; member = member.next)
789             {
790                uint addSize = ComputeTypeSize(member);
791
792                member.offset = size;
793                if(member.alignment && size % member.alignment)
794                   member.offset += member.alignment - (size % member.alignment);
795                size = member.offset;
796
797                type.alignment = Max(type.alignment, member.alignment);
798                size = Max(size, addSize);
799             }
800             if(type.alignment && size % type.alignment)
801                size += type.alignment - (size % type.alignment);
802             break;
803          }
804          case templateType:
805          {
806             TemplateParameter param = type.templateParameter;
807             Type baseType = ProcessTemplateParameterType(param);
808             if(baseType)
809             {
810                size = ComputeTypeSize(baseType);
811                type.alignment = baseType.alignment;
812             }
813             else
814                type.alignment = size = sizeof(uint64);
815             break;
816          }
817          case enumType:
818          {
819             type.alignment = size = sizeof(enum { test });
820             break;
821          }
822          case thisClassType:
823          {
824             type.alignment = size = targetBits / 8; //sizeof(void *);
825             break;
826          }
827       }
828       type.size = size;
829       type.computing = false;
830    }
831    return size;
832 }
833
834
835 /*static */int AddMembers(OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
836 {
837    // This function is in need of a major review when implementing private members etc.
838    DataMember topMember = isMember ? (DataMember) _class : null;
839    uint totalSize = 0;
840    uint maxSize = 0;
841    int alignment, size;
842    DataMember member;
843    Context context = isMember ? null : SetupTemplatesContext(_class);
844    if(addedPadding)
845       *addedPadding = false;
846
847    if(!isMember && _class.base)
848    {
849       maxSize = _class.structSize;
850       //if(_class.base.type != systemClass) // Commented out with new Instance _class
851       {
852          // DANGER: Testing this noHeadClass here...
853          if(_class.type == structClass || _class.type == noHeadClass)
854             /*totalSize = */AddMembers(declarations, _class.base, false, &totalSize, topClass, null);
855          else
856          {
857             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
858             if(maxSize > baseSize)
859                maxSize -= baseSize;
860             else
861                maxSize = 0;
862          }
863       }
864    }
865
866    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
867    {
868       if(!member.isProperty)
869       {
870          switch(member.type)
871          {
872             case normalMember:
873             {
874                if(member.dataTypeString)
875                {
876                   OldList * specs = MkList(), * decls = MkList();
877                   Declarator decl;
878
879                   decl = SpecDeclFromString(member.dataTypeString, specs,
880                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
881                   ListAdd(decls, MkStructDeclarator(decl, null));
882                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
883
884                   if(!member.dataType)
885                      member.dataType = ProcessType(specs, decl);
886
887                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
888
889                   {
890                      Type type = ProcessType(specs, decl);
891                      DeclareType(member.dataType, false, false);
892                      FreeType(type);
893                   }
894                   /*
895                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
896                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
897                      DeclareStruct(member.dataType._class.string, false);
898                   */
899
900                   ComputeTypeSize(member.dataType);
901                   size = member.dataType.size;
902                   alignment = member.dataType.alignment;
903
904                   if(alignment)
905                   {
906                      if(totalSize % alignment)
907                         totalSize += alignment - (totalSize % alignment);
908                   }
909                   totalSize += size;
910                }
911                break;
912             }
913             case unionMember:
914             case structMember:
915             {
916                OldList * specs = MkList(), * list = MkList();
917
918                size = 0;
919                AddMembers(list, (Class)member, true, &size, topClass, null);
920                ListAdd(specs,
921                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
922                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, null, null)));
923                alignment = member.structAlignment;
924
925                if(alignment)
926                {
927                   if(totalSize % alignment)
928                      totalSize += alignment - (totalSize % alignment);
929                }
930                totalSize += size;
931                break;
932             }
933          }
934       }
935    }
936    if(retSize)
937    {
938       if(topMember && topMember.type == unionMember)
939          *retSize = Max(*retSize, totalSize);
940       else
941          *retSize += totalSize;
942    }
943    else if(totalSize < maxSize && _class.type != systemClass)
944    {
945       int autoPadding = 0;
946       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
947          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
948       if(totalSize + autoPadding < maxSize)
949       {
950          char sizeString[50];
951          sprintf(sizeString, "%d", maxSize - totalSize);
952          ListAdd(declarations,
953             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
954             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
955          if(addedPadding)
956             *addedPadding = true;
957       }
958    }
959    if(context)
960       FinishTemplatesContext(context);
961    return topMember ? topMember.memberID : _class.memberID;
962 }
963
964 static int DeclareMembers(Class _class, bool isMember)
965 {
966    DataMember topMember = isMember ? (DataMember) _class : null;
967    uint totalSize = 0;
968    DataMember member;
969    Context context = isMember ? null : SetupTemplatesContext(_class);
970
971    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
972       DeclareMembers(_class.base, false);
973
974    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
975    {
976       if(!member.isProperty)
977       {
978          switch(member.type)
979          {
980             case normalMember:
981             {
982                /*
983                if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
984                   member.dataType._class.registered && member.dataType._class.registered.type == structClass)
985                   DeclareStruct(member.dataType._class.string, false);
986                   */
987                if(!member.dataType && member.dataTypeString)
988                   member.dataType = ProcessTypeString(member.dataTypeString, false);
989                if(member.dataType)
990                   DeclareType(member.dataType, false, false);
991                break;
992             }
993             case unionMember:
994             case structMember:
995             {
996                DeclareMembers((Class)member, true);
997                break;
998             }
999          }
1000       }
1001    }
1002    if(context)
1003       FinishTemplatesContext(context);
1004
1005    return topMember ? topMember.memberID : _class.memberID;
1006 }
1007
1008 void DeclareStruct(char * name, bool skipNoHead)
1009 {
1010    External external = null;
1011    Symbol classSym = FindClass(name);
1012
1013    if(!inCompiler || !classSym) return;
1014
1015    // We don't need any declaration for bit classes...
1016    if(classSym.registered &&
1017       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1018       return;
1019
1020    /*if(classSym.registered.templateClass)
1021       return DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1022    */
1023
1024    if(classSym.registered && classSym.imported && !classSym.declaredStructSym)
1025    {
1026       // Add typedef struct
1027       Declaration decl;
1028       OldList * specifiers, * declarators;
1029       OldList * declarations = null;
1030       char structName[1024];
1031       external = (classSym.registered && classSym.registered.type == structClass) ?
1032          classSym.pointerExternal : classSym.structExternal;
1033
1034       // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1035       // Moved this one up because DeclareClass done later will need it
1036
1037       classSym.declaring++;
1038
1039       if(strchr(classSym.string, '<'))
1040       {
1041          if(classSym.registered.templateClass)
1042          {
1043             DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1044             classSym.declaring--;
1045          }
1046          return;
1047       }
1048
1049       //if(!skipNoHead)
1050          DeclareMembers(classSym.registered, false);
1051
1052       structName[0] = 0;
1053       FullClassNameCat(structName, name, false);
1054
1055       /*if(!external)
1056          external = MkExternalDeclaration(null);*/
1057
1058       if(!skipNoHead)
1059       {
1060          bool addedPadding = false;
1061          classSym.declaredStructSym = true;
1062
1063          declarations = MkList();
1064
1065          AddMembers(declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1066
1067          //ListAdd(specifiers, MkSpecifier(TYPEDEF));
1068          //ListAdd(specifiers, MkStructOrUnion(structSpecifier, null, declarations));
1069
1070          if(!declarations->count || (declarations->count == 1 && addedPadding))
1071          {
1072             FreeList(declarations, FreeClassDef);
1073             declarations = null;
1074          }
1075       }
1076       if(skipNoHead || declarations)
1077       {
1078          if(external && external.declaration)
1079          {
1080             ((Specifier)external.declaration.specifiers->first).definitions = declarations;
1081
1082             if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1083             {
1084                // TODO: Fix this
1085                //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1086
1087                // DANGER
1088                if(classSym.structExternal)
1089                   ast->Move(classSym.structExternal, curExternal.prev);
1090                ast->Move(classSym.pointerExternal, curExternal.prev);
1091
1092                classSym.id = curExternal.symbol.idCode;
1093                classSym.idCode = curExternal.symbol.idCode;
1094                // external = classSym.pointerExternal;
1095                //external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1096             }
1097          }
1098          else
1099          {
1100             if(!external)
1101                external = MkExternalDeclaration(null);
1102
1103             specifiers = MkList();
1104             declarators = MkList();
1105             ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1106
1107             /*
1108             d = MkDeclaratorIdentifier(MkIdentifier(structName));
1109             ListAdd(declarators, MkInitDeclarator(d, null));
1110             */
1111             external.declaration = decl = MkDeclaration(specifiers, declarators);
1112             if(decl.symbol && !decl.symbol.pointerExternal)
1113                decl.symbol.pointerExternal = external;
1114
1115             // For simple classes, keep the declaration as the external to move around
1116             if(classSym.registered && classSym.registered.type == structClass)
1117             {
1118                char className[1024];
1119                strcpy(className, "__ecereClass_");
1120                FullClassNameCat(className, classSym.string, true);
1121                MangleClassName(className);
1122
1123                // Testing This
1124                DeclareClass(classSym, className);
1125
1126                external.symbol = classSym;
1127                classSym.pointerExternal = external;
1128                classSym.id = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1129                classSym.idCode = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1130             }
1131             else
1132             {
1133                char className[1024];
1134                strcpy(className, "__ecereClass_");
1135                FullClassNameCat(className, classSym.string, true);
1136                MangleClassName(className);
1137
1138                // TOFIX: TESTING THIS...
1139                classSym.structExternal = external;
1140                DeclareClass(classSym, className);
1141                external.symbol = classSym;
1142             }
1143
1144             //if(curExternal)
1145                ast->Insert(curExternal ? curExternal.prev : null, external);
1146          }
1147       }
1148
1149       classSym.declaring--;
1150    }
1151    else if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1152    {
1153       // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1154       // Moved this one up because DeclareClass done later will need it
1155
1156       // TESTING THIS:
1157       classSym.declaring++;
1158
1159       //if(!skipNoHead)
1160       {
1161          if(classSym.registered)
1162             DeclareMembers(classSym.registered, false);
1163       }
1164
1165       if(classSym.registered && (classSym.registered.type == structClass || classSym.registered.type == noHeadClass))
1166       {
1167          // TODO: Fix this
1168          //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1169
1170          // DANGER
1171          if(classSym.structExternal)
1172             ast->Move(classSym.structExternal, curExternal.prev);
1173          ast->Move(classSym.pointerExternal, curExternal.prev);
1174
1175          classSym.id = curExternal.symbol.idCode;
1176          classSym.idCode = curExternal.symbol.idCode;
1177          // external = classSym.pointerExternal;
1178          // external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1179       }
1180
1181       classSym.declaring--;
1182    }
1183    //return external;
1184 }
1185
1186 void DeclareProperty(Property prop, char * setName, char * getName)
1187 {
1188    Symbol symbol = prop.symbol;
1189    char propName[1024];
1190
1191    strcpy(setName, "__ecereProp_");
1192    FullClassNameCat(setName, prop._class.fullName, false);
1193    strcat(setName, "_Set_");
1194    // strcat(setName, prop.name);
1195    FullClassNameCat(setName, prop.name, true);
1196
1197    strcpy(getName, "__ecereProp_");
1198    FullClassNameCat(getName, prop._class.fullName, false);
1199    strcat(getName, "_Get_");
1200    FullClassNameCat(getName, prop.name, true);
1201    // strcat(getName, prop.name);
1202
1203    strcpy(propName, "__ecereProp_");
1204    FullClassNameCat(propName, prop._class.fullName, false);
1205    strcat(propName, "_");
1206    FullClassNameCat(propName, prop.name, true);
1207    // strcat(propName, prop.name);
1208
1209    // To support "char *" property
1210    MangleClassName(getName);
1211    MangleClassName(setName);
1212    MangleClassName(propName);
1213
1214    if(prop._class.type == structClass)
1215       DeclareStruct(prop._class.fullName, false);
1216
1217    if(!symbol || curExternal.symbol.idCode < symbol.id)
1218    {
1219       bool imported = false;
1220       bool dllImport = false;
1221       if(!symbol || symbol._import)
1222       {
1223          if(!symbol)
1224          {
1225             Symbol classSym;
1226             if(!prop._class.symbol)
1227                prop._class.symbol = FindClass(prop._class.fullName);
1228             classSym = prop._class.symbol;
1229             if(classSym && !classSym._import)
1230             {
1231                ModuleImport module;
1232
1233                if(prop._class.module)
1234                   module = FindModule(prop._class.module);
1235                else
1236                   module = mainModule;
1237
1238                classSym._import = ClassImport
1239                {
1240                   name = CopyString(prop._class.fullName);
1241                   isRemote = prop._class.isRemote;
1242                };
1243                module.classes.Add(classSym._import);
1244             }
1245             symbol = prop.symbol = Symbol { };
1246             symbol._import = (ClassImport)PropertyImport
1247             {
1248                name = CopyString(prop.name);
1249                isVirtual = false; //prop.isVirtual;
1250                hasSet = prop.Set ? true : false;
1251                hasGet = prop.Get ? true : false;
1252             };
1253             if(classSym)
1254                classSym._import.properties.Add(symbol._import);
1255          }
1256          imported = true;
1257          if(prop._class.module != privateModule && prop._class.module.importType != staticImport)
1258             dllImport = true;
1259       }
1260
1261       if(!symbol.type)
1262       {
1263          Context context = SetupTemplatesContext(prop._class);
1264          symbol.type = ProcessTypeString(prop.dataTypeString, false);
1265          FinishTemplatesContext(context);
1266       }
1267
1268       // Get
1269       if(prop.Get)
1270       {
1271          if(!symbol.externalGet || symbol.externalGet.type == functionExternal)
1272          {
1273             Declaration decl;
1274             OldList * specifiers, * declarators;
1275             Declarator d;
1276             OldList * params;
1277             Specifier spec;
1278             External external;
1279             Declarator typeDecl;
1280             bool simple = false;
1281
1282             specifiers = MkList();
1283             declarators = MkList();
1284             params = MkList();
1285
1286             ListAdd(params, MkTypeName(MkListOne(MkSpecifierName /*MkClassName*/(prop._class.fullName)),
1287                MkDeclaratorIdentifier(MkIdentifier("this"))));
1288
1289             d = MkDeclaratorIdentifier(MkIdentifier(getName));
1290             //if(imported)
1291             if(dllImport)
1292                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1293
1294             {
1295                Context context = SetupTemplatesContext(prop._class);
1296                typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1297                FinishTemplatesContext(context);
1298             }
1299
1300             // Make sure the simple _class's type is declared
1301             for(spec = specifiers->first; spec; spec = spec.next)
1302             {
1303                if(spec.type == nameSpecifier /*SpecifierClass*/)
1304                {
1305                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1306                   {
1307                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1308                      symbol._class = classSym.registered;
1309                      if(classSym.registered && classSym.registered.type == structClass)
1310                      {
1311                         DeclareStruct(spec.name, false);
1312                         simple = true;
1313                      }
1314                   }
1315                }
1316             }
1317
1318             if(!simple)
1319                d = PlugDeclarator(typeDecl, d);
1320             else
1321             {
1322                ListAdd(params, MkTypeName(specifiers,
1323                   PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1324                specifiers = MkList();
1325             }
1326
1327             d = MkDeclaratorFunction(d, params);
1328
1329             //if(imported)
1330             if(dllImport)
1331                specifiers->Insert(null, MkSpecifier(EXTERN));
1332             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1333                specifiers->Insert(null, MkSpecifier(STATIC));
1334             if(simple)
1335                ListAdd(specifiers, MkSpecifier(VOID));
1336
1337             ListAdd(declarators, MkInitDeclarator(d, null));
1338
1339             decl = MkDeclaration(specifiers, declarators);
1340
1341             external = MkExternalDeclaration(decl);
1342             ast->Insert(curExternal.prev, external);
1343             external.symbol = symbol;
1344             symbol.externalGet = external;
1345
1346             ReplaceThisClassSpecifiers(specifiers, prop._class);
1347
1348             if(typeDecl)
1349                FreeDeclarator(typeDecl);
1350          }
1351          else
1352          {
1353             // Move declaration higher...
1354             ast->Move(symbol.externalGet, curExternal.prev);
1355          }
1356       }
1357
1358       // Set
1359       if(prop.Set)
1360       {
1361          if(!symbol.externalSet || symbol.externalSet.type == functionExternal)
1362          {
1363             Declaration decl;
1364             OldList * specifiers, * declarators;
1365             Declarator d;
1366             OldList * params;
1367             Specifier spec;
1368             External external;
1369             Declarator typeDecl;
1370
1371             declarators = MkList();
1372             params = MkList();
1373
1374             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1375             if(!prop.conversion || prop._class.type == structClass)
1376             {
1377                ListAdd(params, MkTypeName(MkListOne(MkSpecifierName/*MkClassName*/(prop._class.fullName)),
1378                   MkDeclaratorIdentifier(MkIdentifier("this"))));
1379             }
1380
1381             specifiers = MkList();
1382
1383             {
1384                Context context = SetupTemplatesContext(prop._class);
1385                typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1386                   MkDeclaratorIdentifier(MkIdentifier("value")));
1387                FinishTemplatesContext(context);
1388             }
1389             ListAdd(params, MkTypeName(specifiers, d));
1390
1391             d = MkDeclaratorIdentifier(MkIdentifier(setName));
1392             //if(imported)
1393             if(dllImport)
1394                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1395             d = MkDeclaratorFunction(d, params);
1396
1397             // Make sure the simple _class's type is declared
1398             for(spec = specifiers->first; spec; spec = spec.next)
1399             {
1400                if(spec.type == nameSpecifier /*SpecifierClass*/)
1401                {
1402                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1403                   {
1404                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1405                      symbol._class = classSym.registered;
1406                      if(classSym.registered && classSym.registered.type == structClass)
1407                         DeclareStruct(spec.name, false);
1408                   }
1409                }
1410             }
1411
1412             ListAdd(declarators, MkInitDeclarator(d, null));
1413
1414             specifiers = MkList();
1415             //if(imported)
1416             if(dllImport)
1417                specifiers->Insert(null, MkSpecifier(EXTERN));
1418             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1419                specifiers->Insert(null, MkSpecifier(STATIC));
1420
1421             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1422             if(!prop.conversion || prop._class.type == structClass)
1423                ListAdd(specifiers, MkSpecifier(VOID));
1424             else
1425                ListAdd(specifiers, MkSpecifierName/*MkClassName*/(prop._class.fullName));
1426
1427             decl = MkDeclaration(specifiers, declarators);
1428
1429             external = MkExternalDeclaration(decl);
1430             ast->Insert(curExternal.prev, external);
1431             external.symbol = symbol;
1432             symbol.externalSet = external;
1433
1434             ReplaceThisClassSpecifiers(specifiers, prop._class);
1435          }
1436          else
1437          {
1438             // Move declaration higher...
1439             ast->Move(symbol.externalSet, curExternal.prev);
1440          }
1441       }
1442
1443       // Property (for Watchers)
1444       if(!symbol.externalPtr)
1445       {
1446          Declaration decl;
1447          External external;
1448          OldList * specifiers = MkList();
1449
1450          if(imported)
1451             specifiers->Insert(null, MkSpecifier(EXTERN));
1452          else
1453             specifiers->Insert(null, MkSpecifier(STATIC));
1454
1455          ListAdd(specifiers, MkSpecifierName("Property"));
1456
1457          {
1458             OldList * list = MkList();
1459             ListAdd(list, MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null),
1460                   MkDeclaratorIdentifier(MkIdentifier(propName))), null));
1461
1462             if(!imported)
1463             {
1464                strcpy(propName, "__ecerePropM_");
1465                FullClassNameCat(propName, prop._class.fullName, false);
1466                strcat(propName, "_");
1467                // strcat(propName, prop.name);
1468                FullClassNameCat(propName, prop.name, true);
1469
1470                MangleClassName(propName);
1471
1472                ListAdd(list, MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null),
1473                      MkDeclaratorIdentifier(MkIdentifier(propName))), null));
1474             }
1475             decl = MkDeclaration(specifiers, list);
1476          }
1477
1478          external = MkExternalDeclaration(decl);
1479          ast->Insert(curExternal.prev, external);
1480          external.symbol = symbol;
1481          symbol.externalPtr = external;
1482       }
1483       else
1484       {
1485          // Move declaration higher...
1486          ast->Move(symbol.externalPtr, curExternal.prev);
1487       }
1488
1489       symbol.id = curExternal.symbol.idCode;
1490    }
1491 }
1492
1493 // ***************** EXPRESSION PROCESSING ***************************
1494 public Type Dereference(Type source)
1495 {
1496    Type type = null;
1497    if(source)
1498    {
1499       if(source.kind == pointerType || source.kind == arrayType)
1500       {
1501          type = source.type;
1502          source.type.refCount++;
1503       }
1504       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1505       {
1506          type = Type
1507          {
1508             kind = charType;
1509             refCount = 1;
1510          };
1511       }
1512       // Support dereferencing of no head classes for now...
1513       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1514       {
1515          type = source;
1516          source.refCount++;
1517       }
1518       else
1519          Compiler_Error($"cannot dereference type\n");
1520    }
1521    return type;
1522 }
1523
1524 static Type Reference(Type source)
1525 {
1526    Type type = null;
1527    if(source)
1528    {
1529       type = Type
1530       {
1531          kind = pointerType;
1532          type = source;
1533          refCount = 1;
1534       };
1535       source.refCount++;
1536    }
1537    return type;
1538 }
1539
1540 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1541 {
1542    Identifier ident = member.identifiers ? member.identifiers->first : null;
1543    bool found = false;
1544    DataMember dataMember = null;
1545    Method method = null;
1546    bool freeType = false;
1547
1548    yylloc = member.loc;
1549
1550    if(!ident)
1551    {
1552       if(curMember)
1553       {
1554          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1555          if(*curMember)
1556          {
1557             found = true;
1558             dataMember = *curMember;
1559          }
1560       }
1561    }
1562    else
1563    {
1564       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1565       DataMember _subMemberStack[256];
1566       int _subMemberStackPos = 0;
1567
1568       // FILL MEMBER STACK
1569       if(!thisMember)
1570          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1571       if(thisMember)
1572       {
1573          dataMember = thisMember;
1574          if(curMember && thisMember.memberAccess == publicAccess)
1575          {
1576             *curMember = thisMember;
1577             *curClass = thisMember._class;
1578             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1579             *subMemberStackPos = _subMemberStackPos;
1580          }
1581          found = true;
1582       }
1583       else
1584       {
1585          // Setting a method
1586          method = eClass_FindMethod(_class, ident.string, privateModule);
1587          if(method && method.type == virtualMethod)
1588             found = true;
1589          else
1590             method = null;
1591       }
1592    }
1593
1594    if(found)
1595    {
1596       Type type = null;
1597       if(dataMember)
1598       {
1599          if(!dataMember.dataType && dataMember.dataTypeString)
1600          {
1601             //Context context = SetupTemplatesContext(dataMember._class);
1602             Context context = SetupTemplatesContext(_class);
1603             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1604             FinishTemplatesContext(context);
1605          }
1606          type = dataMember.dataType;
1607       }
1608       else if(method)
1609       {
1610          // This is for destination type...
1611          if(!method.dataType)
1612             ProcessMethodType(method);
1613          //DeclareMethod(method);
1614          // method.dataType = ((Symbol)method.symbol)->type;
1615          type = method.dataType;
1616       }
1617
1618       if(ident && ident.next)
1619       {
1620          for(ident = ident.next; ident && type; ident = ident.next)
1621          {
1622             if(type.kind == classType)
1623             {
1624                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1625                if(!dataMember)
1626                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1627                if(dataMember)
1628                   type = dataMember.dataType;
1629             }
1630             else if(type.kind == structType || type.kind == unionType)
1631             {
1632                Type memberType;
1633                for(memberType = type.members.first; memberType; memberType = memberType.next)
1634                {
1635                   if(!strcmp(memberType.name, ident.string))
1636                   {
1637                      type = memberType;
1638                      break;
1639                   }
1640                }
1641             }
1642          }
1643       }
1644
1645       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1646       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1647       {
1648          int id = 0;
1649          ClassTemplateParameter curParam = null;
1650          Class sClass;
1651          for(sClass = _class; sClass; sClass = sClass.base)
1652          {
1653             id = 0;
1654             if(sClass.templateClass) sClass = sClass.templateClass;
1655             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1656             {
1657                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1658                {
1659                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1660                   {
1661                      if(sClass.templateClass) sClass = sClass.templateClass;
1662                      id += sClass.templateParams.count;
1663                   }
1664                   break;
1665                }
1666                id++;
1667             }
1668             if(curParam) break;
1669          }
1670
1671          if(curParam)
1672          {
1673             ClassTemplateArgument arg = _class.templateArgs[id];
1674             if(arg.dataTypeString)
1675             {
1676                // FreeType(type);
1677                type = ProcessTypeString(arg.dataTypeString, false);
1678                freeType = true;
1679                if(type && _class.templateClass)
1680                   type.passAsTemplate = true;
1681                if(type)
1682                {
1683                   // type.refCount++;
1684                   /*if(!exp.destType)
1685                   {
1686                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1687                      exp.destType.refCount++;
1688                   }*/
1689                }
1690             }
1691          }
1692       }
1693       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1694       {
1695          Class expClass = type._class.registered;
1696          Class cClass = null;
1697          int c;
1698          int paramCount = 0;
1699          int lastParam = -1;
1700
1701          char templateString[1024];
1702          ClassTemplateParameter param;
1703          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1704          for(cClass = expClass; cClass; cClass = cClass.base)
1705          {
1706             int p = 0;
1707             if(cClass.templateClass) cClass = cClass.templateClass;
1708             for(param = cClass.templateParams.first; param; param = param.next)
1709             {
1710                int id = p;
1711                Class sClass;
1712                ClassTemplateArgument arg;
1713                for(sClass = cClass.base; sClass; sClass = sClass.base)
1714                {
1715                   if(sClass.templateClass) sClass = sClass.templateClass;
1716                   id += sClass.templateParams.count;
1717                }
1718                arg = expClass.templateArgs[id];
1719
1720                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1721                {
1722                   ClassTemplateParameter cParam;
1723                   //int p = numParams - sClass.templateParams.count;
1724                   int p = 0;
1725                   Class nextClass;
1726                   if(sClass.templateClass) sClass = sClass.templateClass;
1727
1728                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1729                   {
1730                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1731                      p += nextClass.templateParams.count;
1732                   }
1733
1734                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1735                   {
1736                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1737                      {
1738                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1739                         {
1740                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1741                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1742                            break;
1743                         }
1744                      }
1745                   }
1746                }
1747
1748                {
1749                   char argument[256];
1750                   argument[0] = '\0';
1751                   /*if(arg.name)
1752                   {
1753                      strcat(argument, arg.name.string);
1754                      strcat(argument, " = ");
1755                   }*/
1756                   switch(param.type)
1757                   {
1758                      case expression:
1759                      {
1760                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1761                         char expString[1024];
1762                         OldList * specs = MkList();
1763                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1764                         Expression exp;
1765                         char * string = PrintHexUInt64(arg.expression.ui64);
1766                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1767
1768                         ProcessExpressionType(exp);
1769                         ComputeExpression(exp);
1770                         expString[0] = '\0';
1771                         PrintExpression(exp, expString);
1772                         strcat(argument, expString);
1773                         //delete exp;
1774                         FreeExpression(exp);
1775                         break;
1776                      }
1777                      case identifier:
1778                      {
1779                         strcat(argument, arg.member.name);
1780                         break;
1781                      }
1782                      case TemplateParameterType::type:
1783                      {
1784                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1785                            strcat(argument, arg.dataTypeString);
1786                         break;
1787                      }
1788                   }
1789                   if(argument[0])
1790                   {
1791                      if(paramCount) strcat(templateString, ", ");
1792                      if(lastParam != p - 1)
1793                      {
1794                         strcat(templateString, param.name);
1795                         strcat(templateString, " = ");
1796                      }
1797                      strcat(templateString, argument);
1798                      paramCount++;
1799                      lastParam = p;
1800                   }
1801                   p++;
1802                }
1803             }
1804          }
1805          {
1806             int len = strlen(templateString);
1807             if(templateString[len-1] == '<')
1808                len--;
1809             else
1810             {
1811                if(templateString[len-1] == '>')
1812                   templateString[len++] = ' ';
1813                templateString[len++] = '>';
1814             }
1815             templateString[len++] = '\0';
1816          }
1817          {
1818             Context context = SetupTemplatesContext(_class);
1819             if(freeType) FreeType(type);
1820             type = ProcessTypeString(templateString, false);
1821             freeType = true;
1822             FinishTemplatesContext(context);
1823          }
1824       }
1825
1826       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1827       {
1828          ProcessExpressionType(member.initializer.exp);
1829          if(!member.initializer.exp.expType)
1830          {
1831             if(inCompiler)
1832             {
1833                char expString[10240];
1834                expString[0] = '\0';
1835                PrintExpression(member.initializer.exp, expString);
1836                ChangeCh(expString, '\n', ' ');
1837                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1838             }
1839          }
1840          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1841          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false))
1842          {
1843             Compiler_Error($"incompatible instance method %s\n", ident.string);
1844          }
1845       }
1846       else if(member.initializer)
1847       {
1848          /*
1849          FreeType(member.exp.destType);
1850          member.exp.destType = type;
1851          if(member.exp.destType)
1852             member.exp.destType.refCount++;
1853          ProcessExpressionType(member.exp);
1854          */
1855
1856          ProcessInitializer(member.initializer, type);
1857       }
1858       if(freeType) FreeType(type);
1859    }
1860    else
1861    {
1862       if(_class && _class.type == unitClass)
1863       {
1864          if(member.initializer)
1865          {
1866             /*
1867             FreeType(member.exp.destType);
1868             member.exp.destType = MkClassType(_class.fullName);
1869             ProcessExpressionType(member.initializer, type);
1870             */
1871             Type type = MkClassType(_class.fullName);
1872             ProcessInitializer(member.initializer, type);
1873             FreeType(type);
1874          }
1875       }
1876       else
1877       {
1878          if(member.initializer)
1879          {
1880             //ProcessExpressionType(member.exp);
1881             ProcessInitializer(member.initializer, null);
1882          }
1883          if(ident)
1884          {
1885             if(method)
1886             {
1887                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
1888             }
1889             else if(_class)
1890             {
1891                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
1892                if(inCompiler)
1893                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
1894             }
1895          }
1896          else if(_class)
1897             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
1898       }
1899    }
1900 }
1901
1902 void ProcessInstantiationType(Instantiation inst)
1903 {
1904    yylloc = inst.loc;
1905    if(inst._class)
1906    {
1907       MembersInit members;
1908       Symbol classSym; // = inst._class.symbol; // FindClass(inst._class.name);
1909       Class _class;
1910
1911       /*if(!inst._class.symbol)
1912          inst._class.symbol = FindClass(inst._class.name);*/
1913       classSym = inst._class.symbol;
1914       _class = classSym ? classSym.registered : null;
1915
1916       // DANGER: Patch for mutex not declaring its struct when not needed
1917       if(!_class || _class.type != noHeadClass)
1918          DeclareStruct(inst._class.name, false); //_class && _class.type == noHeadClass);
1919
1920       afterExternal = afterExternal ? afterExternal : curExternal;
1921
1922       if(inst.exp)
1923          ProcessExpressionType(inst.exp);
1924
1925       inst.isConstant = true;
1926       if(inst.members)
1927       {
1928          DataMember curMember = null;
1929          Class curClass = null;
1930          DataMember subMemberStack[256];
1931          int subMemberStackPos = 0;
1932
1933          for(members = inst.members->first; members; members = members.next)
1934          {
1935             switch(members.type)
1936             {
1937                case methodMembersInit:
1938                {
1939                   char name[1024];
1940                   static uint instMethodID = 0;
1941                   External external = curExternal;
1942                   Context context = curContext;
1943                   Declarator declarator = members.function.declarator;
1944                   Identifier nameID = GetDeclId(declarator);
1945                   char * unmangled = nameID ? nameID.string : null;
1946                   Expression exp;
1947                   External createdExternal = null;
1948
1949                   if(inCompiler)
1950                   {
1951                      char number[16];
1952                      //members.function.dontMangle = true;
1953                      strcpy(name, "__ecereInstMeth_");
1954                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
1955                      strcat(name, "_");
1956                      strcat(name, nameID.string);
1957                      strcat(name, "_");
1958                      sprintf(number, "_%08d", instMethodID++);
1959                      strcat(name, number);
1960                      nameID.string = CopyString(name);
1961                   }
1962
1963                   // Do modifications here...
1964                   if(declarator)
1965                   {
1966                      Symbol symbol = declarator.symbol;
1967                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
1968
1969                      if(method && method.type == virtualMethod)
1970                      {
1971                         symbol.method = method;
1972                         ProcessMethodType(method);
1973
1974                         if(!symbol.type.thisClass)
1975                         {
1976                            if(method.dataType.thisClass && currentClass &&
1977                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
1978                            {
1979                               if(!currentClass.symbol)
1980                                  currentClass.symbol = FindClass(currentClass.fullName);
1981                               symbol.type.thisClass = currentClass.symbol;
1982                            }
1983                            else
1984                            {
1985                               if(!_class.symbol)
1986                                  _class.symbol = FindClass(_class.fullName);
1987                               symbol.type.thisClass = _class.symbol;
1988                            }
1989                         }
1990                         // TESTING THIS HERE:
1991                         DeclareType(symbol.type, true, true);
1992
1993                      }
1994                      else if(classSym)
1995                      {
1996                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
1997                            unmangled, classSym.string);
1998                      }
1999                   }
2000
2001                   //declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2002                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2003
2004                   if(nameID)
2005                   {
2006                      FreeSpecifier(nameID._class);
2007                      nameID._class = null;
2008                   }
2009
2010                   if(inCompiler)
2011                   {
2012
2013                      Type type = declarator.symbol.type;
2014                      External oldExternal = curExternal;
2015
2016                      // *** Commented this out... Any negative impact? Yes: makes double prototypes declarations... Why was it commented out?
2017                      // *** It was commented out for problems such as
2018                      /*
2019                            class VirtualDesktop : Window
2020                            {
2021                               clientSize = Size { };
2022                               Timer timer
2023                               {
2024                                  bool DelayExpired()
2025                                  {
2026                                     clientSize.w;
2027                                     return true;
2028                                  }
2029                               };
2030                            }
2031                      */
2032                      // Commented Out: Good for bet.ec in Poker (Otherwise: obj\bet.c:187: error: `currentBet' undeclared (first use in this function))
2033
2034                      declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2035
2036                      /*
2037                      if(strcmp(declarator.symbol.string, name))
2038                      {
2039                         printf("TOCHECK: Look out for this\n");
2040                         delete declarator.symbol.string;
2041                         declarator.symbol.string = CopyString(name);
2042                      }
2043
2044                      if(!declarator.symbol.parent && globalContext.symbols.root != (BTNode)declarator.symbol)
2045                      {
2046                         printf("TOCHECK: Will this ever be in a list? Yes.\n");
2047                         excludedSymbols->Remove(declarator.symbol);
2048                         globalContext.symbols.Add((BTNode)declarator.symbol);
2049                         if(strstr(declarator.symbol.string), "::")
2050                            globalContext.hasNameSpace = true;
2051
2052                      }
2053                      */
2054
2055                      //curExternal = curExternal.prev;
2056                      //afterExternal = afterExternal->next;
2057
2058                      //ProcessFunction(afterExternal->function);
2059
2060                      //curExternal = afterExternal;
2061                      {
2062                         External externalDecl;
2063                         externalDecl = MkExternalDeclaration(null);
2064                         ast->Insert(oldExternal.prev, externalDecl);
2065
2066                         // Which function does this process?
2067                         if(createdExternal.function)
2068                         {
2069                            ProcessFunction(createdExternal.function);
2070
2071                            //curExternal = oldExternal;
2072
2073                            {
2074                               //Declaration decl = MkDeclaration(members.function.specifiers, MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2075
2076                               Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
2077                                  MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2078
2079                               //externalDecl = MkExternalDeclaration(decl);
2080
2081                               //***** ast->Insert(external.prev, externalDecl);
2082                               //ast->Insert(curExternal.prev, externalDecl);
2083                               externalDecl.declaration = decl;
2084                               if(decl.symbol && !decl.symbol.pointerExternal)
2085                                  decl.symbol.pointerExternal = externalDecl;
2086
2087                               // Trying this out...
2088                               declarator.symbol.pointerExternal = externalDecl;
2089                            }
2090                         }
2091                      }
2092                   }
2093                   else if(declarator)
2094                   {
2095                      curExternal = declarator.symbol.pointerExternal;
2096                      ProcessFunction((FunctionDefinition)members.function);
2097                   }
2098                   curExternal = external;
2099                   curContext = context;
2100
2101                   if(inCompiler)
2102                   {
2103                      FreeClassFunction(members.function);
2104
2105                      // In this pass, turn this into a MemberInitData
2106                      exp = QMkExpId(name);
2107                      members.type = dataMembersInit;
2108                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2109
2110                      delete unmangled;
2111                   }
2112                   break;
2113                }
2114                case dataMembersInit:
2115                {
2116                   if(members.dataMembers && classSym)
2117                   {
2118                      MemberInit member;
2119                      Location oldyyloc = yylloc;
2120                      for(member = members.dataMembers->first; member; member = member.next)
2121                      {
2122                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2123                         if(member.initializer && !member.initializer.isConstant)
2124                            inst.isConstant = false;
2125                      }
2126                      yylloc = oldyyloc;
2127                   }
2128                   break;
2129                }
2130             }
2131          }
2132       }
2133    }
2134 }
2135
2136 static void DeclareType(Type type, bool declarePointers, bool declareParams)
2137 {
2138    // OPTIMIZATIONS: TESTING THIS...
2139    if(inCompiler)
2140    {
2141       if(type.kind == functionType)
2142       {
2143          Type param;
2144          if(declareParams)
2145          {
2146             for(param = type.params.first; param; param = param.next)
2147                DeclareType(param, declarePointers, true);
2148          }
2149          DeclareType(type.returnType, declarePointers, true);
2150       }
2151       else if(type.kind == pointerType && declarePointers)
2152          DeclareType(type.type, declarePointers, false);
2153       else if(type.kind == classType)
2154       {
2155          if(type._class.registered && (type._class.registered.type == structClass || type._class.registered.type == noHeadClass) && !type._class.declaring)
2156             DeclareStruct(type._class.registered.fullName, type._class.registered.type == noHeadClass);
2157       }
2158       else if(type.kind == structType || type.kind == unionType)
2159       {
2160          Type member;
2161          for(member = type.members.first; member; member = member.next)
2162             DeclareType(member, false, false);
2163       }
2164       else if(type.kind == arrayType)
2165          DeclareType(type.arrayType, declarePointers, false);
2166    }
2167 }
2168
2169 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2170 {
2171    ClassTemplateArgument * arg = null;
2172    int id = 0;
2173    ClassTemplateParameter curParam = null;
2174    Class sClass;
2175    for(sClass = _class; sClass; sClass = sClass.base)
2176    {
2177       id = 0;
2178       if(sClass.templateClass) sClass = sClass.templateClass;
2179       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2180       {
2181          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2182          {
2183             for(sClass = sClass.base; sClass; sClass = sClass.base)
2184             {
2185                if(sClass.templateClass) sClass = sClass.templateClass;
2186                id += sClass.templateParams.count;
2187             }
2188             break;
2189          }
2190          id++;
2191       }
2192       if(curParam) break;
2193    }
2194    if(curParam)
2195    {
2196       arg = &_class.templateArgs[id];
2197       if(arg && param.type == type)
2198          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2199    }
2200    return arg;
2201 }
2202
2203 public Context SetupTemplatesContext(Class _class)
2204 {
2205    Context context = PushContext();
2206    context.templateTypesOnly = true;
2207    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2208    {
2209       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2210       for(; param; param = param.next)
2211       {
2212          if(param.type == type && param.identifier)
2213          {
2214             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2215             curContext.templateTypes.Add((BTNode)type);
2216          }
2217       }
2218    }
2219    else if(_class)
2220    {
2221       Class sClass;
2222       for(sClass = _class; sClass; sClass = sClass.base)
2223       {
2224          ClassTemplateParameter p;
2225          for(p = sClass.templateParams.first; p; p = p.next)
2226          {
2227             //OldList * specs = MkList();
2228             //Declarator decl = null;
2229             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2230             if(p.type == type)
2231             {
2232                TemplateParameter param = p.param;
2233                TemplatedType type;
2234                if(!param)
2235                {
2236                   // ADD DATA TYPE HERE...
2237                   p.param = param = TemplateParameter
2238                   {
2239                      identifier = MkIdentifier(p.name), type = p.type,
2240                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2241                   };
2242                }
2243                type = TemplatedType { key = (uintptr)p.name, param = param };
2244                curContext.templateTypes.Add((BTNode)type);
2245             }
2246          }
2247       }
2248    }
2249    return context;
2250 }
2251
2252 public void FinishTemplatesContext(Context context)
2253 {
2254    PopContext(context);
2255    FreeContext(context);
2256    delete context;
2257 }
2258
2259 public void ProcessMethodType(Method method)
2260 {
2261    if(!method.dataType)
2262    {
2263       Context context = SetupTemplatesContext(method._class);
2264
2265       method.dataType = ProcessTypeString(method.dataTypeString, false);
2266
2267       FinishTemplatesContext(context);
2268
2269       if(method.type != virtualMethod && method.dataType)
2270       {
2271          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2272          {
2273             if(!method._class.symbol)
2274                method._class.symbol = FindClass(method._class.fullName);
2275             method.dataType.thisClass = method._class.symbol;
2276          }
2277       }
2278
2279       // Why was this commented out? Working fine without now...
2280
2281       /*
2282       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2283          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2284          */
2285    }
2286
2287    /*
2288    if(type)
2289    {
2290       char * par = strstr(type, "(");
2291       char * classOp = null;
2292       int classOpLen = 0;
2293       if(par)
2294       {
2295          int c;
2296          for(c = par-type-1; c >= 0; c++)
2297          {
2298             if(type[c] == ':' && type[c+1] == ':')
2299             {
2300                classOp = type + c - 1;
2301                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2302                {
2303                   classOp--;
2304                   classOpLen++;
2305                }
2306                break;
2307             }
2308             else if(!isspace(type[c]))
2309                break;
2310          }
2311       }
2312       if(classOp)
2313       {
2314          char temp[1024];
2315          int typeLen = strlen(type);
2316          memcpy(temp, classOp, classOpLen);
2317          temp[classOpLen] = '\0';
2318          if(temp[0])
2319             _class = eSystem_FindClass(module, temp);
2320          else
2321             _class = null;
2322          method.dataTypeString = new char[typeLen - classOpLen + 1];
2323          memcpy(method.dataTypeString, type, classOp - type);
2324          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2325       }
2326       else
2327          method.dataTypeString = type;
2328    }
2329    */
2330 }
2331
2332
2333 public void ProcessPropertyType(Property prop)
2334 {
2335    if(!prop.dataType)
2336    {
2337       Context context = SetupTemplatesContext(prop._class);
2338       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2339       FinishTemplatesContext(context);
2340    }
2341 }
2342
2343 public void DeclareMethod(Method method, char * name)
2344 {
2345    Symbol symbol = method.symbol;
2346    if(!symbol || (!symbol.pointerExternal && method.type == virtualMethod) || symbol.id > (curExternal ? curExternal.symbol.idCode : -1))
2347    {
2348       bool imported = false;
2349       bool dllImport = false;
2350
2351       if(!method.dataType)
2352          method.dataType = ProcessTypeString(method.dataTypeString, false);
2353
2354       if(!symbol || symbol._import || method.type == virtualMethod)
2355       {
2356          if(!symbol || method.type == virtualMethod)
2357          {
2358             Symbol classSym;
2359             if(!method._class.symbol)
2360                method._class.symbol = FindClass(method._class.fullName);
2361             classSym = method._class.symbol;
2362             if(!classSym._import)
2363             {
2364                ModuleImport module;
2365
2366                if(method._class.module && method._class.module.name)
2367                   module = FindModule(method._class.module);
2368                else
2369                   module = mainModule;
2370                classSym._import = ClassImport
2371                {
2372                   name = CopyString(method._class.fullName);
2373                   isRemote = method._class.isRemote;
2374                };
2375                module.classes.Add(classSym._import);
2376             }
2377             if(!symbol)
2378             {
2379                symbol = method.symbol = Symbol { };
2380             }
2381             if(!symbol._import)
2382             {
2383                symbol._import = (ClassImport)MethodImport
2384                {
2385                   name = CopyString(method.name);
2386                   isVirtual = method.type == virtualMethod;
2387                };
2388                classSym._import.methods.Add(symbol._import);
2389             }
2390             if(!symbol)
2391             {
2392                // Set the symbol type
2393                /*
2394                if(!type.thisClass)
2395                {
2396                   type.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2397                }
2398                else if(type.thisClass == (void *)-1)
2399                {
2400                   type.thisClass = null;
2401                }
2402                */
2403                // symbol.type = ProcessTypeString(method.dataTypeString, false);
2404                symbol.type = method.dataType;
2405                if(symbol.type) symbol.type.refCount++;
2406             }
2407             /*
2408             if(!method.thisClass || strcmp(method.thisClass, "void"))
2409                symbol.type.params.Insert(null,
2410                   MkClassType(method.thisClass ? method.thisClass : method._class.fullName));
2411             */
2412          }
2413          if(!method.dataType.dllExport)
2414          {
2415             imported = true;
2416             if(method._class.module != privateModule && method._class.module.importType != staticImport)
2417                dllImport = true;
2418          }
2419       }
2420
2421       /* MOVING THIS UP
2422       if(!method.dataType)
2423          method.dataType = ((Symbol)method.symbol).type;
2424          //ProcessMethodType(method);
2425       */
2426
2427       if(method.type != virtualMethod && method.dataType)
2428          DeclareType(method.dataType, true, true);
2429
2430       if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2431       {
2432          // We need a declaration here :)
2433          Declaration decl;
2434          OldList * specifiers, * declarators;
2435          Declarator d;
2436          Declarator funcDecl;
2437          External external;
2438
2439          specifiers = MkList();
2440          declarators = MkList();
2441
2442          //if(imported)
2443          if(dllImport)
2444             ListAdd(specifiers, MkSpecifier(EXTERN));
2445          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2446             ListAdd(specifiers, MkSpecifier(STATIC));
2447
2448          if(method.type == virtualMethod)
2449          {
2450             ListAdd(specifiers, MkSpecifier(INT));
2451             d = MkDeclaratorIdentifier(MkIdentifier(name));
2452          }
2453          else
2454          {
2455             d = MkDeclaratorIdentifier(MkIdentifier(name));
2456             //if(imported)
2457             if(dllImport)
2458                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2459             {
2460                Context context = SetupTemplatesContext(method._class);
2461                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2462                FinishTemplatesContext(context);
2463             }
2464             funcDecl = GetFuncDecl(d);
2465
2466             if(dllImport)
2467             {
2468                Specifier spec, next;
2469                for(spec = specifiers->first; spec; spec = next)
2470                {
2471                   next = spec.next;
2472                   if(spec.type == extendedSpecifier)
2473                   {
2474                      specifiers->Remove(spec);
2475                      FreeSpecifier(spec);
2476                   }
2477                }
2478             }
2479
2480             // Add this parameter if not a static method
2481             if(method.dataType && !method.dataType.staticMethod)
2482             {
2483                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2484                {
2485                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2486                   TypeName thisParam = MkTypeName(MkListOne(
2487                      MkSpecifierName/*MkClassName*/(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2488                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2489                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2490                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2491
2492                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2493                   {
2494                      TypeName param = funcDecl.function.parameters->first;
2495                      funcDecl.function.parameters->Remove(param);
2496                      FreeTypeName(param);
2497                   }
2498
2499                   if(!funcDecl.function.parameters)
2500                      funcDecl.function.parameters = MkList();
2501                   funcDecl.function.parameters->Insert(null, thisParam);
2502                }
2503             }
2504             // Make sure we don't have empty parameter declarations for static methods...
2505             /*
2506             else if(!funcDecl.function.parameters)
2507             {
2508                funcDecl.function.parameters = MkList();
2509                funcDecl.function.parameters->Insert(null,
2510                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2511             }*/
2512          }
2513          // TESTING THIS:
2514          ProcessDeclarator(d);
2515
2516          ListAdd(declarators, MkInitDeclarator(d, null));
2517
2518          decl = MkDeclaration(specifiers, declarators);
2519
2520          ReplaceThisClassSpecifiers(specifiers, method._class);
2521
2522          // Keep a different symbol for the function definition than the declaration...
2523          if(symbol.pointerExternal)
2524          {
2525             Symbol functionSymbol { };
2526
2527             // Copy symbol
2528             {
2529                *functionSymbol = *symbol;
2530                functionSymbol.string = CopyString(symbol.string);
2531                if(functionSymbol.type)
2532                   functionSymbol.type.refCount++;
2533             }
2534
2535             excludedSymbols->Add(functionSymbol);
2536             symbol.pointerExternal.symbol = functionSymbol;
2537          }
2538          external = MkExternalDeclaration(decl);
2539          if(curExternal)
2540             ast->Insert(curExternal ? curExternal.prev : null, external);
2541          external.symbol = symbol;
2542          symbol.pointerExternal = external;
2543       }
2544       else if(ast)
2545       {
2546          // Move declaration higher...
2547          ast->Move(symbol.pointerExternal, curExternal.prev);
2548       }
2549
2550       symbol.id = curExternal ? curExternal.symbol.idCode : MAXINT;
2551    }
2552 }
2553
2554 char * ReplaceThisClass(Class _class)
2555 {
2556    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2557    {
2558       bool first = true;
2559       int p = 0;
2560       ClassTemplateParameter param;
2561       int lastParam = -1;
2562
2563       char className[1024];
2564       strcpy(className, _class.fullName);
2565       for(param = _class.templateParams.first; param; param = param.next)
2566       {
2567          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2568          {
2569             if(first) strcat(className, "<");
2570             if(!first) strcat(className, ", ");
2571             if(lastParam + 1 != p)
2572             {
2573                strcat(className, param.name);
2574                strcat(className, " = ");
2575             }
2576             strcat(className, param.name);
2577             first = false;
2578             lastParam = p;
2579          }
2580          p++;
2581       }
2582       if(!first)
2583       {
2584          int len = strlen(className);
2585          if(className[len-1] == '>') className[len++] = ' ';
2586          className[len++] = '>';
2587          className[len++] = '\0';
2588       }
2589       return CopyString(className);
2590    }
2591    else
2592       return CopyString(_class.fullName);
2593 }
2594
2595 Type ReplaceThisClassType(Class _class)
2596 {
2597    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2598    {
2599       bool first = true;
2600       int p = 0;
2601       ClassTemplateParameter param;
2602       int lastParam = -1;
2603       char className[1024];
2604       strcpy(className, _class.fullName);
2605
2606       for(param = _class.templateParams.first; param; param = param.next)
2607       {
2608          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2609          {
2610             if(first) strcat(className, "<");
2611             if(!first) strcat(className, ", ");
2612             if(lastParam + 1 != p)
2613             {
2614                strcat(className, param.name);
2615                strcat(className, " = ");
2616             }
2617             strcat(className, param.name);
2618             first = false;
2619             lastParam = p;
2620          }
2621          p++;
2622       }
2623       if(!first)
2624       {
2625          int len = strlen(className);
2626          if(className[len-1] == '>') className[len++] = ' ';
2627          className[len++] = '>';
2628          className[len++] = '\0';
2629       }
2630       return MkClassType(className);
2631       //return ProcessTypeString(className, false);
2632    }
2633    else
2634    {
2635       return MkClassType(_class.fullName);
2636       //return ProcessTypeString(_class.fullName, false);
2637    }
2638 }
2639
2640 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2641 {
2642    if(specs != null && _class)
2643    {
2644       Specifier spec;
2645       for(spec = specs.first; spec; spec = spec.next)
2646       {
2647          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2648          {
2649             spec.type = nameSpecifier;
2650             spec.name = ReplaceThisClass(_class);
2651             spec.symbol = FindClass(spec.name); //_class.symbol;
2652          }
2653       }
2654    }
2655 }
2656
2657 // Returns imported or not
2658 bool DeclareFunction(GlobalFunction function, char * name)
2659 {
2660    Symbol symbol = function.symbol;
2661    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2662    {
2663       bool imported = false;
2664       bool dllImport = false;
2665
2666       if(!function.dataType)
2667       {
2668          function.dataType = ProcessTypeString(function.dataTypeString, false);
2669          if(!function.dataType.thisClass)
2670             function.dataType.staticMethod = true;
2671       }
2672
2673       if(inCompiler)
2674       {
2675          if(!symbol)
2676          {
2677             ModuleImport module = FindModule(function.module);
2678             // WARNING: This is not added anywhere...
2679             symbol = function.symbol = Symbol {  };
2680
2681             if(module.name)
2682             {
2683                if(!function.dataType.dllExport)
2684                {
2685                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2686                   module.functions.Add(symbol._import);
2687                }
2688             }
2689             // Set the symbol type
2690             {
2691                symbol.type = ProcessTypeString(function.dataTypeString, false);
2692                if(!symbol.type.thisClass)
2693                   symbol.type.staticMethod = true;
2694             }
2695          }
2696          imported = symbol._import ? true : false;
2697          if(imported && function.module != privateModule && function.module.importType != staticImport)
2698             dllImport = true;
2699       }
2700
2701       DeclareType(function.dataType, true, true);
2702
2703       if(inCompiler)
2704       {
2705          if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2706          {
2707             // We need a declaration here :)
2708             Declaration decl;
2709             OldList * specifiers, * declarators;
2710             Declarator d;
2711             Declarator funcDecl;
2712             External external;
2713
2714             specifiers = MkList();
2715             declarators = MkList();
2716
2717             //if(imported)
2718                ListAdd(specifiers, MkSpecifier(EXTERN));
2719             /*
2720             else
2721                ListAdd(specifiers, MkSpecifier(STATIC));
2722             */
2723
2724             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2725             //if(imported)
2726             if(dllImport)
2727                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2728
2729             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2730             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2731             if(function.module.importType == staticImport)
2732             {
2733                Specifier spec;
2734                for(spec = specifiers->first; spec; spec = spec.next)
2735                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2736                   {
2737                      specifiers->Remove(spec);
2738                      FreeSpecifier(spec);
2739                      break;
2740                   }
2741             }
2742
2743             funcDecl = GetFuncDecl(d);
2744
2745             // Make sure we don't have empty parameter declarations for static methods...
2746             if(funcDecl && !funcDecl.function.parameters)
2747             {
2748                funcDecl.function.parameters = MkList();
2749                funcDecl.function.parameters->Insert(null,
2750                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2751             }
2752
2753             ListAdd(declarators, MkInitDeclarator(d, null));
2754
2755             {
2756                Context oldCtx = curContext;
2757                curContext = globalContext;
2758                decl = MkDeclaration(specifiers, declarators);
2759                curContext = oldCtx;
2760             }
2761
2762             // Keep a different symbol for the function definition than the declaration...
2763             if(symbol.pointerExternal)
2764             {
2765                Symbol functionSymbol { };
2766                // Copy symbol
2767                {
2768                   *functionSymbol = *symbol;
2769                   functionSymbol.string = CopyString(symbol.string);
2770                   if(functionSymbol.type)
2771                      functionSymbol.type.refCount++;
2772                }
2773
2774                excludedSymbols->Add(functionSymbol);
2775
2776                symbol.pointerExternal.symbol = functionSymbol;
2777             }
2778             external = MkExternalDeclaration(decl);
2779             if(curExternal)
2780                ast->Insert(curExternal.prev, external);
2781             external.symbol = symbol;
2782             symbol.pointerExternal = external;
2783          }
2784          else
2785          {
2786             // Move declaration higher...
2787             ast->Move(symbol.pointerExternal, curExternal.prev);
2788          }
2789
2790          if(curExternal)
2791             symbol.id = curExternal.symbol.idCode;
2792       }
2793    }
2794    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2795 }
2796
2797 void DeclareGlobalData(GlobalData data)
2798 {
2799    Symbol symbol = data.symbol;
2800    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2801    {
2802       if(inCompiler)
2803       {
2804          if(!symbol)
2805             symbol = data.symbol = Symbol { };
2806       }
2807       if(!data.dataType)
2808          data.dataType = ProcessTypeString(data.dataTypeString, false);
2809       DeclareType(data.dataType, true, true);
2810       if(inCompiler)
2811       {
2812          if(!symbol.pointerExternal)
2813          {
2814             // We need a declaration here :)
2815             Declaration decl;
2816             OldList * specifiers, * declarators;
2817             Declarator d;
2818             External external;
2819
2820             specifiers = MkList();
2821             declarators = MkList();
2822
2823             ListAdd(specifiers, MkSpecifier(EXTERN));
2824             d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2825             d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2826
2827             ListAdd(declarators, MkInitDeclarator(d, null));
2828
2829             decl = MkDeclaration(specifiers, declarators);
2830             external = MkExternalDeclaration(decl);
2831             if(curExternal)
2832                ast->Insert(curExternal.prev, external);
2833             external.symbol = symbol;
2834             symbol.pointerExternal = external;
2835          }
2836          else
2837          {
2838             // Move declaration higher...
2839             ast->Move(symbol.pointerExternal, curExternal.prev);
2840          }
2841
2842          if(curExternal)
2843             symbol.id = curExternal.symbol.idCode;
2844       }
2845    }
2846 }
2847
2848 class Conversion : struct
2849 {
2850    Conversion prev, next;
2851    Property convert;
2852    bool isGet;
2853    Type resultType;
2854 };
2855
2856 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams, bool isConversionExploration)
2857 {
2858    if(source && dest)
2859    {
2860       // Property convert;
2861
2862       if(source.kind == templateType && dest.kind != templateType)
2863       {
2864          Type type = ProcessTemplateParameterType(source.templateParameter);
2865          if(type) source = type;
2866       }
2867
2868       if(dest.kind == templateType && source.kind != templateType)
2869       {
2870          Type type = ProcessTemplateParameterType(dest.templateParameter);
2871          if(type) dest = type;
2872       }
2873
2874       if(dest.classObjectType == typedObject)
2875       {
2876          if(source.classObjectType != anyObject)
2877             return true;
2878          else
2879          {
2880             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
2881             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
2882             {
2883                return true;
2884             }
2885          }
2886       }
2887       else
2888       {
2889          if(source.classObjectType == anyObject)
2890             return true;
2891          if(dest.classObjectType == anyObject && source.classObjectType != typedObject)
2892             return true;
2893       }
2894
2895       if((dest.kind == structType && source.kind == structType) ||
2896          (dest.kind == unionType && source.kind == unionType))
2897       {
2898          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
2899              (source.members.first && source.members.first == dest.members.first))
2900             return true;
2901       }
2902
2903       if(dest.kind == ellipsisType && source.kind != voidType)
2904          return true;
2905
2906       if(dest.kind == pointerType && dest.type.kind == voidType &&
2907          ((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))
2908          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
2909
2910          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
2911
2912          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
2913          return true;
2914       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
2915          ((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))
2916          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
2917
2918          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
2919
2920          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
2921          return true;
2922
2923       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
2924       {
2925          if(source._class.registered && source._class.registered.type == unitClass)
2926          {
2927             if(conversions != null)
2928             {
2929                if(source._class.registered == dest._class.registered)
2930                   return true;
2931             }
2932             else
2933             {
2934                Class sourceBase, destBase;
2935                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
2936                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
2937                if(sourceBase == destBase)
2938                   return true;
2939             }
2940          }
2941          // Don't match enum inheriting from other enum if resolving enumeration values
2942          // TESTING: !dest.classObjectType
2943          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
2944             (enumBaseType ||
2945                (!source._class.registered || source._class.registered.type != enumClass) ||
2946                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
2947             return true;
2948          else
2949          {
2950             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
2951             if(enumBaseType &&
2952                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
2953                ((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)
2954             {
2955                if(eClass_IsDerived(dest._class.registered, source._class.registered))
2956                {
2957                   return true;
2958                }
2959             }
2960          }
2961       }
2962
2963       // JUST ADDED THIS...
2964       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
2965          return true;
2966
2967       if(doConversion)
2968       {
2969          // Just added this for Straight conversion of ColorAlpha => Color
2970          if(source.kind == classType)
2971          {
2972             Class _class;
2973             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
2974             {
2975                Property convert;
2976                for(convert = _class.conversions.first; convert; convert = convert.next)
2977                {
2978                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
2979                   {
2980                      Conversion after = (conversions != null) ? conversions.last : null;
2981
2982                      if(!convert.dataType)
2983                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
2984                      if(MatchTypes(convert.dataType, dest, conversions, null, null, false, true, false, true))
2985                      {
2986                         if(!conversions && !convert.Get)
2987                            return true;
2988                         else if(conversions != null)
2989                         {
2990                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
2991                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
2992                               (dest.kind != classType || dest._class.registered != _class.base))
2993                               return true;
2994                            else
2995                            {
2996                               Conversion conv { convert = convert, isGet = true };
2997                               // conversions.Add(conv);
2998                               conversions.Insert(after, conv);
2999                               return true;
3000                            }
3001                         }
3002                      }
3003                   }
3004                }
3005             }
3006          }
3007
3008          // MOVING THIS??
3009
3010          if(dest.kind == classType)
3011          {
3012             Class _class;
3013             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3014             {
3015                Property convert;
3016                for(convert = _class.conversions.first; convert; convert = convert.next)
3017                {
3018                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3019                   {
3020                      // Conversion after = (conversions != null) ? conversions.last : null;
3021
3022                      if(!convert.dataType)
3023                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3024                      // Just added this equality check to prevent recursion.... Make it safer?
3025                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3026                      if(convert.dataType != dest && MatchTypes(source, convert.dataType, conversions, null, null, true, false /*true*/, false, true))
3027                      {
3028                         if(!conversions && !convert.Set)
3029                            return true;
3030                         else if(conversions != null)
3031                         {
3032                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3033                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3034                               (source.kind != classType || source._class.registered != _class.base))
3035                               return true;
3036                            else
3037                            {
3038                               // *** Testing this! ***
3039                               Conversion conv { convert = convert };
3040                               conversions.Add(conv);
3041                               //conversions.Insert(after, conv);
3042                               return true;
3043                            }
3044                         }
3045                      }
3046                   }
3047                }
3048             }
3049             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3050             {
3051                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3052                   (source.kind != classType || source._class.registered.type != structClass))
3053                   return true;
3054             }*/
3055
3056             // TESTING THIS... IS THIS OK??
3057             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3058             {
3059                if(!dest._class.registered.dataType)
3060                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3061                // Only support this for classes...
3062                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3063                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3064                {
3065                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false))
3066                   {
3067                      return true;
3068                   }
3069                }
3070             }
3071          }
3072
3073          // Moved this lower
3074          if(source.kind == classType)
3075          {
3076             Class _class;
3077             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3078             {
3079                Property convert;
3080                for(convert = _class.conversions.first; convert; convert = convert.next)
3081                {
3082                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3083                   {
3084                      Conversion after = (conversions != null) ? conversions.last : null;
3085
3086                      if(!convert.dataType)
3087                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3088                      if(convert.dataType != source && MatchTypes(convert.dataType, dest, conversions, null, null, true, true, false, true))
3089                      {
3090                         if(!conversions && !convert.Get)
3091                            return true;
3092                         else if(conversions != null)
3093                         {
3094                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3095                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3096                               (dest.kind != classType || dest._class.registered != _class.base))
3097                               return true;
3098                            else
3099                            {
3100                               Conversion conv { convert = convert, isGet = true };
3101
3102                               // conversions.Add(conv);
3103                               conversions.Insert(after, conv);
3104                               return true;
3105                            }
3106                         }
3107                      }
3108                   }
3109                }
3110             }
3111
3112             // TESTING THIS... IS THIS OK??
3113             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3114             {
3115                if(!source._class.registered.dataType)
3116                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3117                if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, true, false, false))
3118                {
3119                   return true;
3120                }
3121             }
3122          }
3123       }
3124
3125       if(source.kind == classType || source.kind == subClassType)
3126          ;
3127       else if(dest.kind == source.kind &&
3128          (dest.kind != structType && dest.kind != unionType &&
3129           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3130           return true;
3131       // RECENTLY ADDED THESE
3132       else if(dest.kind == doubleType && source.kind == floatType)
3133          return true;
3134       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3135          return true;
3136       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3137          return true;
3138       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3139          return true;
3140       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3141          return true;
3142       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3143          return true;
3144       else if(source.kind == enumType &&
3145          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3146           return true;
3147       else if(dest.kind == enumType &&
3148          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3149           return true;
3150       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3151               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3152       {
3153          Type paramSource, paramDest;
3154
3155          if(dest.kind == methodType)
3156             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3157          if(source.kind == methodType)
3158             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3159
3160          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3161          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3162          if(dest.kind == methodType)
3163             dest = dest.method.dataType;
3164          if(source.kind == methodType)
3165             source = source.method.dataType;
3166
3167          paramSource = source.params.first;
3168          if(paramSource && paramSource.kind == voidType) paramSource = null;
3169          paramDest = dest.params.first;
3170          if(paramDest && paramDest.kind == voidType) paramDest = null;
3171
3172
3173          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3174             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3175          {
3176             // Source thisClass must be derived from destination thisClass
3177             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3178                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3179             {
3180                if(paramDest && paramDest.kind == classType)
3181                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3182                else
3183                   Compiler_Error($"method class should not take an object\n");
3184                return false;
3185             }
3186             paramDest = paramDest.next;
3187          }
3188          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3189          {
3190             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3191             {
3192                if(dest.thisClass)
3193                {
3194                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3195                   {
3196                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3197                      return false;
3198                   }
3199                }
3200                else
3201                {
3202                   // THIS WAS BACKWARDS:
3203                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3204                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3205                   {
3206                      if(owningClassDest)
3207                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3208                      else
3209                         Compiler_Error($"overriding class expected to be derived from method class\n");
3210                      return false;
3211                   }
3212                }
3213                paramSource = paramSource.next;
3214             }
3215             else
3216             {
3217                if(dest.thisClass)
3218                {
3219                   // Source thisClass must be derived from destination thisClass
3220                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3221                   {
3222                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3223                      return false;
3224                   }
3225                }
3226                else
3227                {
3228                   // THIS WAS BACKWARDS TOO??
3229                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3230                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3231                   {
3232                      //if(owningClass)
3233                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3234                      //else
3235                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3236                      return false;
3237                   }
3238                }
3239             }
3240          }
3241
3242
3243          // Source return type must be derived from destination return type
3244          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false))
3245          {
3246             Compiler_Warning($"incompatible return type for function\n");
3247             return false;
3248          }
3249
3250          // Check parameters
3251
3252          for(; paramDest; paramDest = paramDest.next)
3253          {
3254             if(!paramSource)
3255             {
3256                //Compiler_Warning($"not enough parameters\n");
3257                Compiler_Error($"not enough parameters\n");
3258                return false;
3259             }
3260             {
3261                Type paramDestType = paramDest;
3262                Type paramSourceType = paramSource;
3263                Type type = paramDestType;
3264
3265                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3266                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3267                   paramSource.kind != templateType)
3268                {
3269                   int id = 0;
3270                   ClassTemplateParameter curParam = null;
3271                   Class sClass;
3272                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3273                   {
3274                      id = 0;
3275                      if(sClass.templateClass) sClass = sClass.templateClass;
3276                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3277                      {
3278                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3279                         {
3280                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3281                            {
3282                               if(sClass.templateClass) sClass = sClass.templateClass;
3283                               id += sClass.templateParams.count;
3284                            }
3285                            break;
3286                         }
3287                         id++;
3288                      }
3289                      if(curParam) break;
3290                   }
3291
3292                   if(curParam)
3293                   {
3294                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3295                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3296                   }
3297                }
3298
3299                // paramDest must be derived from paramSource
3300                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false) &&
3301                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false)))
3302                {
3303                   char type[1024];
3304                   type[0] = 0;
3305                   PrintType(paramDest, type, false, true);
3306                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3307
3308                   if(paramDestType != paramDest)
3309                      FreeType(paramDestType);
3310                   return false;
3311                }
3312                if(paramDestType != paramDest)
3313                   FreeType(paramDestType);
3314             }
3315
3316             paramSource = paramSource.next;
3317          }
3318          if(paramSource)
3319          {
3320             Compiler_Error($"too many parameters\n");
3321             return false;
3322          }
3323          return true;
3324       }
3325       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3326       {
3327          return true;
3328       }
3329       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3330          (source.kind == arrayType || source.kind == pointerType))
3331       {
3332          if(MatchTypes(source.type, dest.type, null, null, null, true, true, false, false))
3333             return true;
3334       }
3335    }
3336    return false;
3337 }
3338
3339 static void FreeConvert(Conversion convert)
3340 {
3341    if(convert.resultType)
3342       FreeType(convert.resultType);
3343 }
3344
3345 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3346                               char * string, OldList conversions)
3347 {
3348    BTNamedLink link;
3349
3350    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3351    {
3352       Class _class = link.data;
3353       if(_class.type == enumClass)
3354       {
3355          OldList converts { };
3356          Type type { };
3357          type.kind = classType;
3358
3359          if(!_class.symbol)
3360             _class.symbol = FindClass(_class.fullName);
3361          type._class = _class.symbol;
3362
3363          if(MatchTypes(type, dest, &converts, null, null, true, false, false, false))
3364          {
3365             NamedLink value;
3366             Class enumClass = eSystem_FindClass(privateModule, "enum");
3367             if(enumClass)
3368             {
3369                Class baseClass;
3370                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3371                {
3372                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3373                   for(value = e.values.first; value; value = value.next)
3374                   {
3375                      if(!strcmp(value.name, string))
3376                         break;
3377                   }
3378                   if(value)
3379                   {
3380                      FreeExpContents(sourceExp);
3381                      FreeType(sourceExp.expType);
3382
3383                      sourceExp.isConstant = true;
3384                      sourceExp.expType = MkClassType(baseClass.fullName);
3385                      //if(inCompiler)
3386                      {
3387                         char constant[256];
3388                         sourceExp.type = constantExp;
3389                         if(!strcmp(baseClass.dataTypeString, "int"))
3390                            sprintf(constant, "%d",(int)value.data);
3391                         else
3392                            sprintf(constant, "0x%X",(int)value.data);
3393                         sourceExp.constant = CopyString(constant);
3394                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3395                      }
3396
3397                      while(converts.first)
3398                      {
3399                         Conversion convert = converts.first;
3400                         converts.Remove(convert);
3401                         conversions.Add(convert);
3402                      }
3403                      delete type;
3404                      return true;
3405                   }
3406                }
3407             }
3408          }
3409          if(converts.first)
3410             converts.Free(FreeConvert);
3411          delete type;
3412       }
3413    }
3414    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3415       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3416          return true;
3417    return false;
3418 }
3419
3420 public bool ModuleVisibility(Module searchIn, Module searchFor)
3421 {
3422    SubModule subModule;
3423
3424    if(searchFor == searchIn)
3425       return true;
3426
3427    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3428    {
3429       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3430       {
3431          if(ModuleVisibility(subModule.module, searchFor))
3432             return true;
3433       }
3434    }
3435    return false;
3436 }
3437
3438 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3439 {
3440    Module module;
3441
3442    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3443       return true;
3444    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3445       return true;
3446    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3447       return true;
3448
3449    for(module = mainModule.application.allModules.first; module; module = module.next)
3450    {
3451       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3452          return true;
3453    }
3454    return false;
3455 }
3456
3457 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla)
3458 {
3459    Type source = sourceExp.expType;
3460    Type realDest = dest;
3461    Type backupSourceExpType = null;
3462
3463    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3464       return true;
3465
3466    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3467    {
3468        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3469        {
3470           Class sourceBase, destBase;
3471           for(sourceBase = source._class.registered;
3472               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3473               sourceBase = sourceBase.base);
3474           for(destBase = dest._class.registered;
3475               destBase && destBase.base && destBase.base.type != systemClass;
3476               destBase = destBase.base);
3477           //if(source._class.registered == dest._class.registered)
3478           if(sourceBase == destBase)
3479              return true;
3480        }
3481    }
3482
3483    if(source)
3484    {
3485       OldList * specs;
3486       bool flag = false;
3487       int64 value = MAXINT;
3488
3489       source.refCount++;
3490       dest.refCount++;
3491
3492       if(sourceExp.type == constantExp)
3493       {
3494          if(source.isSigned)
3495             value = strtoll(sourceExp.constant, null, 0);
3496          else
3497             value = strtoull(sourceExp.constant, null, 0);
3498       }
3499       else if(sourceExp.type == opExp && sourceExp.op.op == '-' && !sourceExp.op.exp1 && sourceExp.op.exp2 && sourceExp.op.exp2.type == constantExp)
3500       {
3501          if(source.isSigned)
3502             value = -strtoll(sourceExp.op.exp2.constant, null, 0);
3503          else
3504             value = -strtoull(sourceExp.op.exp2.constant, null, 0);
3505       }
3506
3507       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3508          !strcmp(source._class.registered.fullName, "ecere::com::unichar"))
3509       {
3510          FreeType(source);
3511          source = Type { kind = intType, isSigned = false, refCount = 1 };
3512       }
3513
3514       if(dest.kind == classType)
3515       {
3516          Class _class = dest._class ? dest._class.registered : null;
3517
3518          if(_class && _class.type == unitClass)
3519          {
3520             if(source.kind != classType)
3521             {
3522                Type tempType { };
3523                Type tempDest, tempSource;
3524
3525                for(; _class.base.type != systemClass; _class = _class.base);
3526                tempSource = dest;
3527                tempDest = tempType;
3528
3529                tempType.kind = classType;
3530                if(!_class.symbol)
3531                   _class.symbol = FindClass(_class.fullName);
3532
3533                tempType._class = _class.symbol;
3534                tempType.truth = dest.truth;
3535                if(tempType._class)
3536                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false);
3537
3538                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3539                backupSourceExpType = sourceExp.expType;
3540                sourceExp.expType = dest; dest.refCount++;
3541                //sourceExp.expType = MkClassType(_class.fullName);
3542                flag = true;
3543
3544                delete tempType;
3545             }
3546          }
3547
3548
3549          // Why wasn't there something like this?
3550          if(_class && _class.type == bitClass && source.kind != classType)
3551          {
3552             if(!dest._class.registered.dataType)
3553                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3554             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false))
3555             {
3556                FreeType(source);
3557                FreeType(sourceExp.expType);
3558                source = sourceExp.expType = MkClassType(dest._class.string);
3559                source.refCount++;
3560
3561                //source.kind = classType;
3562                //source._class = dest._class;
3563             }
3564          }
3565
3566          // Adding two enumerations
3567          /*
3568          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3569          {
3570             if(!source._class.registered.dataType)
3571                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3572             if(!dest._class.registered.dataType)
3573                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3574
3575             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3576             {
3577                FreeType(source);
3578                source = sourceExp.expType = MkClassType(dest._class.string);
3579                source.refCount++;
3580
3581                //source.kind = classType;
3582                //source._class = dest._class;
3583             }
3584          }*/
3585
3586          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3587          {
3588             OldList * specs = MkList();
3589             Declarator decl;
3590             char string[1024];
3591
3592             ReadString(string, sourceExp.string);
3593             decl = SpecDeclFromString(string, specs, null);
3594
3595             FreeExpContents(sourceExp);
3596             FreeType(sourceExp.expType);
3597
3598             sourceExp.type = classExp;
3599             sourceExp._classExp.specifiers = specs;
3600             sourceExp._classExp.decl = decl;
3601             sourceExp.expType = dest;
3602             dest.refCount++;
3603
3604             FreeType(source);
3605             FreeType(dest);
3606             if(backupSourceExpType) FreeType(backupSourceExpType);
3607             return true;
3608          }
3609       }
3610       else if(source.kind == classType)
3611       {
3612          Class _class = source._class ? source._class.registered : null;
3613
3614          if(_class && (_class.type == unitClass || !strcmp(_class.fullName, "bool") || /*_class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3615          {
3616             /*
3617             if(dest.kind != classType)
3618             {
3619                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3620                if(!source._class.registered.dataType)
3621                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3622
3623                FreeType(dest);
3624                dest = MkClassType(source._class.string);
3625                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3626                //   dest = MkClassType(source._class.string);
3627             }
3628             */
3629
3630             if(dest.kind != classType)
3631             {
3632                Type tempType { };
3633                Type tempDest, tempSource;
3634
3635                if(!source._class.registered.dataType)
3636                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3637
3638                for(; _class.base.type != systemClass; _class = _class.base);
3639                tempDest = source;
3640                tempSource = tempType;
3641                tempType.kind = classType;
3642                tempType._class = FindClass(_class.fullName);
3643                tempType.truth = source.truth;
3644                tempType.classObjectType = source.classObjectType;
3645
3646                if(tempType._class)
3647                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false);
3648
3649                // PUT THIS BACK TESTING UNITS?
3650                if(conversions.last)
3651                {
3652                   ((Conversion)(conversions.last)).resultType = dest;
3653                   dest.refCount++;
3654                }
3655
3656                FreeType(sourceExp.expType);
3657                sourceExp.expType = MkClassType(_class.fullName);
3658                sourceExp.expType.truth = source.truth;
3659                sourceExp.expType.classObjectType = source.classObjectType;
3660
3661                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3662
3663                if(!sourceExp.destType)
3664                {
3665                   FreeType(sourceExp.destType);
3666                   sourceExp.destType = sourceExp.expType;
3667                   if(sourceExp.expType)
3668                      sourceExp.expType.refCount++;
3669                }
3670                //flag = true;
3671                //source = _class.dataType;
3672
3673
3674                // TOCHECK: TESTING THIS NEW CODE
3675                if(!_class.dataType)
3676                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3677                FreeType(dest);
3678                dest = MkClassType(source._class.string);
3679                dest.truth = source.truth;
3680                dest.classObjectType = source.classObjectType;
3681
3682                FreeType(source);
3683                source = _class.dataType;
3684                source.refCount++;
3685
3686                delete tempType;
3687             }
3688          }
3689       }
3690
3691       if(!flag)
3692       {
3693          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false))
3694          {
3695             FreeType(source);
3696             FreeType(dest);
3697             return true;
3698          }
3699       }
3700
3701       // Implicit Casts
3702       /*
3703       if(source.kind == classType)
3704       {
3705          Class _class = source._class.registered;
3706          if(_class.type == unitClass)
3707          {
3708             if(!_class.dataType)
3709                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3710             source = _class.dataType;
3711          }
3712       }*/
3713
3714       if(dest.kind == classType)
3715       {
3716          Class _class = dest._class ? dest._class.registered : null;
3717          if(_class && !dest.truth && (_class.type == unitClass || !strcmp(_class.fullName, "bool") ||
3718             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3719          {
3720             if(_class.type == normalClass || _class.type == noHeadClass)
3721             {
3722                Expression newExp { };
3723                *newExp = *sourceExp;
3724                if(sourceExp.destType) sourceExp.destType.refCount++;
3725                if(sourceExp.expType)  sourceExp.expType.refCount++;
3726                sourceExp.type = castExp;
3727                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3728                sourceExp.cast.exp = newExp;
3729                FreeType(sourceExp.expType);
3730                sourceExp.expType = null;
3731                ProcessExpressionType(sourceExp);
3732
3733                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3734                if(!inCompiler)
3735                {
3736                   FreeType(sourceExp.expType);
3737                   sourceExp.expType = dest;
3738                }
3739
3740                FreeType(source);
3741                if(inCompiler) FreeType(dest);
3742
3743                if(backupSourceExpType) FreeType(backupSourceExpType);
3744                return true;
3745             }
3746
3747             if(!_class.dataType)
3748                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3749             FreeType(dest);
3750             dest = _class.dataType;
3751             dest.refCount++;
3752          }
3753
3754          // Accept lower precision types for units, since we want to keep the unit type
3755          if(dest.kind == doubleType &&
3756             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3757              source.kind == charType || source.kind == _BoolType))
3758          {
3759             specs = MkListOne(MkSpecifier(DOUBLE));
3760          }
3761          else if(dest.kind == floatType &&
3762             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3763             source.kind == _BoolType || source.kind == doubleType))
3764          {
3765             specs = MkListOne(MkSpecifier(FLOAT));
3766          }
3767          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3768             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3769          {
3770             specs = MkList();
3771             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3772             ListAdd(specs, MkSpecifier(INT64));
3773          }
3774          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
3775             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3776          {
3777             specs = MkList();
3778             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3779             ListAdd(specs, MkSpecifier(INT));
3780          }
3781          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
3782             source.kind == floatType || source.kind == doubleType))
3783          {
3784             specs = MkList();
3785             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3786             ListAdd(specs, MkSpecifier(SHORT));
3787          }
3788          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
3789             source.kind == floatType || source.kind == doubleType))
3790          {
3791             specs = MkList();
3792             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3793             ListAdd(specs, MkSpecifier(CHAR));
3794          }
3795          else
3796          {
3797             FreeType(source);
3798             FreeType(dest);
3799             if(backupSourceExpType)
3800             {
3801                // Failed to convert: revert previous exp type
3802                if(sourceExp.expType) FreeType(sourceExp.expType);
3803                sourceExp.expType = backupSourceExpType;
3804             }
3805             return false;
3806          }
3807       }
3808       else if(dest.kind == doubleType &&
3809          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
3810           source.kind == _BoolType || source.kind == charType))
3811       {
3812          specs = MkListOne(MkSpecifier(DOUBLE));
3813       }
3814       else if(dest.kind == floatType &&
3815          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3816       {
3817          specs = MkListOne(MkSpecifier(FLOAT));
3818       }
3819       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3820          (value == 1 || value == 0))
3821       {
3822          specs = MkList();
3823          ListAdd(specs, MkSpecifier(BOOL));
3824       }
3825       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3826          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
3827       {
3828          specs = MkList();
3829          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3830          ListAdd(specs, MkSpecifier(CHAR));
3831       }
3832       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
3833          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
3834       {
3835          specs = MkList();
3836          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3837          ListAdd(specs, MkSpecifier(SHORT));
3838       }
3839       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
3840       {
3841          specs = MkList();
3842          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3843          ListAdd(specs, MkSpecifier(INT));
3844       }
3845       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
3846       {
3847          specs = MkList();
3848          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3849          ListAdd(specs, MkSpecifier(INT64));
3850       }
3851       else if(dest.kind == enumType &&
3852          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3853       {
3854          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
3855       }
3856       else
3857       {
3858          FreeType(source);
3859          FreeType(dest);
3860          if(backupSourceExpType)
3861          {
3862             // Failed to convert: revert previous exp type
3863             if(sourceExp.expType) FreeType(sourceExp.expType);
3864             sourceExp.expType = backupSourceExpType;
3865          }
3866          return false;
3867       }
3868
3869       if(!flag)
3870       {
3871          Expression newExp { };
3872          *newExp = *sourceExp;
3873          newExp.prev = null;
3874          newExp.next = null;
3875          if(sourceExp.destType) sourceExp.destType.refCount++;
3876          if(sourceExp.expType)  sourceExp.expType.refCount++;
3877
3878          sourceExp.type = castExp;
3879          if(realDest.kind == classType)
3880          {
3881             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
3882             FreeList(specs, FreeSpecifier);
3883          }
3884          else
3885             sourceExp.cast.typeName = MkTypeName(specs, null);
3886          if(newExp.type == opExp)
3887          {
3888             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
3889          }
3890          else
3891             sourceExp.cast.exp = newExp;
3892
3893          FreeType(sourceExp.expType);
3894          sourceExp.expType = null;
3895          ProcessExpressionType(sourceExp);
3896       }
3897       else
3898          FreeList(specs, FreeSpecifier);
3899
3900       FreeType(dest);
3901       FreeType(source);
3902       if(backupSourceExpType) FreeType(backupSourceExpType);
3903
3904       return true;
3905    }
3906    else
3907    {
3908       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
3909       if(sourceExp.type == identifierExp)
3910       {
3911          Identifier id = sourceExp.identifier;
3912          if(dest.kind == classType)
3913          {
3914             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3915             {
3916                Class _class = dest._class.registered;
3917                Class enumClass = eSystem_FindClass(privateModule, "enum");
3918                if(enumClass)
3919                {
3920                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
3921                   {
3922                      NamedLink value;
3923                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
3924                      for(value = e.values.first; value; value = value.next)
3925                      {
3926                         if(!strcmp(value.name, id.string))
3927                            break;
3928                      }
3929                      if(value)
3930                      {
3931                         FreeExpContents(sourceExp);
3932                         FreeType(sourceExp.expType);
3933
3934                         sourceExp.isConstant = true;
3935                         sourceExp.expType = MkClassType(_class.fullName);
3936                         //if(inCompiler)
3937                         {
3938                            char constant[256];
3939                            sourceExp.type = constantExp;
3940                            if(/*_class && */_class.dataTypeString && !strcmp(_class.dataTypeString, "int")) // _class cannot be null here!
3941                               sprintf(constant, "%d", (int) value.data);
3942                            else
3943                               sprintf(constant, "0x%X", (int) value.data);
3944                            sourceExp.constant = CopyString(constant);
3945                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
3946                         }
3947                         return true;
3948                      }
3949                   }
3950                }
3951             }
3952          }
3953
3954          // Loop through all enum classes
3955          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
3956             return true;
3957       }
3958    }
3959    return false;
3960 }
3961
3962 #define TERTIARY(o, name, m, t, p) \
3963    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
3964    {                                                              \
3965       exp.type = constantExp;                                    \
3966       exp.string = p(op1.m ? op2.m : op3.m);                     \
3967       if(!exp.expType) \
3968          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
3969       return true;                                                \
3970    }
3971
3972 #define BINARY(o, name, m, t, p) \
3973    static bool name(Expression exp, Operand op1, Operand op2)   \
3974    {                                                              \
3975       t value2 = op2.m;                                           \
3976       exp.type = constantExp;                                    \
3977       exp.string = p(op1.m o value2);                     \
3978       if(!exp.expType) \
3979          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
3980       return true;                                                \
3981    }
3982
3983 #define BINARY_DIVIDE(o, name, m, t, p) \
3984    static bool name(Expression exp, Operand op1, Operand op2)   \
3985    {                                                              \
3986       t value2 = op2.m;                                           \
3987       exp.type = constantExp;                                    \
3988       exp.string = p(value2 ? (op1.m o value2) : 0);             \
3989       if(!exp.expType) \
3990          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
3991       return true;                                                \
3992    }
3993
3994 #define UNARY(o, name, m, t, p) \
3995    static bool name(Expression exp, Operand op1)                \
3996    {                                                              \
3997       exp.type = constantExp;                                    \
3998       exp.string = p((t)(o op1.m));                                   \
3999       if(!exp.expType) \
4000          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4001       return true;                                                \
4002    }
4003
4004 #define OPERATOR_ALL(macro, o, name) \
4005    macro(o, Int##name, i, int, PrintInt) \
4006    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4007    macro(o, Short##name, s, short, PrintShort) \
4008    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4009    macro(o, Char##name, c, char, PrintChar) \
4010    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4011    macro(o, Float##name, f, float, PrintFloat) \
4012    macro(o, Double##name, d, double, PrintDouble)
4013
4014 #define OPERATOR_INTTYPES(macro, o, name) \
4015    macro(o, Int##name, i, int, PrintInt) \
4016    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4017    macro(o, Short##name, s, short, PrintShort) \
4018    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4019    macro(o, Char##name, c, char, PrintChar) \
4020    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4021
4022
4023 // binary arithmetic
4024 OPERATOR_ALL(BINARY, +, Add)
4025 OPERATOR_ALL(BINARY, -, Sub)
4026 OPERATOR_ALL(BINARY, *, Mul)
4027 OPERATOR_ALL(BINARY_DIVIDE, /, Div)
4028 OPERATOR_INTTYPES(BINARY_DIVIDE, %, Mod)
4029
4030 // unary arithmetic
4031 OPERATOR_ALL(UNARY, -, Neg)
4032
4033 // unary arithmetic increment and decrement
4034 OPERATOR_ALL(UNARY, ++, Inc)
4035 OPERATOR_ALL(UNARY, --, Dec)
4036
4037 // binary arithmetic assignment
4038 OPERATOR_ALL(BINARY, =, Asign)
4039 OPERATOR_ALL(BINARY, +=, AddAsign)
4040 OPERATOR_ALL(BINARY, -=, SubAsign)
4041 OPERATOR_ALL(BINARY, *=, MulAsign)
4042 OPERATOR_ALL(BINARY_DIVIDE, /=, DivAsign)
4043 OPERATOR_INTTYPES(BINARY_DIVIDE, %=, ModAsign)
4044
4045 // binary bitwise
4046 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4047 OPERATOR_INTTYPES(BINARY, |, BitOr)
4048 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4049 OPERATOR_INTTYPES(BINARY, <<, LShift)
4050 OPERATOR_INTTYPES(BINARY, >>, RShift)
4051
4052 // unary bitwise
4053 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4054
4055 // binary bitwise assignment
4056 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4057 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4058 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4059 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4060 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4061
4062 // unary logical negation
4063 OPERATOR_INTTYPES(UNARY, !, Not)
4064
4065 // binary logical equality
4066 OPERATOR_ALL(BINARY, ==, Equ)
4067 OPERATOR_ALL(BINARY, !=, Nqu)
4068
4069 // binary logical
4070 OPERATOR_ALL(BINARY, &&, And)
4071 OPERATOR_ALL(BINARY, ||, Or)
4072
4073 // binary logical relational
4074 OPERATOR_ALL(BINARY, >, Grt)
4075 OPERATOR_ALL(BINARY, <, Sma)
4076 OPERATOR_ALL(BINARY, >=, GrtEqu)
4077 OPERATOR_ALL(BINARY, <=, SmaEqu)
4078
4079 // tertiary condition operator
4080 OPERATOR_ALL(TERTIARY, ?, Cond)
4081
4082 //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
4083 #define OPERATOR_TABLE_ALL(name, type) \
4084     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4085                           type##Neg, \
4086                           type##Inc, type##Dec, \
4087                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4088                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4089                           type##BitNot, \
4090                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4091                           type##Not, \
4092                           type##Equ, type##Nqu, \
4093                           type##And, type##Or, \
4094                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4095                         }; \
4096
4097 #define OPERATOR_TABLE_INTTYPES(name, type) \
4098     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4099                           type##Neg, \
4100                           type##Inc, type##Dec, \
4101                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4102                           null, null, null, null, null, \
4103                           null, \
4104                           null, null, null, null, null, \
4105                           null, \
4106                           type##Equ, type##Nqu, \
4107                           type##And, type##Or, \
4108                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4109                         }; \
4110
4111 OPERATOR_TABLE_ALL(int, Int)
4112 OPERATOR_TABLE_ALL(uint, UInt)
4113 OPERATOR_TABLE_ALL(short, Short)
4114 OPERATOR_TABLE_ALL(ushort, UShort)
4115 OPERATOR_TABLE_INTTYPES(float, Float)
4116 OPERATOR_TABLE_INTTYPES(double, Double)
4117 OPERATOR_TABLE_ALL(char, Char)
4118 OPERATOR_TABLE_ALL(uchar, UChar)
4119
4120 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4121 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4122 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4123 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4124 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4125 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4126 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4127 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4128
4129 public void ReadString(char * output,  char * string)
4130 {
4131    int len = strlen(string);
4132    int c,d = 0;
4133    bool quoted = false, escaped = false;
4134    for(c = 0; c<len; c++)
4135    {
4136       char ch = string[c];
4137       if(escaped)
4138       {
4139          switch(ch)
4140          {
4141             case 'n': output[d] = '\n'; break;
4142             case 't': output[d] = '\t'; break;
4143             case 'a': output[d] = '\a'; break;
4144             case 'b': output[d] = '\b'; break;
4145             case 'f': output[d] = '\f'; break;
4146             case 'r': output[d] = '\r'; break;
4147             case 'v': output[d] = '\v'; break;
4148             case '\\': output[d] = '\\'; break;
4149             case '\"': output[d] = '\"'; break;
4150             default: output[d++] = '\\'; output[d] = ch;
4151             //default: output[d] = ch;
4152          }
4153          d++;
4154          escaped = false;
4155       }
4156       else
4157       {
4158          if(ch == '\"')
4159             quoted ^= true;
4160          else if(quoted)
4161          {
4162             if(ch == '\\')
4163                escaped = true;
4164             else
4165                output[d++] = ch;
4166          }
4167       }
4168    }
4169    output[d] = '\0';
4170 }
4171
4172 public Operand GetOperand(Expression exp)
4173 {
4174    Operand op { };
4175    Type type = exp.expType;
4176    if(type)
4177    {
4178       while(type.kind == classType &&
4179          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4180       {
4181          if(!type._class.registered.dataType)
4182             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4183          type = type._class.registered.dataType;
4184
4185       }
4186       op.kind = type.kind;
4187       op.type = exp.expType;
4188       if(exp.isConstant && exp.type == constantExp)
4189       {
4190          switch(op.kind)
4191          {
4192             case _BoolType:
4193             case charType:
4194             {
4195                if(exp.constant[0] == '\'')
4196                   op.c = exp.constant[1];
4197                else if(type.isSigned)
4198                {
4199                   op.c = (char)strtol(exp.constant, null, 0);
4200                   op.ops = charOps;
4201                }
4202                else
4203                {
4204                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4205                   op.ops = ucharOps;
4206                }
4207                break;
4208             }
4209             case shortType:
4210                if(type.isSigned)
4211                {
4212                   op.s = (short)strtol(exp.constant, null, 0);
4213                   op.ops = shortOps;
4214                }
4215                else
4216                {
4217                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4218                   op.ops = ushortOps;
4219                }
4220                break;
4221             case intType:
4222             case longType:
4223                if(type.isSigned)
4224                {
4225                   op.i = (int)strtol(exp.constant, null, 0);
4226                   op.ops = intOps;
4227                }
4228                else
4229                {
4230                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4231                   op.ops = uintOps;
4232                }
4233                op.kind = intType;
4234                break;
4235             case int64Type:
4236                if(type.isSigned)
4237                {
4238                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4239                   op.ops = intOps;
4240                }
4241                else
4242                {
4243                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4244                   op.ops = uintOps;
4245                }
4246                op.kind = intType;
4247                break;
4248             case intPtrType:
4249                if(type.isSigned)
4250                {
4251                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4252                   op.ops = intOps;
4253                }
4254                else
4255                {
4256                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4257                   op.ops = uintOps;
4258                }
4259                op.kind = intType;
4260                break;
4261             case intSizeType:
4262                if(type.isSigned)
4263                {
4264                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4265                   op.ops = intOps;
4266                }
4267                else
4268                {
4269                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4270                   op.ops = uintOps;
4271                }
4272                op.kind = intType;
4273                break;
4274             case floatType:
4275                op.f = (float)strtod(exp.constant, null);
4276                op.ops = floatOps;
4277                break;
4278             case doubleType:
4279                op.d = (double)strtod(exp.constant, null);
4280                op.ops = doubleOps;
4281                break;
4282             //case classType:    For when we have operator overloading...
4283             // Pointer additions
4284             //case functionType:
4285             case arrayType:
4286             case pointerType:
4287             case classType:
4288                op.ui64 = _strtoui64(exp.constant, null, 0);
4289                op.kind = pointerType;
4290                op.ops = uintOps;
4291                // op.ptrSize =
4292                break;
4293          }
4294       }
4295    }
4296    return op;
4297 }
4298
4299 static void UnusedFunction()
4300 {
4301    int a;
4302    a.OnGetString(0,0,0);
4303 }
4304 default:
4305 extern int __ecereVMethodID_class_OnGetString;
4306 public:
4307
4308 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4309 {
4310    DataMember dataMember;
4311    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4312    {
4313       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4314          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4315       else
4316       {
4317          Expression exp { };
4318          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4319          Type type;
4320          void * ptr = inst.data + dataMember.offset + offset;
4321          char * result = null;
4322          exp.loc = member.loc = inst.loc;
4323          ((Identifier)member.identifiers->first).loc = inst.loc;
4324
4325          if(!dataMember.dataType)
4326             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4327          type = dataMember.dataType;
4328          if(type.kind == classType)
4329          {
4330             Class _class = type._class.registered;
4331             if(_class.type == enumClass)
4332             {
4333                Class enumClass = eSystem_FindClass(privateModule, "enum");
4334                if(enumClass)
4335                {
4336                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4337                   NamedLink item;
4338                   for(item = e.values.first; item; item = item.next)
4339                   {
4340                      if((int)item.data == *(int *)ptr)
4341                      {
4342                         result = item.name;
4343                         break;
4344                      }
4345                   }
4346                   if(result)
4347                   {
4348                      exp.identifier = MkIdentifier(result);
4349                      exp.type = identifierExp;
4350                      exp.destType = MkClassType(_class.fullName);
4351                      ProcessExpressionType(exp);
4352                   }
4353                }
4354             }
4355             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4356             {
4357                if(!_class.dataType)
4358                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4359                type = _class.dataType;
4360             }
4361          }
4362          if(!result)
4363          {
4364             switch(type.kind)
4365             {
4366                case floatType:
4367                {
4368                   FreeExpContents(exp);
4369
4370                   exp.constant = PrintFloat(*(float*)ptr);
4371                   exp.type = constantExp;
4372                   break;
4373                }
4374                case doubleType:
4375                {
4376                   FreeExpContents(exp);
4377
4378                   exp.constant = PrintDouble(*(double*)ptr);
4379                   exp.type = constantExp;
4380                   break;
4381                }
4382                case intType:
4383                {
4384                   FreeExpContents(exp);
4385
4386                   exp.constant = PrintInt(*(int*)ptr);
4387                   exp.type = constantExp;
4388                   break;
4389                }
4390                case int64Type:
4391                {
4392                   FreeExpContents(exp);
4393
4394                   exp.constant = PrintInt64(*(int64*)ptr);
4395                   exp.type = constantExp;
4396                   break;
4397                }
4398                case intPtrType:
4399                {
4400                   FreeExpContents(exp);
4401                   // TODO: This should probably use proper type
4402                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4403                   exp.type = constantExp;
4404                   break;
4405                }
4406                case intSizeType:
4407                {
4408                   FreeExpContents(exp);
4409                   // TODO: This should probably use proper type
4410                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4411                   exp.type = constantExp;
4412                   break;
4413                }
4414                default:
4415                   Compiler_Error($"Unhandled type populating instance\n");
4416             }
4417          }
4418          ListAdd(memberList, member);
4419       }
4420
4421       if(parentDataMember.type == unionMember)
4422          break;
4423    }
4424 }
4425
4426 void PopulateInstance(Instantiation inst)
4427 {
4428    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4429    Class _class = classSym.registered;
4430    DataMember dataMember;
4431    OldList * memberList = MkList();
4432    // Added this check and ->Add to prevent memory leaks on bad code
4433    if(!inst.members)
4434       inst.members = MkListOne(MkMembersInitList(memberList));
4435    else
4436       inst.members->Add(MkMembersInitList(memberList));
4437    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4438    {
4439       if(!dataMember.isProperty)
4440       {
4441          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4442             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4443          else
4444          {
4445             Expression exp { };
4446             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4447             Type type;
4448             void * ptr = inst.data + dataMember.offset;
4449             char * result = null;
4450
4451             exp.loc = member.loc = inst.loc;
4452             ((Identifier)member.identifiers->first).loc = inst.loc;
4453
4454             if(!dataMember.dataType)
4455                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4456             type = dataMember.dataType;
4457             if(type.kind == classType)
4458             {
4459                Class _class = type._class.registered;
4460                if(_class.type == enumClass)
4461                {
4462                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4463                   if(enumClass)
4464                   {
4465                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4466                      NamedLink item;
4467                      for(item = e.values.first; item; item = item.next)
4468                      {
4469                         if((int)item.data == *(int *)ptr)
4470                         {
4471                            result = item.name;
4472                            break;
4473                         }
4474                      }
4475                   }
4476                   if(result)
4477                   {
4478                      exp.identifier = MkIdentifier(result);
4479                      exp.type = identifierExp;
4480                      exp.destType = MkClassType(_class.fullName);
4481                      ProcessExpressionType(exp);
4482                   }
4483                }
4484                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4485                {
4486                   if(!_class.dataType)
4487                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4488                   type = _class.dataType;
4489                }
4490             }
4491             if(!result)
4492             {
4493                switch(type.kind)
4494                {
4495                   case floatType:
4496                   {
4497                      exp.constant = PrintFloat(*(float*)ptr);
4498                      exp.type = constantExp;
4499                      break;
4500                   }
4501                   case doubleType:
4502                   {
4503                      exp.constant = PrintDouble(*(double*)ptr);
4504                      exp.type = constantExp;
4505                      break;
4506                   }
4507                   case intType:
4508                   {
4509                      exp.constant = PrintInt(*(int*)ptr);
4510                      exp.type = constantExp;
4511                      break;
4512                   }
4513                   case int64Type:
4514                   {
4515                      exp.constant = PrintInt64(*(int64*)ptr);
4516                      exp.type = constantExp;
4517                      break;
4518                   }
4519                   case intPtrType:
4520                   {
4521                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4522                      exp.type = constantExp;
4523                      break;
4524                   }
4525                   default:
4526                      Compiler_Error($"Unhandled type populating instance\n");
4527                }
4528             }
4529             ListAdd(memberList, member);
4530          }
4531       }
4532    }
4533 }
4534
4535 void ComputeInstantiation(Expression exp)
4536 {
4537    Instantiation inst = exp.instance;
4538    MembersInit members;
4539    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4540    Class _class = classSym ? classSym.registered : null;
4541    DataMember curMember = null;
4542    Class curClass = null;
4543    DataMember subMemberStack[256];
4544    int subMemberStackPos = 0;
4545    uint64 bits = 0;
4546
4547    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4548    {
4549       // Don't recompute the instantiation...
4550       // Non Simple classes will have become constants by now
4551       if(inst.data)
4552          return;
4553
4554       if(_class.type == normalClass || _class.type == noHeadClass)
4555       {
4556          inst.data = (byte *)eInstance_New(_class);
4557          if(_class.type == normalClass)
4558             ((Instance)inst.data)._refCount++;
4559       }
4560       else
4561          inst.data = new0 byte[_class.structSize];
4562    }
4563
4564    if(inst.members)
4565    {
4566       for(members = inst.members->first; members; members = members.next)
4567       {
4568          switch(members.type)
4569          {
4570             case dataMembersInit:
4571             {
4572                if(members.dataMembers)
4573                {
4574                   MemberInit member;
4575                   for(member = members.dataMembers->first; member; member = member.next)
4576                   {
4577                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4578                      bool found = false;
4579
4580                      Property prop = null;
4581                      DataMember dataMember = null;
4582                      Method method = null;
4583                      uint dataMemberOffset;
4584
4585                      if(!ident)
4586                      {
4587                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4588                         if(curMember)
4589                         {
4590                            if(curMember.isProperty)
4591                               prop = (Property)curMember;
4592                            else
4593                            {
4594                               dataMember = curMember;
4595
4596                               // CHANGED THIS HERE
4597                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4598
4599                               // 2013/17/29 -- It seems that this was missing here!
4600                               if(_class.type == normalClass)
4601                                  dataMemberOffset += _class.base.structSize;
4602                               // dataMemberOffset = dataMember.offset;
4603                            }
4604                            found = true;
4605                         }
4606                      }
4607                      else
4608                      {
4609                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4610                         if(prop)
4611                         {
4612                            found = true;
4613                            if(prop.memberAccess == publicAccess)
4614                            {
4615                               curMember = (DataMember)prop;
4616                               curClass = prop._class;
4617                            }
4618                         }
4619                         else
4620                         {
4621                            DataMember _subMemberStack[256];
4622                            int _subMemberStackPos = 0;
4623
4624                            // FILL MEMBER STACK
4625                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4626
4627                            if(dataMember)
4628                            {
4629                               found = true;
4630                               if(dataMember.memberAccess == publicAccess)
4631                               {
4632                                  curMember = dataMember;
4633                                  curClass = dataMember._class;
4634                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
4635                                  subMemberStackPos = _subMemberStackPos;
4636                               }
4637                            }
4638                         }
4639                      }
4640
4641                      if(found && member.initializer && member.initializer.type == expInitializer)
4642                      {
4643                         Expression value = member.initializer.exp;
4644                         Type type = null;
4645                         bool deepMember = false;
4646                         if(prop)
4647                         {
4648                            type = prop.dataType;
4649                         }
4650                         else if(dataMember)
4651                         {
4652                            if(!dataMember.dataType)
4653                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4654
4655                            type = dataMember.dataType;
4656                         }
4657
4658                         if(ident && ident.next)
4659                         {
4660                            deepMember = true;
4661
4662                            // for(; ident && type; ident = ident.next)
4663                            for(ident = ident.next; ident && type; ident = ident.next)
4664                            {
4665                               if(type.kind == classType)
4666                               {
4667                                  prop = eClass_FindProperty(type._class.registered,
4668                                     ident.string, privateModule);
4669                                  if(prop)
4670                                     type = prop.dataType;
4671                                  else
4672                                  {
4673                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
4674                                        ident.string, &dataMemberOffset, privateModule, null, null);
4675                                     if(dataMember)
4676                                        type = dataMember.dataType;
4677                                  }
4678                               }
4679                               else if(type.kind == structType || type.kind == unionType)
4680                               {
4681                                  Type memberType;
4682                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
4683                                  {
4684                                     if(!strcmp(memberType.name, ident.string))
4685                                     {
4686                                        type = memberType;
4687                                        break;
4688                                     }
4689                                  }
4690                               }
4691                            }
4692                         }
4693                         if(value)
4694                         {
4695                            FreeType(value.destType);
4696                            value.destType = type;
4697                            if(type) type.refCount++;
4698                            ComputeExpression(value);
4699                         }
4700                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
4701                         {
4702                            if(type.kind == classType)
4703                            {
4704                               Class _class = type._class.registered;
4705                               if(_class.type == bitClass || _class.type == unitClass ||
4706                                  _class.type == enumClass)
4707                               {
4708                                  if(!_class.dataType)
4709                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4710                                  type = _class.dataType;
4711                               }
4712                            }
4713
4714                            if(dataMember)
4715                            {
4716                               void * ptr = inst.data + dataMemberOffset;
4717
4718                               if(value.type == constantExp)
4719                               {
4720                                  switch(type.kind)
4721                                  {
4722                                     case intType:
4723                                     {
4724                                        GetInt(value, (int*)ptr);
4725                                        break;
4726                                     }
4727                                     case int64Type:
4728                                     {
4729                                        GetInt64(value, (int64*)ptr);
4730                                        break;
4731                                     }
4732                                     case intPtrType:
4733                                     {
4734                                        GetIntPtr(value, (intptr*)ptr);
4735                                        break;
4736                                     }
4737                                     case intSizeType:
4738                                     {
4739                                        GetIntSize(value, (intsize*)ptr);
4740                                        break;
4741                                     }
4742                                     case floatType:
4743                                     {
4744                                        GetFloat(value, (float*)ptr);
4745                                        break;
4746                                     }
4747                                     case doubleType:
4748                                     {
4749                                        GetDouble(value, (double *)ptr);
4750                                        break;
4751                                     }
4752                                  }
4753                               }
4754                               else if(value.type == instanceExp)
4755                               {
4756                                  if(type.kind == classType)
4757                                  {
4758                                     Class _class = type._class.registered;
4759                                     if(_class.type == structClass)
4760                                     {
4761                                        ComputeTypeSize(type);
4762                                        if(value.instance.data)
4763                                           memcpy(ptr, value.instance.data, type.size);
4764                                     }
4765                                  }
4766                               }
4767                            }
4768                            else if(prop)
4769                            {
4770                               if(value.type == instanceExp && value.instance.data)
4771                               {
4772                                  if(type.kind == classType)
4773                                  {
4774                                     Class _class = type._class.registered;
4775                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
4776                                     {
4777                                        void (*Set)(void *, void *) = (void *)prop.Set;
4778                                        Set(inst.data, value.instance.data);
4779                                        PopulateInstance(inst);
4780                                     }
4781                                  }
4782                               }
4783                               else if(value.type == constantExp)
4784                               {
4785                                  switch(type.kind)
4786                                  {
4787                                     case doubleType:
4788                                     {
4789                                        void (*Set)(void *, double) = (void *)prop.Set;
4790                                        Set(inst.data, strtod(value.constant, null) );
4791                                        break;
4792                                     }
4793                                     case floatType:
4794                                     {
4795                                        void (*Set)(void *, float) = (void *)prop.Set;
4796                                        Set(inst.data, (float)(strtod(value.constant, null)));
4797                                        break;
4798                                     }
4799                                     case intType:
4800                                     {
4801                                        void (*Set)(void *, int) = (void *)prop.Set;
4802                                        Set(inst.data, (int)strtol(value.constant, null, 0));
4803                                        break;
4804                                     }
4805                                     case int64Type:
4806                                     {
4807                                        void (*Set)(void *, int64) = (void *)prop.Set;
4808                                        Set(inst.data, _strtoi64(value.constant, null, 0));
4809                                        break;
4810                                     }
4811                                     case intPtrType:
4812                                     {
4813                                        void (*Set)(void *, intptr) = (void *)prop.Set;
4814                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
4815                                        break;
4816                                     }
4817                                     case intSizeType:
4818                                     {
4819                                        void (*Set)(void *, intsize) = (void *)prop.Set;
4820                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
4821                                        break;
4822                                     }
4823                                  }
4824                               }
4825                               else if(value.type == stringExp)
4826                               {
4827                                  char temp[1024];
4828                                  ReadString(temp, value.string);
4829                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
4830                               }
4831                            }
4832                         }
4833                         else if(!deepMember && type && _class.type == unitClass)
4834                         {
4835                            if(prop)
4836                            {
4837                               // Only support converting units to units for now...
4838                               if(value.type == constantExp)
4839                               {
4840                                  if(type.kind == classType)
4841                                  {
4842                                     Class _class = type._class.registered;
4843                                     if(_class.type == unitClass)
4844                                     {
4845                                        if(!_class.dataType)
4846                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4847                                        type = _class.dataType;
4848                                     }
4849                                  }
4850                                  // TODO: Assuming same base type for units...
4851                                  switch(type.kind)
4852                                  {
4853                                     case floatType:
4854                                     {
4855                                        float fValue;
4856                                        float (*Set)(float) = (void *)prop.Set;
4857                                        GetFloat(member.initializer.exp, &fValue);
4858                                        exp.constant = PrintFloat(Set(fValue));
4859                                        exp.type = constantExp;
4860                                        break;
4861                                     }
4862                                     case doubleType:
4863                                     {
4864                                        double dValue;
4865                                        double (*Set)(double) = (void *)prop.Set;
4866                                        GetDouble(member.initializer.exp, &dValue);
4867                                        exp.constant = PrintDouble(Set(dValue));
4868                                        exp.type = constantExp;
4869                                        break;
4870                                     }
4871                                  }
4872                               }
4873                            }
4874                         }
4875                         else if(!deepMember && type && _class.type == bitClass)
4876                         {
4877                            if(prop)
4878                            {
4879                               if(value.type == instanceExp && value.instance.data)
4880                               {
4881                                  unsigned int (*Set)(void *) = (void *)prop.Set;
4882                                  bits = Set(value.instance.data);
4883                               }
4884                               else if(value.type == constantExp)
4885                               {
4886                               }
4887                            }
4888                            else if(dataMember)
4889                            {
4890                               BitMember bitMember = (BitMember) dataMember;
4891                               Type type;
4892                               int part = 0;
4893                               GetInt(value, &part);
4894                               bits = (bits & ~bitMember.mask);
4895                               if(!bitMember.dataType)
4896                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
4897
4898                               type = bitMember.dataType;
4899
4900                               if(type.kind == classType && type._class && type._class.registered)
4901                               {
4902                                  if(!type._class.registered.dataType)
4903                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4904                                  type = type._class.registered.dataType;
4905                               }
4906
4907                               switch(type.kind)
4908                               {
4909                                  case _BoolType:
4910                                  case charType:
4911                                     if(type.isSigned)
4912                                        bits |= ((char)part << bitMember.pos);
4913                                     else
4914                                        bits |= ((unsigned char)part << bitMember.pos);
4915                                     break;
4916                                  case shortType:
4917                                     if(type.isSigned)
4918                                        bits |= ((short)part << bitMember.pos);
4919                                     else
4920                                        bits |= ((unsigned short)part << bitMember.pos);
4921                                     break;
4922                                  case intType:
4923                                  case longType:
4924                                     if(type.isSigned)
4925                                        bits |= ((int)part << bitMember.pos);
4926                                     else
4927                                        bits |= ((unsigned int)part << bitMember.pos);
4928                                     break;
4929                                  case int64Type:
4930                                     if(type.isSigned)
4931                                        bits |= ((int64)part << bitMember.pos);
4932                                     else
4933                                        bits |= ((uint64)part << bitMember.pos);
4934                                     break;
4935                                  case intPtrType:
4936                                     if(type.isSigned)
4937                                     {
4938                                        bits |= ((intptr)part << bitMember.pos);
4939                                     }
4940                                     else
4941                                     {
4942                                        bits |= ((uintptr)part << bitMember.pos);
4943                                     }
4944                                     break;
4945                                  case intSizeType:
4946                                     if(type.isSigned)
4947                                     {
4948                                        bits |= ((ssize_t)(intsize)part << bitMember.pos);
4949                                     }
4950                                     else
4951                                     {
4952                                        bits |= ((size_t) (uintsize)part << bitMember.pos);
4953                                     }
4954                                     break;
4955                               }
4956                            }
4957                         }
4958                      }
4959                      else
4960                      {
4961                         if(_class && _class.type == unitClass)
4962                         {
4963                            ComputeExpression(member.initializer.exp);
4964                            exp.constant = member.initializer.exp.constant;
4965                            exp.type = constantExp;
4966
4967                            member.initializer.exp.constant = null;
4968                         }
4969                      }
4970                   }
4971                }
4972                break;
4973             }
4974          }
4975       }
4976    }
4977    if(_class && _class.type == bitClass)
4978    {
4979       exp.constant = PrintHexUInt(bits);
4980       exp.type = constantExp;
4981    }
4982    if(exp.type != instanceExp)
4983    {
4984       FreeInstance(inst);
4985    }
4986 }
4987
4988 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
4989 {
4990    if(exp.op.op == SIZEOF)
4991    {
4992       FreeExpContents(exp);
4993       exp.type = constantExp;
4994       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
4995    }
4996    else
4997    {
4998       if(!exp.op.exp1)
4999       {
5000          switch(exp.op.op)
5001          {
5002             // unary arithmetic
5003             case '+':
5004             {
5005                // Provide default unary +
5006                Expression exp2 = exp.op.exp2;
5007                exp.op.exp2 = null;
5008                FreeExpContents(exp);
5009                FreeType(exp.expType);
5010                FreeType(exp.destType);
5011                *exp = *exp2;
5012                delete exp2;
5013                break;
5014             }
5015             case '-':
5016                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5017                break;
5018             // unary arithmetic increment and decrement
5019                   //OPERATOR_ALL(UNARY, ++, Inc)
5020                   //OPERATOR_ALL(UNARY, --, Dec)
5021             // unary bitwise
5022             case '~':
5023                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5024                break;
5025             // unary logical negation
5026             case '!':
5027                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5028                break;
5029          }
5030       }
5031       else
5032       {
5033          switch(exp.op.op)
5034          {
5035             // binary arithmetic
5036             case '+':
5037                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5038                break;
5039             case '-':
5040                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5041                break;
5042             case '*':
5043                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5044                break;
5045             case '/':
5046                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5047                break;
5048             case '%':
5049                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5050                break;
5051             // binary arithmetic assignment
5052                   //OPERATOR_ALL(BINARY, =, Asign)
5053                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5054                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5055                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5056                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5057                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5058             // binary bitwise
5059             case '&':
5060                if(exp.op.exp2)
5061                {
5062                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5063                }
5064                break;
5065             case '|':
5066                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5067                break;
5068             case '^':
5069                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5070                break;
5071             case LEFT_OP:
5072                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5073                break;
5074             case RIGHT_OP:
5075                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5076                break;
5077             // binary bitwise assignment
5078                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5079                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5080                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5081                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5082                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5083             // binary logical equality
5084             case EQ_OP:
5085                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5086                break;
5087             case NE_OP:
5088                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5089                break;
5090             // binary logical
5091             case AND_OP:
5092                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5093                break;
5094             case OR_OP:
5095                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5096                break;
5097             // binary logical relational
5098             case '>':
5099                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5100                break;
5101             case '<':
5102                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5103                break;
5104             case GE_OP:
5105                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5106                break;
5107             case LE_OP:
5108                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5109                break;
5110          }
5111       }
5112    }
5113 }
5114
5115 void ComputeExpression(Expression exp)
5116 {
5117    char expString[10240];
5118    expString[0] = '\0';
5119 #ifdef _DEBUG
5120    PrintExpression(exp, expString);
5121 #endif
5122
5123    switch(exp.type)
5124    {
5125       case instanceExp:
5126       {
5127          ComputeInstantiation(exp);
5128          break;
5129       }
5130       /*
5131       case constantExp:
5132          break;
5133       */
5134       case opExp:
5135       {
5136          Expression exp1, exp2 = null;
5137          Operand op1 { };
5138          Operand op2 { };
5139
5140          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5141          if(exp.op.exp2)
5142             ComputeExpression(exp.op.exp2);
5143          if(exp.op.exp1)
5144          {
5145             ComputeExpression(exp.op.exp1);
5146             exp1 = exp.op.exp1;
5147             exp2 = exp.op.exp2;
5148             op1 = GetOperand(exp1);
5149             if(op1.type) op1.type.refCount++;
5150             if(exp2)
5151             {
5152                op2 = GetOperand(exp2);
5153                if(op2.type) op2.type.refCount++;
5154             }
5155          }
5156          else
5157          {
5158             exp1 = exp.op.exp2;
5159             op1 = GetOperand(exp1);
5160             if(op1.type) op1.type.refCount++;
5161          }
5162
5163          CallOperator(exp, exp1, exp2, op1, op2);
5164          /*
5165          switch(exp.op.op)
5166          {
5167             // Unary operators
5168             case '&':
5169                // Also binary
5170                if(exp.op.exp1 && exp.op.exp2)
5171                {
5172                   // Binary And
5173                   if(op1.ops.BitAnd)
5174                   {
5175                      FreeExpContents(exp);
5176                      op1.ops.BitAnd(exp, op1, op2);
5177                   }
5178                }
5179                break;
5180             case '*':
5181                if(exp.op.exp1)
5182                {
5183                   if(op1.ops.Mul)
5184                   {
5185                      FreeExpContents(exp);
5186                      op1.ops.Mul(exp, op1, op2);
5187                   }
5188                }
5189                break;
5190             case '+':
5191                if(exp.op.exp1)
5192                {
5193                   if(op1.ops.Add)
5194                   {
5195                      FreeExpContents(exp);
5196                      op1.ops.Add(exp, op1, op2);
5197                   }
5198                }
5199                else
5200                {
5201                   // Provide default unary +
5202                   Expression exp2 = exp.op.exp2;
5203                   exp.op.exp2 = null;
5204                   FreeExpContents(exp);
5205                   FreeType(exp.expType);
5206                   FreeType(exp.destType);
5207
5208                   *exp = *exp2;
5209                   delete exp2;
5210                }
5211                break;
5212             case '-':
5213                if(exp.op.exp1)
5214                {
5215                   if(op1.ops.Sub)
5216                   {
5217                      FreeExpContents(exp);
5218                      op1.ops.Sub(exp, op1, op2);
5219                   }
5220                }
5221                else
5222                {
5223                   if(op1.ops.Neg)
5224                   {
5225                      FreeExpContents(exp);
5226                      op1.ops.Neg(exp, op1);
5227                   }
5228                }
5229                break;
5230             case '~':
5231                if(op1.ops.BitNot)
5232                {
5233                   FreeExpContents(exp);
5234                   op1.ops.BitNot(exp, op1);
5235                }
5236                break;
5237             case '!':
5238                if(op1.ops.Not)
5239                {
5240                   FreeExpContents(exp);
5241                   op1.ops.Not(exp, op1);
5242                }
5243                break;
5244             // Binary only operators
5245             case '/':
5246                if(op1.ops.Div)
5247                {
5248                   FreeExpContents(exp);
5249                   op1.ops.Div(exp, op1, op2);
5250                }
5251                break;
5252             case '%':
5253                if(op1.ops.Mod)
5254                {
5255                   FreeExpContents(exp);
5256                   op1.ops.Mod(exp, op1, op2);
5257                }
5258                break;
5259             case LEFT_OP:
5260                break;
5261             case RIGHT_OP:
5262                break;
5263             case '<':
5264                if(exp.op.exp1)
5265                {
5266                   if(op1.ops.Sma)
5267                   {
5268                      FreeExpContents(exp);
5269                      op1.ops.Sma(exp, op1, op2);
5270                   }
5271                }
5272                break;
5273             case '>':
5274                if(exp.op.exp1)
5275                {
5276                   if(op1.ops.Grt)
5277                   {
5278                      FreeExpContents(exp);
5279                      op1.ops.Grt(exp, op1, op2);
5280                   }
5281                }
5282                break;
5283             case LE_OP:
5284                if(exp.op.exp1)
5285                {
5286                   if(op1.ops.SmaEqu)
5287                   {
5288                      FreeExpContents(exp);
5289                      op1.ops.SmaEqu(exp, op1, op2);
5290                   }
5291                }
5292                break;
5293             case GE_OP:
5294                if(exp.op.exp1)
5295                {
5296                   if(op1.ops.GrtEqu)
5297                   {
5298                      FreeExpContents(exp);
5299                      op1.ops.GrtEqu(exp, op1, op2);
5300                   }
5301                }
5302                break;
5303             case EQ_OP:
5304                if(exp.op.exp1)
5305                {
5306                   if(op1.ops.Equ)
5307                   {
5308                      FreeExpContents(exp);
5309                      op1.ops.Equ(exp, op1, op2);
5310                   }
5311                }
5312                break;
5313             case NE_OP:
5314                if(exp.op.exp1)
5315                {
5316                   if(op1.ops.Nqu)
5317                   {
5318                      FreeExpContents(exp);
5319                      op1.ops.Nqu(exp, op1, op2);
5320                   }
5321                }
5322                break;
5323             case '|':
5324                if(op1.ops.BitOr)
5325                {
5326                   FreeExpContents(exp);
5327                   op1.ops.BitOr(exp, op1, op2);
5328                }
5329                break;
5330             case '^':
5331                if(op1.ops.BitXor)
5332                {
5333                   FreeExpContents(exp);
5334                   op1.ops.BitXor(exp, op1, op2);
5335                }
5336                break;
5337             case AND_OP:
5338                break;
5339             case OR_OP:
5340                break;
5341             case SIZEOF:
5342                FreeExpContents(exp);
5343                exp.type = constantExp;
5344                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5345                break;
5346          }
5347          */
5348          if(op1.type) FreeType(op1.type);
5349          if(op2.type) FreeType(op2.type);
5350          break;
5351       }
5352       case bracketsExp:
5353       case extensionExpressionExp:
5354       {
5355          Expression e, n;
5356          for(e = exp.list->first; e; e = n)
5357          {
5358             n = e.next;
5359             if(!n)
5360             {
5361                OldList * list = exp.list;
5362                ComputeExpression(e);
5363                //FreeExpContents(exp);
5364                FreeType(exp.expType);
5365                FreeType(exp.destType);
5366                *exp = *e;
5367                delete e;
5368                delete list;
5369             }
5370             else
5371             {
5372                FreeExpression(e);
5373             }
5374          }
5375          break;
5376       }
5377       /*
5378
5379       case ExpIndex:
5380       {
5381          Expression e;
5382          exp.isConstant = true;
5383
5384          ComputeExpression(exp.index.exp);
5385          if(!exp.index.exp.isConstant)
5386             exp.isConstant = false;
5387
5388          for(e = exp.index.index->first; e; e = e.next)
5389          {
5390             ComputeExpression(e);
5391             if(!e.next)
5392             {
5393                // Check if this type is int
5394             }
5395             if(!e.isConstant)
5396                exp.isConstant = false;
5397          }
5398          exp.expType = Dereference(exp.index.exp.expType);
5399          break;
5400       }
5401       */
5402       case memberExp:
5403       {
5404          Expression memberExp = exp.member.exp;
5405          Identifier memberID = exp.member.member;
5406
5407          Type type;
5408          ComputeExpression(exp.member.exp);
5409          type = exp.member.exp.expType;
5410          if(type)
5411          {
5412             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);
5413             Property prop = null;
5414             DataMember member = null;
5415             Class convertTo = null;
5416             if(type.kind == subClassType && exp.member.exp.type == classExp)
5417                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5418
5419             if(!_class)
5420             {
5421                char string[256];
5422                Symbol classSym;
5423                string[0] = '\0';
5424                PrintTypeNoConst(type, string, false, true);
5425                classSym = FindClass(string);
5426                _class = classSym ? classSym.registered : null;
5427             }
5428
5429             if(exp.member.member)
5430             {
5431                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5432                if(!prop)
5433                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5434             }
5435             if(!prop && !member && _class && exp.member.member)
5436             {
5437                Symbol classSym = FindClass(exp.member.member.string);
5438                convertTo = _class;
5439                _class = classSym ? classSym.registered : null;
5440                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5441             }
5442
5443             if(prop)
5444             {
5445                if(prop.compiled)
5446                {
5447                   Type type = prop.dataType;
5448                   // TODO: Assuming same base type for units...
5449                   if(_class.type == unitClass)
5450                   {
5451                      if(type.kind == classType)
5452                      {
5453                         Class _class = type._class.registered;
5454                         if(_class.type == unitClass)
5455                         {
5456                            if(!_class.dataType)
5457                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5458                            type = _class.dataType;
5459                         }
5460                      }
5461                      switch(type.kind)
5462                      {
5463                         case floatType:
5464                         {
5465                            float value;
5466                            float (*Get)(float) = (void *)prop.Get;
5467                            GetFloat(exp.member.exp, &value);
5468                            exp.constant = PrintFloat(Get ? Get(value) : value);
5469                            exp.type = constantExp;
5470                            break;
5471                         }
5472                         case doubleType:
5473                         {
5474                            double value;
5475                            double (*Get)(double);
5476                            GetDouble(exp.member.exp, &value);
5477
5478                            if(convertTo)
5479                               Get = (void *)prop.Set;
5480                            else
5481                               Get = (void *)prop.Get;
5482                            exp.constant = PrintDouble(Get ? Get(value) : value);
5483                            exp.type = constantExp;
5484                            break;
5485                         }
5486                      }
5487                   }
5488                   else
5489                   {
5490                      if(convertTo)
5491                      {
5492                         Expression value = exp.member.exp;
5493                         Type type;
5494                         if(!prop.dataType)
5495                            ProcessPropertyType(prop);
5496
5497                         type = prop.dataType;
5498                         if(!type)
5499                         {
5500                             // printf("Investigate this\n");
5501                         }
5502                         else if(_class.type == structClass)
5503                         {
5504                            switch(type.kind)
5505                            {
5506                               case classType:
5507                               {
5508                                  Class propertyClass = type._class.registered;
5509                                  if(propertyClass.type == structClass && value.type == instanceExp)
5510                                  {
5511                                     void (*Set)(void *, void *) = (void *)prop.Set;
5512                                     exp.instance = Instantiation { };
5513                                     exp.instance.data = new0 byte[_class.structSize];
5514                                     exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5515                                     exp.instance.loc = exp.loc;
5516                                     exp.type = instanceExp;
5517                                     Set(exp.instance.data, value.instance.data);
5518                                     PopulateInstance(exp.instance);
5519                                  }
5520                                  break;
5521                               }
5522                               case intType:
5523                               {
5524                                  int intValue;
5525                                  void (*Set)(void *, int) = (void *)prop.Set;
5526
5527                                  exp.instance = Instantiation { };
5528                                  exp.instance.data = new0 byte[_class.structSize];
5529                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5530                                  exp.instance.loc = exp.loc;
5531                                  exp.type = instanceExp;
5532
5533                                  GetInt(value, &intValue);
5534
5535                                  Set(exp.instance.data, intValue);
5536                                  PopulateInstance(exp.instance);
5537                                  break;
5538                               }
5539                               case int64Type:
5540                               {
5541                                  int64 intValue;
5542                                  void (*Set)(void *, int64) = (void *)prop.Set;
5543
5544                                  exp.instance = Instantiation { };
5545                                  exp.instance.data = new0 byte[_class.structSize];
5546                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5547                                  exp.instance.loc = exp.loc;
5548                                  exp.type = instanceExp;
5549
5550                                  GetInt64(value, &intValue);
5551
5552                                  Set(exp.instance.data, intValue);
5553                                  PopulateInstance(exp.instance);
5554                                  break;
5555                               }
5556                               case intPtrType:
5557                               {
5558                                  // TOFIX:
5559                                  intptr intValue;
5560                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5561
5562                                  exp.instance = Instantiation { };
5563                                  exp.instance.data = new0 byte[_class.structSize];
5564                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5565                                  exp.instance.loc = exp.loc;
5566                                  exp.type = instanceExp;
5567
5568                                  GetIntPtr(value, &intValue);
5569
5570                                  Set(exp.instance.data, intValue);
5571                                  PopulateInstance(exp.instance);
5572                                  break;
5573                               }
5574                               case intSizeType:
5575                               {
5576                                  // TOFIX:
5577                                  intsize intValue;
5578                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5579
5580                                  exp.instance = Instantiation { };
5581                                  exp.instance.data = new0 byte[_class.structSize];
5582                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5583                                  exp.instance.loc = exp.loc;
5584                                  exp.type = instanceExp;
5585
5586                                  GetIntSize(value, &intValue);
5587
5588                                  Set(exp.instance.data, intValue);
5589                                  PopulateInstance(exp.instance);
5590                                  break;
5591                               }
5592                               case doubleType:
5593                               {
5594                                  double doubleValue;
5595                                  void (*Set)(void *, double) = (void *)prop.Set;
5596
5597                                  exp.instance = Instantiation { };
5598                                  exp.instance.data = new0 byte[_class.structSize];
5599                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5600                                  exp.instance.loc = exp.loc;
5601                                  exp.type = instanceExp;
5602
5603                                  GetDouble(value, &doubleValue);
5604
5605                                  Set(exp.instance.data, doubleValue);
5606                                  PopulateInstance(exp.instance);
5607                                  break;
5608                               }
5609                            }
5610                         }
5611                         else if(_class.type == bitClass)
5612                         {
5613                            switch(type.kind)
5614                            {
5615                               case classType:
5616                               {
5617                                  Class propertyClass = type._class.registered;
5618                                  if(propertyClass.type == structClass && value.instance.data)
5619                                  {
5620                                     unsigned int (*Set)(void *) = (void *)prop.Set;
5621                                     unsigned int bits = Set(value.instance.data);
5622                                     exp.constant = PrintHexUInt(bits);
5623                                     exp.type = constantExp;
5624                                     break;
5625                                  }
5626                                  else if(_class.type == bitClass)
5627                                  {
5628                                     unsigned int value;
5629                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
5630                                     unsigned int bits;
5631
5632                                     GetUInt(exp.member.exp, &value);
5633                                     bits = Set(value);
5634                                     exp.constant = PrintHexUInt(bits);
5635                                     exp.type = constantExp;
5636                                  }
5637                               }
5638                            }
5639                         }
5640                      }
5641                      else
5642                      {
5643                         if(_class.type == bitClass)
5644                         {
5645                            unsigned int value;
5646                            GetUInt(exp.member.exp, &value);
5647
5648                            switch(type.kind)
5649                            {
5650                               case classType:
5651                               {
5652                                  Class _class = type._class.registered;
5653                                  if(_class.type == structClass)
5654                                  {
5655                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
5656
5657                                     exp.instance = Instantiation { };
5658                                     exp.instance.data = new0 byte[_class.structSize];
5659                                     exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5660                                     exp.instance.loc = exp.loc;
5661                                     //exp.instance.fullSet = true;
5662                                     exp.type = instanceExp;
5663                                     Get(value, exp.instance.data);
5664                                     PopulateInstance(exp.instance);
5665                                  }
5666                                  else if(_class.type == bitClass)
5667                                  {
5668                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
5669                                     uint64 bits = Get(value);
5670                                     exp.constant = PrintHexUInt64(bits);
5671                                     exp.type = constantExp;
5672                                  }
5673                                  break;
5674                               }
5675                            }
5676                         }
5677                         else if(_class.type == structClass)
5678                         {
5679                            char * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
5680                            switch(type.kind)
5681                            {
5682                               case classType:
5683                               {
5684                                  Class _class = type._class.registered;
5685                                  if(_class.type == structClass && value)
5686                                  {
5687                                     void (*Get)(void *, void *) = (void *)prop.Get;
5688
5689                                     exp.instance = Instantiation { };
5690                                     exp.instance.data = new0 byte[_class.structSize];
5691                                     exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5692                                     exp.instance.loc = exp.loc;
5693                                     //exp.instance.fullSet = true;
5694                                     exp.type = instanceExp;
5695                                     Get(value, exp.instance.data);
5696                                     PopulateInstance(exp.instance);
5697                                  }
5698                                  break;
5699                               }
5700                            }
5701                         }
5702                         /*else
5703                         {
5704                            char * value = exp.member.exp.instance.data;
5705                            switch(type.kind)
5706                            {
5707                               case classType:
5708                               {
5709                                  Class _class = type._class.registered;
5710                                  if(_class.type == normalClass)
5711                                  {
5712                                     void *(*Get)(void *) = (void *)prop.Get;
5713
5714                                     exp.instance = Instantiation { };
5715                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
5716                                     exp.type = instanceExp;
5717                                     exp.instance.data = Get(value, exp.instance.data);
5718                                  }
5719                                  break;
5720                               }
5721                            }
5722                         }
5723                         */
5724                      }
5725                   }
5726                }
5727                else
5728                {
5729                   exp.isConstant = false;
5730                }
5731             }
5732             else if(member)
5733             {
5734             }
5735          }
5736
5737          if(exp.type != ExpressionType::memberExp)
5738          {
5739             FreeExpression(memberExp);
5740             FreeIdentifier(memberID);
5741          }
5742          break;
5743       }
5744       case typeSizeExp:
5745       {
5746          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
5747          FreeExpContents(exp);
5748          exp.constant = PrintUInt(ComputeTypeSize(type));
5749          exp.type = constantExp;
5750          FreeType(type);
5751          break;
5752       }
5753       case classSizeExp:
5754       {
5755          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
5756          if(classSym && classSym.registered)
5757          {
5758             if(classSym.registered.fixed)
5759             {
5760                FreeSpecifier(exp._class);
5761                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
5762                exp.type = constantExp;
5763             }
5764             else
5765             {
5766                char className[1024];
5767                strcpy(className, "__ecereClass_");
5768                FullClassNameCat(className, classSym.string, true);
5769                MangleClassName(className);
5770
5771                DeclareClass(classSym, className);
5772
5773                FreeExpContents(exp);
5774                exp.type = pointerExp;
5775                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
5776                exp.member.member = MkIdentifier("structSize");
5777             }
5778          }
5779          break;
5780       }
5781       case castExp:
5782       //case constantExp:
5783       {
5784          Type type;
5785          Expression e = exp;
5786          if(exp.type == castExp)
5787          {
5788             if(exp.cast.exp)
5789                ComputeExpression(exp.cast.exp);
5790             e = exp.cast.exp;
5791          }
5792          if(e && exp.expType)
5793          {
5794             /*if(exp.destType)
5795                type = exp.destType;
5796             else*/
5797                type = exp.expType;
5798             if(type.kind == classType)
5799             {
5800                Class _class = type._class.registered;
5801                if(_class && (_class.type == unitClass || _class.type == bitClass))
5802                {
5803                   if(!_class.dataType)
5804                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5805                   type = _class.dataType;
5806                }
5807             }
5808
5809             switch(type.kind)
5810             {
5811                case _BoolType:
5812                case charType:
5813                   if(type.isSigned)
5814                   {
5815                      char value;
5816                      GetChar(e, &value);
5817                      FreeExpContents(exp);
5818                      exp.constant = PrintChar(value);
5819                      exp.type = constantExp;
5820                   }
5821                   else
5822                   {
5823                      unsigned char value;
5824                      GetUChar(e, &value);
5825                      FreeExpContents(exp);
5826                      exp.constant = PrintUChar(value);
5827                      exp.type = constantExp;
5828                   }
5829                   break;
5830                case shortType:
5831                   if(type.isSigned)
5832                   {
5833                      short value;
5834                      GetShort(e, &value);
5835                      FreeExpContents(exp);
5836                      exp.constant = PrintShort(value);
5837                      exp.type = constantExp;
5838                   }
5839                   else
5840                   {
5841                      unsigned short value;
5842                      GetUShort(e, &value);
5843                      FreeExpContents(exp);
5844                      exp.constant = PrintUShort(value);
5845                      exp.type = constantExp;
5846                   }
5847                   break;
5848                case intType:
5849                   if(type.isSigned)
5850                   {
5851                      int value;
5852                      GetInt(e, &value);
5853                      FreeExpContents(exp);
5854                      exp.constant = PrintInt(value);
5855                      exp.type = constantExp;
5856                   }
5857                   else
5858                   {
5859                      unsigned int value;
5860                      GetUInt(e, &value);
5861                      FreeExpContents(exp);
5862                      exp.constant = PrintUInt(value);
5863                      exp.type = constantExp;
5864                   }
5865                   break;
5866                case int64Type:
5867                   if(type.isSigned)
5868                   {
5869                      int64 value;
5870                      GetInt64(e, &value);
5871                      FreeExpContents(exp);
5872                      exp.constant = PrintInt64(value);
5873                      exp.type = constantExp;
5874                   }
5875                   else
5876                   {
5877                      uint64 value;
5878                      GetUInt64(e, &value);
5879                      FreeExpContents(exp);
5880                      exp.constant = PrintUInt64(value);
5881                      exp.type = constantExp;
5882                   }
5883                   break;
5884                case intPtrType:
5885                   if(type.isSigned)
5886                   {
5887                      intptr value;
5888                      GetIntPtr(e, &value);
5889                      FreeExpContents(exp);
5890                      exp.constant = PrintInt64((int64)value);
5891                      exp.type = constantExp;
5892                   }
5893                   else
5894                   {
5895                      uintptr value;
5896                      GetUIntPtr(e, &value);
5897                      FreeExpContents(exp);
5898                      exp.constant = PrintUInt64((uint64)value);
5899                      exp.type = constantExp;
5900                   }
5901                   break;
5902                case intSizeType:
5903                   if(type.isSigned)
5904                   {
5905                      intsize value;
5906                      GetIntSize(e, &value);
5907                      FreeExpContents(exp);
5908                      exp.constant = PrintInt64((int64)value);
5909                      exp.type = constantExp;
5910                   }
5911                   else
5912                   {
5913                      uintsize value;
5914                      GetUIntSize(e, &value);
5915                      FreeExpContents(exp);
5916                      exp.constant = PrintUInt64((uint64)value);
5917                      exp.type = constantExp;
5918                   }
5919                   break;
5920                case floatType:
5921                {
5922                   float value;
5923                   GetFloat(e, &value);
5924                   FreeExpContents(exp);
5925                   exp.constant = PrintFloat(value);
5926                   exp.type = constantExp;
5927                   break;
5928                }
5929                case doubleType:
5930                {
5931                   double value;
5932                   GetDouble(e, &value);
5933                   FreeExpContents(exp);
5934                   exp.constant = PrintDouble(value);
5935                   exp.type = constantExp;
5936                   break;
5937                }
5938             }
5939          }
5940          break;
5941       }
5942       case conditionExp:
5943       {
5944          Operand op1 { };
5945          Operand op2 { };
5946          Operand op3 { };
5947
5948          if(exp.cond.exp)
5949             // Caring only about last expression for now...
5950             ComputeExpression(exp.cond.exp->last);
5951          if(exp.cond.elseExp)
5952             ComputeExpression(exp.cond.elseExp);
5953          if(exp.cond.cond)
5954             ComputeExpression(exp.cond.cond);
5955
5956          op1 = GetOperand(exp.cond.cond);
5957          if(op1.type) op1.type.refCount++;
5958          op2 = GetOperand(exp.cond.exp->last);
5959          if(op2.type) op2.type.refCount++;
5960          op3 = GetOperand(exp.cond.elseExp);
5961          if(op3.type) op3.type.refCount++;
5962
5963          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
5964          if(op1.type) FreeType(op1.type);
5965          if(op2.type) FreeType(op2.type);
5966          if(op3.type) FreeType(op3.type);
5967          break;
5968       }
5969    }
5970 }
5971
5972 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla)
5973 {
5974    bool result = true;
5975    if(destType)
5976    {
5977       OldList converts { };
5978       Conversion convert;
5979
5980       if(destType.kind == voidType)
5981          return false;
5982
5983       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla))
5984          result = false;
5985       if(converts.count)
5986       {
5987          // for(convert = converts.last; convert; convert = convert.prev)
5988          for(convert = converts.first; convert; convert = convert.next)
5989          {
5990             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
5991             if(!empty)
5992             {
5993                Expression newExp { };
5994                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
5995
5996                // TODO: Check this...
5997                *newExp = *exp;
5998                newExp.destType = null;
5999
6000                if(convert.isGet)
6001                {
6002                   // [exp].ColorRGB
6003                   exp.type = memberExp;
6004                   exp.addedThis = true;
6005                   exp.member.exp = newExp;
6006                   FreeType(exp.member.exp.expType);
6007
6008                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6009                   exp.member.exp.expType.classObjectType = objectType;
6010                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6011                   exp.member.memberType = propertyMember;
6012                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6013                   // TESTING THIS... for (int)degrees
6014                   exp.needCast = true;
6015                   if(exp.expType) exp.expType.refCount++;
6016                   ApplyAnyObjectLogic(exp.member.exp);
6017                }
6018                else
6019                {
6020
6021                   /*if(exp.isConstant)
6022                   {
6023                      // Color { ColorRGB = [exp] };
6024                      exp.type = instanceExp;
6025                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6026                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6027                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6028                   }
6029                   else*/
6030                   {
6031                      // If not constant, don't turn it yet into an instantiation
6032                      // (Go through the deep members system first)
6033                      exp.type = memberExp;
6034                      exp.addedThis = true;
6035                      exp.member.exp = newExp;
6036
6037                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6038                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6039                         newExp.expType._class.registered.type == noHeadClass)
6040                      {
6041                         newExp.byReference = true;
6042                      }
6043
6044                      FreeType(exp.member.exp.expType);
6045                      /*exp.member.exp.expType = convert.convert.dataType;
6046                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6047                      exp.member.exp.expType = null;
6048                      if(convert.convert.dataType)
6049                      {
6050                         exp.member.exp.expType = { };
6051                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6052                         exp.member.exp.expType.refCount = 1;
6053                         exp.member.exp.expType.classObjectType = objectType;
6054                         ApplyAnyObjectLogic(exp.member.exp);
6055                      }
6056
6057                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6058                      exp.member.memberType = reverseConversionMember;
6059                      exp.expType = convert.resultType ? convert.resultType :
6060                         MkClassType(convert.convert._class.fullName);
6061                      exp.needCast = true;
6062                      if(convert.resultType) convert.resultType.refCount++;
6063                   }
6064                }
6065             }
6066             else
6067             {
6068                FreeType(exp.expType);
6069                if(convert.isGet)
6070                {
6071                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6072                   exp.needCast = true;
6073                   if(exp.expType) exp.expType.refCount++;
6074                }
6075                else
6076                {
6077                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6078                   exp.needCast = true;
6079                   if(convert.resultType)
6080                      convert.resultType.refCount++;
6081                }
6082             }
6083          }
6084          if(exp.isConstant && inCompiler)
6085             ComputeExpression(exp);
6086
6087          converts.Free(FreeConvert);
6088       }
6089
6090       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6091       {
6092          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false);
6093       }
6094       if(!result && exp.expType && exp.destType)
6095       {
6096          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6097              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6098             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6099             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6100             result = true;
6101       }
6102    }
6103    // if(result) CheckTemplateTypes(exp);
6104    return result;
6105 }
6106
6107 void CheckTemplateTypes(Expression exp)
6108 {
6109    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate)
6110    {
6111       Expression newExp { };
6112       Statement compound;
6113       Context context;
6114       *newExp = *exp;
6115       if(exp.destType) exp.destType.refCount++;
6116       if(exp.expType)  exp.expType.refCount++;
6117       newExp.prev = null;
6118       newExp.next = null;
6119
6120       switch(exp.expType.kind)
6121       {
6122          case doubleType:
6123             if(exp.destType.classObjectType)
6124             {
6125                // We need to pass the address, just pass it along (Undo what was done above)
6126                if(exp.destType) exp.destType.refCount--;
6127                if(exp.expType)  exp.expType.refCount--;
6128                delete newExp;
6129             }
6130             else
6131             {
6132                // If we're looking for value:
6133                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6134                OldList * specs;
6135                OldList * unionDefs = MkList();
6136                OldList * statements = MkList();
6137                context = PushContext();
6138                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6139                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6140                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6141                exp.type = extensionCompoundExp;
6142                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6143                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6144                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6145                exp.compound.compound.context = context;
6146                PopContext(context);
6147             }
6148             break;
6149          default:
6150             exp.type = castExp;
6151             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6152             exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6153             break;
6154       }
6155    }
6156    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6157    {
6158       Expression newExp { };
6159       Statement compound;
6160       Context context;
6161       *newExp = *exp;
6162       if(exp.destType) exp.destType.refCount++;
6163       if(exp.expType)  exp.expType.refCount++;
6164       newExp.prev = null;
6165       newExp.next = null;
6166
6167       switch(exp.expType.kind)
6168       {
6169          case doubleType:
6170             if(exp.destType.classObjectType)
6171             {
6172                // We need to pass the address, just pass it along (Undo what was done above)
6173                if(exp.destType) exp.destType.refCount--;
6174                if(exp.expType)  exp.expType.refCount--;
6175                delete newExp;
6176             }
6177             else
6178             {
6179                // If we're looking for value:
6180                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6181                OldList * specs;
6182                OldList * unionDefs = MkList();
6183                OldList * statements = MkList();
6184                context = PushContext();
6185                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6186                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6187                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6188                exp.type = extensionCompoundExp;
6189                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6190                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6191                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6192                exp.compound.compound.context = context;
6193                PopContext(context);
6194             }
6195             break;
6196          case classType:
6197          {
6198             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6199             {
6200                exp.type = bracketsExp;
6201                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6202                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6203                ProcessExpressionType(exp.list->first);
6204                break;
6205             }
6206             else
6207             {
6208                exp.type = bracketsExp;
6209                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6210                newExp.needCast = true;
6211                ProcessExpressionType(exp.list->first);
6212                break;
6213             }
6214          }
6215          default:
6216          {
6217             if(exp.expType.kind == templateType)
6218             {
6219                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6220                if(type)
6221                {
6222                   FreeType(exp.destType);
6223                   FreeType(exp.expType);
6224                   delete newExp;
6225                   break;
6226                }
6227             }
6228             if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6229             {
6230                exp.type = opExp;
6231                exp.op.op = '*';
6232                exp.op.exp1 = null;
6233                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6234                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6235             }
6236             else
6237             {
6238                char typeString[1024];
6239                Declarator decl;
6240                OldList * specs = MkList();
6241                typeString[0] = '\0';
6242                PrintType(exp.expType, typeString, false, false);
6243                decl = SpecDeclFromString(typeString, specs, null);
6244
6245                exp.type = castExp;
6246                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6247                exp.cast.typeName = MkTypeName(specs, decl);
6248                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6249                exp.cast.exp.needCast = true;
6250             }
6251             break;
6252          }
6253       }
6254    }
6255 }
6256 // TODO: The Symbol tree should be reorganized by namespaces
6257 // Name Space:
6258 //    - Tree of all symbols within (stored without namespace)
6259 //    - Tree of sub-namespaces
6260
6261 static Symbol ScanWithNameSpace(BinaryTree tree, char * nameSpace, char * name)
6262 {
6263    int nsLen = strlen(nameSpace);
6264    Symbol symbol;
6265    // Start at the name space prefix
6266    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6267    {
6268       char * s = symbol.string;
6269       if(!strncmp(s, nameSpace, nsLen))
6270       {
6271          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6272          int c;
6273          char * namePart;
6274          for(c = strlen(s)-1; c >= 0; c--)
6275             if(s[c] == ':')
6276                break;
6277
6278          namePart = s+c+1;
6279          if(!strcmp(namePart, name))
6280          {
6281             // TODO: Error on ambiguity
6282             return symbol;
6283          }
6284       }
6285       else
6286          break;
6287    }
6288    return null;
6289 }
6290
6291 static Symbol FindWithNameSpace(BinaryTree tree, char * name)
6292 {
6293    int c;
6294    char nameSpace[1024];
6295    char * namePart;
6296    bool gotColon = false;
6297
6298    nameSpace[0] = '\0';
6299    for(c = strlen(name)-1; c >= 0; c--)
6300       if(name[c] == ':')
6301       {
6302          gotColon = true;
6303          break;
6304       }
6305
6306    namePart = name+c+1;
6307    while(c >= 0 && name[c] == ':') c--;
6308    if(c >= 0)
6309    {
6310       // Try an exact match first
6311       Symbol symbol = (Symbol)tree.FindString(name);
6312       if(symbol)
6313          return symbol;
6314
6315       // Namespace specified
6316       memcpy(nameSpace, name, c + 1);
6317       nameSpace[c+1] = 0;
6318
6319       return ScanWithNameSpace(tree, nameSpace, namePart);
6320    }
6321    else if(gotColon)
6322    {
6323       // Looking for a global symbol, e.g. ::Sleep()
6324       Symbol symbol = (Symbol)tree.FindString(namePart);
6325       return symbol;
6326    }
6327    else
6328    {
6329       // Name only (no namespace specified)
6330       Symbol symbol = (Symbol)tree.FindString(namePart);
6331       if(symbol)
6332          return symbol;
6333       return ScanWithNameSpace(tree, "", namePart);
6334    }
6335    return null;
6336 }
6337
6338 static void ProcessDeclaration(Declaration decl);
6339
6340 /*static */Symbol FindSymbol(char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6341 {
6342 #ifdef _DEBUG
6343    //Time startTime = GetTime();
6344 #endif
6345    // Optimize this later? Do this before/less?
6346    Context ctx;
6347    Symbol symbol = null;
6348    // First, check if the identifier is declared inside the function
6349    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6350
6351    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6352    {
6353       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6354       {
6355          symbol = null;
6356          if(thisNameSpace)
6357          {
6358             char curName[1024];
6359             strcpy(curName, thisNameSpace);
6360             strcat(curName, "::");
6361             strcat(curName, name);
6362             // Try to resolve in current namespace first
6363             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6364          }
6365          if(!symbol)
6366             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6367       }
6368       else
6369          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6370
6371       if(symbol || ctx == endContext) break;
6372    }
6373    if(inCompiler && curExternal && symbol && ctx == globalContext && curExternal.symbol && symbol.id > curExternal.symbol.idCode && symbol.pointerExternal)
6374    {
6375       if(symbol.pointerExternal.type == functionExternal)
6376       {
6377          FunctionDefinition function = symbol.pointerExternal.function;
6378
6379          // Modified this recently...
6380          Context tmpContext = curContext;
6381          curContext = null;
6382          symbol.pointerExternal = MkExternalDeclaration(MkDeclaration(CopyList(function.specifiers, CopySpecifier), MkListOne(MkInitDeclarator(CopyDeclarator(function.declarator), null))));
6383          curContext = tmpContext;
6384
6385          symbol.pointerExternal.symbol = symbol;
6386
6387          // TESTING THIS:
6388          DeclareType(symbol.type, true, true);
6389
6390          ast->Insert(curExternal.prev, symbol.pointerExternal);
6391
6392          symbol.id = curExternal.symbol.idCode;
6393
6394       }
6395       else if(symbol.pointerExternal.type == declarationExternal && curExternal.symbol.idCode < symbol.pointerExternal.symbol.id) // Added id comparison because Global Function prototypes were broken
6396       {
6397          ast->Move(symbol.pointerExternal, curExternal.prev);
6398          symbol.id = curExternal.symbol.idCode;
6399       }
6400    }
6401 #ifdef _DEBUG
6402    //findSymbolTotalTime += GetTime() - startTime;
6403 #endif
6404    return symbol;
6405 }
6406
6407 static void GetTypeSpecs(Type type, OldList * specs)
6408 {
6409    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6410    switch(type.kind)
6411    {
6412       case classType:
6413       {
6414          if(type._class.registered)
6415          {
6416             if(!type._class.registered.dataType)
6417                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6418             GetTypeSpecs(type._class.registered.dataType, specs);
6419          }
6420          break;
6421       }
6422       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6423       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6424       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6425       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6426       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6427       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6428       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6429       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6430       case intType:
6431       default:
6432          ListAdd(specs, MkSpecifier(INT)); break;
6433    }
6434 }
6435
6436 static void PrintArraySize(Type arrayType, char * string)
6437 {
6438    char size[256];
6439    size[0] = '\0';
6440    strcat(size, "[");
6441    if(arrayType.enumClass)
6442       strcat(size, arrayType.enumClass.string);
6443    else if(arrayType.arraySizeExp)
6444       PrintExpression(arrayType.arraySizeExp, size);
6445    strcat(size, "]");
6446    strcat(string, size);
6447 }
6448
6449 // WARNING : This function expects a null terminated string since it recursively concatenate...
6450 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6451 {
6452    if(type)
6453    {
6454       if(printConst && type.constant)
6455          strcat(string, "const ");
6456       switch(type.kind)
6457       {
6458          case classType:
6459          {
6460             Symbol c = type._class;
6461             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6462             //       look into merging with thisclass ?
6463             if(type.classObjectType == typedObject)
6464                strcat(string, "typed_object");
6465             else if(type.classObjectType == anyObject)
6466                strcat(string, "any_object");
6467             else
6468             {
6469                if(c && c.string)
6470                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6471             }
6472             if(type.byReference)
6473                strcat(string, " &");
6474             break;
6475          }
6476          case voidType: strcat(string, "void"); break;
6477          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6478          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6479          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6480          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6481          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6482          case _BoolType: strcat(string, "_Bool"); break;
6483          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6484          case floatType: strcat(string, "float"); break;
6485          case doubleType: strcat(string, "double"); break;
6486          case structType:
6487             if(type.enumName)
6488             {
6489                strcat(string, "struct ");
6490                strcat(string, type.enumName);
6491             }
6492             else if(type.typeName)
6493                strcat(string, type.typeName);
6494             else
6495             {
6496                Type member;
6497                strcat(string, "struct { ");
6498                for(member = type.members.first; member; member = member.next)
6499                {
6500                   PrintType(member, string, true, fullName);
6501                   strcat(string,"; ");
6502                }
6503                strcat(string,"}");
6504             }
6505             break;
6506          case unionType:
6507             if(type.enumName)
6508             {
6509                strcat(string, "union ");
6510                strcat(string, type.enumName);
6511             }
6512             else if(type.typeName)
6513                strcat(string, type.typeName);
6514             else
6515             {
6516                strcat(string, "union ");
6517                strcat(string,"(unnamed)");
6518             }
6519             break;
6520          case enumType:
6521             if(type.enumName)
6522             {
6523                strcat(string, "enum ");
6524                strcat(string, type.enumName);
6525             }
6526             else if(type.typeName)
6527                strcat(string, type.typeName);
6528             else
6529                strcat(string, "int"); // "enum");
6530             break;
6531          case ellipsisType:
6532             strcat(string, "...");
6533             break;
6534          case subClassType:
6535             strcat(string, "subclass(");
6536             strcat(string, type._class ? type._class.string : "int");
6537             strcat(string, ")");
6538             break;
6539          case templateType:
6540             strcat(string, type.templateParameter.identifier.string);
6541             break;
6542          case thisClassType:
6543             strcat(string, "thisclass");
6544             break;
6545          case vaListType:
6546             strcat(string, "__builtin_va_list");
6547             break;
6548       }
6549    }
6550 }
6551
6552 static void PrintName(Type type, char * string, bool fullName)
6553 {
6554    if(type.name && type.name[0])
6555    {
6556       if(fullName)
6557          strcat(string, type.name);
6558       else
6559       {
6560          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
6561          if(name) name += 2; else name = type.name;
6562          strcat(string, name);
6563       }
6564    }
6565 }
6566
6567 static void PrintAttribs(Type type, char * string)
6568 {
6569    if(type)
6570    {
6571       if(type.dllExport)   strcat(string, "dllexport ");
6572       if(type.attrStdcall) strcat(string, "stdcall ");
6573    }
6574 }
6575
6576 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
6577 {
6578    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
6579    {
6580       Type attrType = null;
6581       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
6582          PrintAttribs(type, string);
6583       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
6584          strcat(string, " const");
6585       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
6586       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
6587          strcat(string, " (");
6588       if(type.kind == pointerType)
6589       {
6590          if(type.type.kind == functionType || type.type.kind == methodType)
6591             PrintAttribs(type.type, string);
6592       }
6593       if(type.kind == pointerType)
6594       {
6595          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
6596             strcat(string, "*");
6597          else
6598             strcat(string, " *");
6599       }
6600       if(printConst && type.constant && type.kind == pointerType)
6601          strcat(string, " const");
6602    }
6603    else
6604       PrintTypeSpecs(type, string, fullName, printConst);
6605 }
6606
6607 static void PostPrintType(Type type, char * string, bool fullName)
6608 {
6609    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
6610       strcat(string, ")");
6611    if(type.kind == arrayType)
6612       PrintArraySize(type, string);
6613    else if(type.kind == functionType)
6614    {
6615       Type param;
6616       strcat(string, "(");
6617       for(param = type.params.first; param; param = param.next)
6618       {
6619          PrintType(param, string, true, fullName);
6620          if(param.next) strcat(string, ", ");
6621       }
6622       strcat(string, ")");
6623    }
6624    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
6625       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
6626 }
6627
6628 // *****
6629 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
6630 // *****
6631 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
6632 {
6633    PrePrintType(type, string, fullName, null, printConst);
6634
6635    if(type.thisClass || (printName && type.name && type.name[0]))
6636       strcat(string, " ");
6637    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
6638    {
6639       Symbol _class = type.thisClass;
6640       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
6641       {
6642          if(type.classObjectType == classPointer)
6643             strcat(string, "class");
6644          else
6645             strcat(string, type.byReference ? "typed_object&" : "typed_object");
6646       }
6647       else if(_class && _class.string)
6648       {
6649          String s = _class.string;
6650          if(fullName)
6651             strcat(string, s);
6652          else
6653          {
6654             char * name = RSearchString(s, "::", strlen(s), true, false);
6655             if(name) name += 2; else name = s;
6656             strcat(string, name);
6657          }
6658       }
6659       strcat(string, "::");
6660    }
6661
6662    if(printName && type.name)
6663       PrintName(type, string, fullName);
6664    PostPrintType(type, string, fullName);
6665    if(type.bitFieldCount)
6666    {
6667       char count[100];
6668       sprintf(count, ":%d", type.bitFieldCount);
6669       strcat(string, count);
6670    }
6671 }
6672
6673 void PrintType(Type type, char * string, bool printName, bool fullName)
6674 {
6675    _PrintType(type, string, printName, fullName, true);
6676 }
6677
6678 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
6679 {
6680    _PrintType(type, string, printName, fullName, false);
6681 }
6682
6683 static Type FindMember(Type type, char * string)
6684 {
6685    Type memberType;
6686    for(memberType = type.members.first; memberType; memberType = memberType.next)
6687    {
6688       if(!memberType.name)
6689       {
6690          Type subType = FindMember(memberType, string);
6691          if(subType)
6692             return subType;
6693       }
6694       else if(!strcmp(memberType.name, string))
6695          return memberType;
6696    }
6697    return null;
6698 }
6699
6700 Type FindMemberAndOffset(Type type, char * string, uint * offset)
6701 {
6702    Type memberType;
6703    for(memberType = type.members.first; memberType; memberType = memberType.next)
6704    {
6705       if(!memberType.name)
6706       {
6707          Type subType = FindMember(memberType, string);
6708          if(subType)
6709          {
6710             *offset += memberType.offset;
6711             return subType;
6712          }
6713       }
6714       else if(!strcmp(memberType.name, string))
6715       {
6716          *offset += memberType.offset;
6717          return memberType;
6718       }
6719    }
6720    return null;
6721 }
6722
6723 Expression ParseExpressionString(char * expression)
6724 {
6725    fileInput = TempFile { };
6726    fileInput.Write(expression, 1, strlen(expression));
6727    fileInput.Seek(0, start);
6728
6729    echoOn = false;
6730    parsedExpression = null;
6731    resetScanner();
6732    expression_yyparse();
6733    delete fileInput;
6734
6735    return parsedExpression;
6736 }
6737
6738 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
6739 {
6740    Identifier id = exp.identifier;
6741    Method method = null;
6742    Property prop = null;
6743    DataMember member = null;
6744    ClassProperty classProp = null;
6745
6746    if(_class && _class.type == enumClass)
6747    {
6748       NamedLink value = null;
6749       Class enumClass = eSystem_FindClass(privateModule, "enum");
6750       if(enumClass)
6751       {
6752          Class baseClass;
6753          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
6754          {
6755             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
6756             for(value = e.values.first; value; value = value.next)
6757             {
6758                if(!strcmp(value.name, id.string))
6759                   break;
6760             }
6761             if(value)
6762             {
6763                char constant[256];
6764
6765                FreeExpContents(exp);
6766
6767                exp.type = constantExp;
6768                exp.isConstant = true;
6769                if(!strcmp(baseClass.dataTypeString, "int"))
6770                   sprintf(constant, "%d",(int)value.data);
6771                else
6772                   sprintf(constant, "0x%X",(int)value.data);
6773                exp.constant = CopyString(constant);
6774                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
6775                exp.expType = MkClassType(baseClass.fullName);
6776                break;
6777             }
6778          }
6779       }
6780       if(value)
6781          return true;
6782    }
6783    if((method = eClass_FindMethod(_class, id.string, privateModule)))
6784    {
6785       ProcessMethodType(method);
6786       exp.expType = Type
6787       {
6788          refCount = 1;
6789          kind = methodType;
6790          method = method;
6791          // Crash here?
6792          // TOCHECK: Put it back to what it was...
6793          // methodClass = _class;
6794          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
6795       };
6796       //id._class = null;
6797       return true;
6798    }
6799    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
6800    {
6801       if(!prop.dataType)
6802          ProcessPropertyType(prop);
6803       exp.expType = prop.dataType;
6804       if(prop.dataType) prop.dataType.refCount++;
6805       return true;
6806    }
6807    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
6808    {
6809       if(!member.dataType)
6810          member.dataType = ProcessTypeString(member.dataTypeString, false);
6811       exp.expType = member.dataType;
6812       if(member.dataType) member.dataType.refCount++;
6813       return true;
6814    }
6815    else if((classProp = eClass_FindClassProperty(_class, id.string)))
6816    {
6817       if(!classProp.dataType)
6818          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
6819
6820       if(classProp.constant)
6821       {
6822          FreeExpContents(exp);
6823
6824          exp.isConstant = true;
6825          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
6826          {
6827             //char constant[256];
6828             exp.type = stringExp;
6829             exp.constant = QMkString((char *)classProp.Get(_class));
6830          }
6831          else
6832          {
6833             char constant[256];
6834             exp.type = constantExp;
6835             sprintf(constant, "%d", (int)classProp.Get(_class));
6836             exp.constant = CopyString(constant);
6837          }
6838       }
6839       else
6840       {
6841          // TO IMPLEMENT...
6842       }
6843
6844       exp.expType = classProp.dataType;
6845       if(classProp.dataType) classProp.dataType.refCount++;
6846       return true;
6847    }
6848    return false;
6849 }
6850
6851 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
6852 {
6853    BinaryTree * tree = &nameSpace.functions;
6854    GlobalData data = (GlobalData)tree->FindString(name);
6855    NameSpace * child;
6856    if(!data)
6857    {
6858       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
6859       {
6860          data = ScanGlobalData(child, name);
6861          if(data)
6862             break;
6863       }
6864    }
6865    return data;
6866 }
6867
6868 static GlobalData FindGlobalData(char * name)
6869 {
6870    int start = 0, c;
6871    NameSpace * nameSpace;
6872    nameSpace = globalData;
6873    for(c = 0; name[c]; c++)
6874    {
6875       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
6876       {
6877          NameSpace * newSpace;
6878          char * spaceName = new char[c - start + 1];
6879          strncpy(spaceName, name + start, c - start);
6880          spaceName[c-start] = '\0';
6881          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
6882          delete spaceName;
6883          if(!newSpace)
6884             return null;
6885          nameSpace = newSpace;
6886          if(name[c] == ':') c++;
6887          start = c+1;
6888       }
6889    }
6890    if(c - start)
6891    {
6892       return ScanGlobalData(nameSpace, name + start);
6893    }
6894    return null;
6895 }
6896
6897 static int definedExpStackPos;
6898 static void * definedExpStack[512];
6899
6900 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
6901 void ReplaceExpContents(Expression checkedExp, Expression newExp)
6902 {
6903    Expression prev = checkedExp.prev, next = checkedExp.next;
6904
6905    FreeExpContents(checkedExp);
6906    FreeType(checkedExp.expType);
6907    FreeType(checkedExp.destType);
6908
6909    *checkedExp = *newExp;
6910
6911    delete newExp;
6912
6913    checkedExp.prev = prev;
6914    checkedExp.next = next;
6915 }
6916
6917 void ApplyAnyObjectLogic(Expression e)
6918 {
6919    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
6920 #ifdef _DEBUG
6921    char debugExpString[4096];
6922    debugExpString[0] = '\0';
6923    PrintExpression(e, debugExpString);
6924 #endif
6925
6926    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
6927    {
6928       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
6929       //ellipsisDestType = destType;
6930       if(e && e.expType)
6931       {
6932          Type type = e.expType;
6933          Class _class = null;
6934          //Type destType = e.destType;
6935
6936          if(type.kind == classType && type._class && type._class.registered)
6937          {
6938             _class = type._class.registered;
6939          }
6940          else if(type.kind == subClassType)
6941          {
6942             _class = FindClass("ecere::com::Class").registered;
6943          }
6944          else
6945          {
6946             char string[1024] = "";
6947             Symbol classSym;
6948
6949             PrintTypeNoConst(type, string, false, true);
6950             classSym = FindClass(string);
6951             if(classSym) _class = classSym.registered;
6952          }
6953
6954          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...
6955             (!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))) ||
6956             destType.byReference)))
6957          {
6958             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
6959             {
6960                Expression checkedExp = e, newExp;
6961
6962                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
6963                {
6964                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
6965                   {
6966                      if(checkedExp.type == extensionCompoundExp)
6967                      {
6968                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
6969                      }
6970                      else
6971                         checkedExp = checkedExp.list->last;
6972                   }
6973                   else if(checkedExp.type == castExp)
6974                      checkedExp = checkedExp.cast.exp;
6975                }
6976
6977                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
6978                {
6979                   newExp = checkedExp.op.exp2;
6980                   checkedExp.op.exp2 = null;
6981                   FreeExpContents(checkedExp);
6982
6983                   if(e.expType && e.expType.passAsTemplate)
6984                   {
6985                      char size[100];
6986                      ComputeTypeSize(e.expType);
6987                      sprintf(size, "%d", e.expType.size);
6988                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
6989                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
6990                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
6991                   }
6992
6993                   ReplaceExpContents(checkedExp, newExp);
6994                   e.byReference = true;
6995                }
6996                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
6997                {
6998                   Expression checkedExp, newExp;
6999
7000                   {
7001                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7002                      bool hasAddress =
7003                         e.type == identifierExp ||
7004                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7005                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7006                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7007                         e.type == indexExp;
7008
7009                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7010                      {
7011                         Context context = PushContext();
7012                         Declarator decl;
7013                         OldList * specs = MkList();
7014                         char typeString[1024];
7015                         Expression newExp { };
7016
7017                         typeString[0] = '\0';
7018                         *newExp = *e;
7019
7020                         //if(e.destType) e.destType.refCount++;
7021                         // if(exp.expType) exp.expType.refCount++;
7022                         newExp.prev = null;
7023                         newExp.next = null;
7024                         newExp.expType = null;
7025
7026                         PrintTypeNoConst(e.expType, typeString, false, true);
7027                         decl = SpecDeclFromString(typeString, specs, null);
7028                         newExp.destType = ProcessType(specs, decl);
7029
7030                         curContext = context;
7031
7032                         // We need a current compound for this
7033                         if(curCompound)
7034                         {
7035                            char name[100];
7036                            OldList * stmts = MkList();
7037                            e.type = extensionCompoundExp;
7038                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7039                            if(!curCompound.compound.declarations)
7040                               curCompound.compound.declarations = MkList();
7041                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7042                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7043                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7044                            e.compound = MkCompoundStmt(null, stmts);
7045                         }
7046                         else
7047                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7048
7049                         /*
7050                         e.compound = MkCompoundStmt(
7051                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7052                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7053
7054                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7055                         */
7056
7057                         {
7058                            Type type = e.destType;
7059                            e.destType = { };
7060                            CopyTypeInto(e.destType, type);
7061                            e.destType.refCount = 1;
7062                            e.destType.classObjectType = none;
7063                            FreeType(type);
7064                         }
7065
7066                         e.compound.compound.context = context;
7067                         PopContext(context);
7068                         curContext = context.parent;
7069                      }
7070                   }
7071
7072                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7073                   checkedExp = e;
7074                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7075                   {
7076                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7077                      {
7078                         if(checkedExp.type == extensionCompoundExp)
7079                         {
7080                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7081                         }
7082                         else
7083                            checkedExp = checkedExp.list->last;
7084                      }
7085                      else if(checkedExp.type == castExp)
7086                         checkedExp = checkedExp.cast.exp;
7087                   }
7088                   {
7089                      Expression operand { };
7090                      operand = *checkedExp;
7091                      checkedExp.destType = null;
7092                      checkedExp.expType = null;
7093                      checkedExp.Clear();
7094                      checkedExp.type = opExp;
7095                      checkedExp.op.op = '&';
7096                      checkedExp.op.exp1 = null;
7097                      checkedExp.op.exp2 = operand;
7098
7099                      //newExp = MkExpOp(null, '&', checkedExp);
7100                   }
7101                   //ReplaceExpContents(checkedExp, newExp);
7102                }
7103             }
7104          }
7105       }
7106    }
7107    {
7108       // If expression type is a simple class, make it an address
7109       // FixReference(e, true);
7110    }
7111 //#if 0
7112    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7113       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7114          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7115    {
7116       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"))
7117       {
7118          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7119       }
7120       else
7121       {
7122          Expression thisExp { };
7123
7124          *thisExp = *e;
7125          thisExp.prev = null;
7126          thisExp.next = null;
7127          e.Clear();
7128
7129          e.type = bracketsExp;
7130          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7131          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7132             ((Expression)e.list->first).byReference = true;
7133
7134          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7135          {
7136             e.expType = thisExp.expType;
7137             e.expType.refCount++;
7138          }
7139          else*/
7140          {
7141             e.expType = { };
7142             CopyTypeInto(e.expType, thisExp.expType);
7143             e.expType.byReference = false;
7144             e.expType.refCount = 1;
7145
7146             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7147                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7148             {
7149                e.expType.classObjectType = none;
7150             }
7151          }
7152       }
7153    }
7154 // TOFIX: Try this for a nice IDE crash!
7155 //#endif
7156    // The other way around
7157    else
7158 //#endif
7159    if(destType && e.expType &&
7160          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7161          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7162          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7163    {
7164       if(destType.kind == ellipsisType)
7165       {
7166          Compiler_Error($"Unspecified type\n");
7167       }
7168       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7169       {
7170          bool byReference = e.expType.byReference;
7171          Expression thisExp { };
7172          Declarator decl;
7173          OldList * specs = MkList();
7174          char typeString[1024]; // Watch buffer overruns
7175          Type type;
7176          ClassObjectType backupClassObjectType;
7177          bool backupByReference;
7178
7179          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7180             type = e.expType;
7181          else
7182             type = destType;
7183
7184          backupClassObjectType = type.classObjectType;
7185          backupByReference = type.byReference;
7186
7187          type.classObjectType = none;
7188          type.byReference = false;
7189
7190          typeString[0] = '\0';
7191          PrintType(type, typeString, false, true);
7192          decl = SpecDeclFromString(typeString, specs, null);
7193
7194          type.classObjectType = backupClassObjectType;
7195          type.byReference = backupByReference;
7196
7197          *thisExp = *e;
7198          thisExp.prev = null;
7199          thisExp.next = null;
7200          e.Clear();
7201
7202          if( ( type.kind == classType && type._class && type._class.registered &&
7203                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7204                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7205              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7206              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7207          {
7208             e.type = opExp;
7209             e.op.op = '*';
7210             e.op.exp1 = null;
7211             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7212
7213             e.expType = { };
7214             CopyTypeInto(e.expType, type);
7215             e.expType.byReference = false;
7216             e.expType.refCount = 1;
7217          }
7218          else
7219          {
7220             e.type = castExp;
7221             e.cast.typeName = MkTypeName(specs, decl);
7222             e.cast.exp = thisExp;
7223             e.byReference = true;
7224             e.expType = type;
7225             type.refCount++;
7226          }
7227          e.destType = destType;
7228          destType.refCount++;
7229       }
7230    }
7231 }
7232
7233 void ProcessExpressionType(Expression exp)
7234 {
7235    bool unresolved = false;
7236    Location oldyylloc = yylloc;
7237    bool notByReference = false;
7238 #ifdef _DEBUG
7239    char debugExpString[4096];
7240    debugExpString[0] = '\0';
7241    PrintExpression(exp, debugExpString);
7242 #endif
7243    if(!exp || exp.expType)
7244       return;
7245
7246    //eSystem_Logf("%s\n", expString);
7247
7248    // Testing this here
7249    yylloc = exp.loc;
7250    switch(exp.type)
7251    {
7252       case identifierExp:
7253       {
7254          Identifier id = exp.identifier;
7255          if(!id) return;
7256
7257          // DOING THIS LATER NOW...
7258          if(id._class && id._class.name)
7259          {
7260             id.classSym = id._class.symbol; // FindClass(id._class.name);
7261             /* TODO: Name Space Fix ups
7262             if(!id.classSym)
7263                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7264             */
7265          }
7266
7267          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7268          {
7269             exp.expType = ProcessTypeString("Module", true);
7270             break;
7271          }
7272          else */if(strstr(id.string, "__ecereClass") == id.string)
7273          {
7274             exp.expType = ProcessTypeString("ecere::com::Class", true);
7275             break;
7276          }
7277          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7278          {
7279             // Added this here as well
7280             ReplaceClassMembers(exp, thisClass);
7281             if(exp.type != identifierExp)
7282             {
7283                ProcessExpressionType(exp);
7284                break;
7285             }
7286
7287             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7288                break;
7289          }
7290          else
7291          {
7292             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7293             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7294             if(!symbol/* && exp.destType*/)
7295             {
7296                if(exp.destType && CheckExpressionType(exp, exp.destType, false))
7297                   break;
7298                else
7299                {
7300                   if(thisClass)
7301                   {
7302                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7303                      if(exp.type != identifierExp)
7304                      {
7305                         ProcessExpressionType(exp);
7306                         break;
7307                      }
7308                   }
7309                   // Static methods called from inside the _class
7310                   else if(currentClass && !id._class)
7311                   {
7312                      if(ResolveIdWithClass(exp, currentClass, true))
7313                         break;
7314                   }
7315                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7316                }
7317             }
7318
7319             // If we manage to resolve this symbol
7320             if(symbol)
7321             {
7322                Type type = symbol.type;
7323                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7324
7325                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7326                {
7327                   Context context = SetupTemplatesContext(_class);
7328                   type = ReplaceThisClassType(_class);
7329                   FinishTemplatesContext(context);
7330                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7331                }
7332
7333                FreeSpecifier(id._class);
7334                id._class = null;
7335                delete id.string;
7336                id.string = CopyString(symbol.string);
7337
7338                id.classSym = null;
7339                exp.expType = type;
7340                if(type)
7341                   type.refCount++;
7342                if(type && (type.kind == enumType || (_class && _class.type == enumClass)))
7343                   // Add missing cases here... enum Classes...
7344                   exp.isConstant = true;
7345
7346                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7347                if(symbol.isParam || !strcmp(id.string, "this"))
7348                {
7349                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7350                      exp.byReference = true;
7351
7352                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7353                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7354                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7355                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7356                   {
7357                      Identifier id = exp.identifier;
7358                      exp.type = bracketsExp;
7359                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7360                   }*/
7361                }
7362
7363                if(symbol.isIterator)
7364                {
7365                   if(symbol.isIterator == 3)
7366                   {
7367                      exp.type = bracketsExp;
7368                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7369                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7370                      exp.expType = null;
7371                      ProcessExpressionType(exp);
7372                   }
7373                   else if(symbol.isIterator != 4)
7374                   {
7375                      exp.type = memberExp;
7376                      exp.member.exp = MkExpIdentifier(exp.identifier);
7377                      exp.member.exp.expType = exp.expType;
7378                      /*if(symbol.isIterator == 6)
7379                         exp.member.member = MkIdentifier("key");
7380                      else*/
7381                         exp.member.member = MkIdentifier("data");
7382                      exp.expType = null;
7383                      ProcessExpressionType(exp);
7384                   }
7385                }
7386                break;
7387             }
7388             else
7389             {
7390                DefinedExpression definedExp = null;
7391                if(thisNameSpace && !(id._class && !id._class.name))
7392                {
7393                   char name[1024];
7394                   strcpy(name, thisNameSpace);
7395                   strcat(name, "::");
7396                   strcat(name, id.string);
7397                   definedExp = eSystem_FindDefine(privateModule, name);
7398                }
7399                if(!definedExp)
7400                   definedExp = eSystem_FindDefine(privateModule, id.string);
7401                if(definedExp)
7402                {
7403                   int c;
7404                   for(c = 0; c<definedExpStackPos; c++)
7405                      if(definedExpStack[c] == definedExp)
7406                         break;
7407                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7408                   {
7409                      Location backupYylloc = yylloc;
7410                      definedExpStack[definedExpStackPos++] = definedExp;
7411                      fileInput = TempFile { };
7412                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7413                      fileInput.Seek(0, start);
7414
7415                      echoOn = false;
7416                      parsedExpression = null;
7417                      resetScanner();
7418                      expression_yyparse();
7419                      delete fileInput;
7420
7421                      yylloc = backupYylloc;
7422
7423                      if(parsedExpression)
7424                      {
7425                         FreeIdentifier(id);
7426                         exp.type = bracketsExp;
7427                         exp.list = MkListOne(parsedExpression);
7428                         parsedExpression.loc = yylloc;
7429                         ProcessExpressionType(exp);
7430                         definedExpStackPos--;
7431                         return;
7432                      }
7433                      definedExpStackPos--;
7434                   }
7435                   else
7436                   {
7437                      if(inCompiler)
7438                      {
7439                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7440                      }
7441                   }
7442                }
7443                else
7444                {
7445                   GlobalData data = null;
7446                   if(thisNameSpace && !(id._class && !id._class.name))
7447                   {
7448                      char name[1024];
7449                      strcpy(name, thisNameSpace);
7450                      strcat(name, "::");
7451                      strcat(name, id.string);
7452                      data = FindGlobalData(name);
7453                   }
7454                   if(!data)
7455                      data = FindGlobalData(id.string);
7456                   if(data)
7457                   {
7458                      DeclareGlobalData(data);
7459                      exp.expType = data.dataType;
7460                      if(data.dataType) data.dataType.refCount++;
7461
7462                      delete id.string;
7463                      id.string = CopyString(data.fullName);
7464                      FreeSpecifier(id._class);
7465                      id._class = null;
7466
7467                      break;
7468                   }
7469                   else
7470                   {
7471                      GlobalFunction function = null;
7472                      if(thisNameSpace && !(id._class && !id._class.name))
7473                      {
7474                         char name[1024];
7475                         strcpy(name, thisNameSpace);
7476                         strcat(name, "::");
7477                         strcat(name, id.string);
7478                         function = eSystem_FindFunction(privateModule, name);
7479                      }
7480                      if(!function)
7481                         function = eSystem_FindFunction(privateModule, id.string);
7482                      if(function)
7483                      {
7484                         char name[1024];
7485                         delete id.string;
7486                         id.string = CopyString(function.name);
7487                         name[0] = 0;
7488
7489                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
7490                            strcpy(name, "__ecereFunction_");
7491                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
7492                         if(DeclareFunction(function, name))
7493                         {
7494                            delete id.string;
7495                            id.string = CopyString(name);
7496                         }
7497                         exp.expType = function.dataType;
7498                         if(function.dataType) function.dataType.refCount++;
7499
7500                         FreeSpecifier(id._class);
7501                         id._class = null;
7502
7503                         break;
7504                      }
7505                   }
7506                }
7507             }
7508          }
7509          unresolved = true;
7510          break;
7511       }
7512       case instanceExp:
7513       {
7514          Class _class;
7515          // Symbol classSym;
7516
7517          if(!exp.instance._class)
7518          {
7519             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
7520             {
7521                exp.instance._class = MkSpecifierName(exp.destType._class.string);
7522             }
7523          }
7524
7525          //classSym = FindClass(exp.instance._class.fullName);
7526          //_class = classSym ? classSym.registered : null;
7527
7528          ProcessInstantiationType(exp.instance);
7529          exp.isConstant = exp.instance.isConstant;
7530
7531          /*
7532          if(_class.type == unitClass && _class.base.type != systemClass)
7533          {
7534             {
7535                Type destType = exp.destType;
7536
7537                exp.destType = MkClassType(_class.base.fullName);
7538                exp.expType = MkClassType(_class.fullName);
7539                CheckExpressionType(exp, exp.destType, true);
7540
7541                exp.destType = destType;
7542             }
7543             exp.expType = MkClassType(_class.fullName);
7544          }
7545          else*/
7546          if(exp.instance._class)
7547          {
7548             exp.expType = MkClassType(exp.instance._class.name);
7549             /*if(exp.expType._class && exp.expType._class.registered &&
7550                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
7551                exp.expType.byReference = true;*/
7552          }
7553          break;
7554       }
7555       case constantExp:
7556       {
7557          if(!exp.expType)
7558          {
7559             Type type
7560             {
7561                refCount = 1;
7562                constant = true;
7563             };
7564             exp.expType = type;
7565
7566             if(exp.constant[0] == '\'')
7567             {
7568                if((int)((byte *)exp.constant)[1] > 127)
7569                {
7570                   int nb;
7571                   unichar ch = UTF8GetChar(exp.constant + 1, &nb);
7572                   if(nb < 2) ch = exp.constant[1];
7573                   delete exp.constant;
7574                   exp.constant = PrintUInt(ch);
7575                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
7576                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
7577                   type._class = FindClass("unichar");
7578
7579                   type.isSigned = false;
7580                }
7581                else
7582                {
7583                   type.kind = charType;
7584                   type.isSigned = true;
7585                }
7586             }
7587             else if(strchr(exp.constant, '.'))
7588             {
7589                char ch = exp.constant[strlen(exp.constant)-1];
7590                if(ch == 'f')
7591                   type.kind = floatType;
7592                else
7593                   type.kind = doubleType;
7594                type.isSigned = true;
7595             }
7596             else
7597             {
7598                if(exp.constant[0] == '0' && exp.constant[1])
7599                   type.isSigned = false;
7600                else if(strchr(exp.constant, 'L') || strchr(exp.constant, 'l'))
7601                   type.isSigned = false;
7602                else if(strtoll(exp.constant, null, 0) > MAXINT)
7603                   type.isSigned = false;
7604                else
7605                   type.isSigned = true;
7606                type.kind = intType;
7607             }
7608             exp.isConstant = true;
7609             if(exp.destType && exp.destType.kind == doubleType)
7610                type.kind = doubleType;
7611             else if(exp.destType && exp.destType.kind == floatType)
7612                type.kind = floatType;
7613             else if(exp.destType && exp.destType.kind == int64Type)
7614                type.kind = int64Type;
7615          }
7616          break;
7617       }
7618       case stringExp:
7619       {
7620          exp.isConstant = true;      // Why wasn't this constant?
7621          exp.expType = Type
7622          {
7623             refCount = 1;
7624             kind = pointerType;
7625             type = Type
7626             {
7627                refCount = 1;
7628                kind = charType;
7629                constant = true;
7630                isSigned = true;
7631             }
7632          };
7633          break;
7634       }
7635       case newExp:
7636       case new0Exp:
7637          ProcessExpressionType(exp._new.size);
7638          exp.expType = Type
7639          {
7640             refCount = 1;
7641             kind = pointerType;
7642             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
7643          };
7644          DeclareType(exp.expType.type, false, false);
7645          break;
7646       case renewExp:
7647       case renew0Exp:
7648          ProcessExpressionType(exp._renew.size);
7649          ProcessExpressionType(exp._renew.exp);
7650          exp.expType = Type
7651          {
7652             refCount = 1;
7653             kind = pointerType;
7654             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
7655          };
7656          DeclareType(exp.expType.type, false, false);
7657          break;
7658       case opExp:
7659       {
7660          bool assign = false, boolResult = false, boolOps = false;
7661          Type type1 = null, type2 = null;
7662          bool useDestType = false, useSideType = false;
7663          Location oldyylloc = yylloc;
7664          bool useSideUnit = false;
7665
7666          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
7667          Type dummy
7668          {
7669             count = 1;
7670             refCount = 1;
7671          };
7672
7673          switch(exp.op.op)
7674          {
7675             // Assignment Operators
7676             case '=':
7677             case MUL_ASSIGN:
7678             case DIV_ASSIGN:
7679             case MOD_ASSIGN:
7680             case ADD_ASSIGN:
7681             case SUB_ASSIGN:
7682             case LEFT_ASSIGN:
7683             case RIGHT_ASSIGN:
7684             case AND_ASSIGN:
7685             case XOR_ASSIGN:
7686             case OR_ASSIGN:
7687                assign = true;
7688                break;
7689             // boolean Operators
7690             case '!':
7691                // Expect boolean operators
7692                //boolOps = true;
7693                //boolResult = true;
7694                break;
7695             case AND_OP:
7696             case OR_OP:
7697                // Expect boolean operands
7698                boolOps = true;
7699                boolResult = true;
7700                break;
7701             // Comparisons
7702             case EQ_OP:
7703             case '<':
7704             case '>':
7705             case LE_OP:
7706             case GE_OP:
7707             case NE_OP:
7708                // Gives boolean result
7709                boolResult = true;
7710                useSideType = true;
7711                break;
7712             case '+':
7713             case '-':
7714                useSideUnit = true;
7715
7716                // Just added these... testing
7717             case '|':
7718             case '&':
7719             case '^':
7720
7721             // DANGER: Verify units
7722             case '/':
7723             case '%':
7724             case '*':
7725
7726                if(exp.op.op != '*' || exp.op.exp1)
7727                {
7728                   useSideType = true;
7729                   useDestType = true;
7730                }
7731                break;
7732
7733             /*// Implement speed etc.
7734             case '*':
7735             case '/':
7736                break;
7737             */
7738          }
7739          if(exp.op.op == '&')
7740          {
7741             // Added this here earlier for Iterator address as key
7742             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
7743             {
7744                Identifier id = exp.op.exp2.identifier;
7745                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
7746                if(symbol && symbol.isIterator == 2)
7747                {
7748                   exp.type = memberExp;
7749                   exp.member.exp = exp.op.exp2;
7750                   exp.member.member = MkIdentifier("key");
7751                   exp.expType = null;
7752                   exp.op.exp2.expType = symbol.type;
7753                   symbol.type.refCount++;
7754                   ProcessExpressionType(exp);
7755                   FreeType(dummy);
7756                   break;
7757                }
7758                // exp.op.exp2.usage.usageRef = true;
7759             }
7760          }
7761
7762          //dummy.kind = TypeDummy;
7763
7764          if(exp.op.exp1)
7765          {
7766             if(exp.destType && exp.destType.kind == classType &&
7767                exp.destType._class && exp.destType._class.registered && useDestType &&
7768
7769               ((exp.destType._class.registered.type == unitClass && useSideUnit) ||
7770                exp.destType._class.registered.type == enumClass ||
7771                exp.destType._class.registered.type == bitClass
7772                ))
7773
7774               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
7775             {
7776                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
7777                exp.op.exp1.destType = exp.destType;
7778                if(exp.destType)
7779                   exp.destType.refCount++;
7780             }
7781             else if(!assign)
7782             {
7783                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
7784                exp.op.exp1.destType = dummy;
7785                dummy.refCount++;
7786             }
7787
7788             // TESTING THIS HERE...
7789             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
7790             ProcessExpressionType(exp.op.exp1);
7791             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
7792
7793             if(exp.op.exp1.destType == dummy)
7794             {
7795                FreeType(dummy);
7796                exp.op.exp1.destType = null;
7797             }
7798             type1 = exp.op.exp1.expType;
7799          }
7800
7801          if(exp.op.exp2)
7802          {
7803             char expString[10240];
7804             expString[0] = '\0';
7805             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
7806             {
7807                if(exp.op.exp1)
7808                {
7809                   exp.op.exp2.destType = exp.op.exp1.expType;
7810                   if(exp.op.exp1.expType)
7811                      exp.op.exp1.expType.refCount++;
7812                }
7813                else
7814                {
7815                   exp.op.exp2.destType = exp.destType;
7816                   if(exp.destType)
7817                      exp.destType.refCount++;
7818                }
7819
7820                if(type1) type1.refCount++;
7821                exp.expType = type1;
7822             }
7823             else if(assign)
7824             {
7825                if(inCompiler)
7826                   PrintExpression(exp.op.exp2, expString);
7827
7828                if(type1 && type1.kind == pointerType)
7829                {
7830                   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 ||
7831                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
7832                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
7833                   else if(exp.op.op == '=')
7834                   {
7835                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
7836                      exp.op.exp2.destType = type1;
7837                      if(type1)
7838                         type1.refCount++;
7839                   }
7840                }
7841                else
7842                {
7843                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
7844                   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/* ||
7845                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
7846                   else
7847                   {
7848                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
7849                      exp.op.exp2.destType = type1;
7850                      if(type1)
7851                         type1.refCount++;
7852                   }
7853                }
7854                if(type1) type1.refCount++;
7855                exp.expType = type1;
7856             }
7857             else if(exp.destType && exp.destType.kind == classType &&
7858                exp.destType._class && exp.destType._class.registered &&
7859
7860                   ((exp.destType._class.registered.type == unitClass && useDestType && useSideUnit) ||
7861                   (exp.destType._class.registered.type == enumClass && useDestType))
7862                   )
7863             {
7864                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
7865                exp.op.exp2.destType = exp.destType;
7866                if(exp.destType)
7867                   exp.destType.refCount++;
7868             }
7869             else
7870             {
7871                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
7872                exp.op.exp2.destType = dummy;
7873                dummy.refCount++;
7874             }
7875
7876             // TESTING THIS HERE... (DANGEROUS)
7877             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
7878                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
7879             {
7880                FreeType(exp.op.exp2.destType);
7881                exp.op.exp2.destType = type1;
7882                type1.refCount++;
7883             }
7884             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
7885             ProcessExpressionType(exp.op.exp2);
7886             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
7887
7888             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
7889             {
7890                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)
7891                {
7892                   if(exp.op.op != '=' && type1.type.kind == voidType)
7893                      Compiler_Error($"void *: unknown size\n");
7894                }
7895                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||
7896                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
7897                               (exp.op.exp2.expType._class.registered.type == normalClass ||
7898                               exp.op.exp2.expType._class.registered.type == structClass ||
7899                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
7900                {
7901                   if(exp.op.op == ADD_ASSIGN)
7902                      Compiler_Error($"cannot add two pointers\n");
7903                }
7904                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
7905                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
7906                {
7907                   if(exp.op.op == ADD_ASSIGN)
7908                      Compiler_Error($"cannot add two pointers\n");
7909                }
7910                else if(inCompiler)
7911                {
7912                   char type1String[1024];
7913                   char type2String[1024];
7914                   type1String[0] = '\0';
7915                   type2String[0] = '\0';
7916
7917                   PrintType(exp.op.exp2.expType, type1String, false, true);
7918                   PrintType(type1, type2String, false, true);
7919                   ChangeCh(expString, '\n', ' ');
7920                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
7921                }
7922             }
7923
7924             if(exp.op.exp2.destType == dummy)
7925             {
7926                FreeType(dummy);
7927                exp.op.exp2.destType = null;
7928             }
7929
7930             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
7931             {
7932                type2 = { };
7933                type2.refCount = 1;
7934                CopyTypeInto(type2, exp.op.exp2.expType);
7935                type2.isSigned = true;
7936             }
7937             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
7938             {
7939                type2 = { kind = intType };
7940                type2.refCount = 1;
7941                type2.isSigned = true;
7942             }
7943             else
7944                type2 = exp.op.exp2.expType;
7945          }
7946
7947          dummy.kind = voidType;
7948
7949          if(exp.op.op == SIZEOF)
7950          {
7951             exp.expType = Type
7952             {
7953                refCount = 1;
7954                kind = intType;
7955             };
7956             exp.isConstant = true;
7957          }
7958          // Get type of dereferenced pointer
7959          else if(exp.op.op == '*' && !exp.op.exp1)
7960          {
7961             exp.expType = Dereference(type2);
7962             if(type2 && type2.kind == classType)
7963                notByReference = true;
7964          }
7965          else if(exp.op.op == '&' && !exp.op.exp1)
7966             exp.expType = Reference(type2);
7967          else if(!assign)
7968          {
7969             if(boolOps)
7970             {
7971                if(exp.op.exp1)
7972                {
7973                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
7974                   exp.op.exp1.destType = MkClassType("bool");
7975                   exp.op.exp1.destType.truth = true;
7976                   if(!exp.op.exp1.expType)
7977                      ProcessExpressionType(exp.op.exp1);
7978                   else
7979                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
7980                   FreeType(exp.op.exp1.expType);
7981                   exp.op.exp1.expType = MkClassType("bool");
7982                   exp.op.exp1.expType.truth = true;
7983                }
7984                if(exp.op.exp2)
7985                {
7986                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
7987                   exp.op.exp2.destType = MkClassType("bool");
7988                   exp.op.exp2.destType.truth = true;
7989                   if(!exp.op.exp2.expType)
7990                      ProcessExpressionType(exp.op.exp2);
7991                   else
7992                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
7993                   FreeType(exp.op.exp2.expType);
7994                   exp.op.exp2.expType = MkClassType("bool");
7995                   exp.op.exp2.expType.truth = true;
7996                }
7997             }
7998             else if(exp.op.exp1 && exp.op.exp2 &&
7999                ((useSideType /*&&
8000                      (useSideUnit ||
8001                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8002                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8003                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8004                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8005             {
8006                if(type1 && type2 &&
8007                   // If either both are class or both are not class
8008                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8009                {
8010                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8011                   exp.op.exp2.destType = type1;
8012                   type1.refCount++;
8013                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8014                   exp.op.exp1.destType = type2;
8015                   type2.refCount++;
8016                   // Warning here for adding Radians + Degrees with no destination type
8017                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8018                      type1._class.registered && type1._class.registered.type == unitClass &&
8019                      type2._class.registered && type2._class.registered.type == unitClass &&
8020                      type1._class.registered != type2._class.registered)
8021                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8022                         type1._class.string, type2._class.string, type1._class.string);
8023
8024                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8025                   {
8026                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8027                      if(argExp)
8028                      {
8029                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8030
8031                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8032                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8033                            exp.op.exp1)));
8034
8035                         ProcessExpressionType(exp.op.exp1);
8036
8037                         if(type2.kind != pointerType)
8038                         {
8039                            ProcessExpressionType(classExp);
8040
8041                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*',
8042                               // ((_class.type == noHeadClass || _class.type == normalClass) ? sizeof(void *) : type.size)
8043                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(MkExpOp(
8044                                  // noHeadClass
8045                                  MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpConstant("5")),
8046                                     OR_OP,
8047                                  // normalClass
8048                                  MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpConstant("0"))))),
8049                                     MkListOne(MkExpTypeSize(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(
8050                                        MkPointer(null, null), null)))),
8051                                        MkExpMember(classExp, MkIdentifier("typeSize"))))))));
8052
8053                            if(!exp.op.exp2.expType)
8054                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8055
8056                            ProcessExpressionType(exp.op.exp2);
8057                         }
8058                      }
8059                   }
8060
8061                   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)))
8062                   {
8063                      if(type1.kind != classType && type1.type.kind == voidType)
8064                         Compiler_Error($"void *: unknown size\n");
8065                      exp.expType = type1;
8066                      if(type1) type1.refCount++;
8067                   }
8068                   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)))
8069                   {
8070                      if(type2.kind != classType && type2.type.kind == voidType)
8071                         Compiler_Error($"void *: unknown size\n");
8072                      exp.expType = type2;
8073                      if(type2) type2.refCount++;
8074                   }
8075                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8076                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8077                   {
8078                      Compiler_Warning($"different levels of indirection\n");
8079                   }
8080                   else
8081                   {
8082                      bool success = false;
8083                      if(type1.kind == pointerType && type2.kind == pointerType)
8084                      {
8085                         if(exp.op.op == '+')
8086                            Compiler_Error($"cannot add two pointers\n");
8087                         else if(exp.op.op == '-')
8088                         {
8089                            // Pointer Subtraction gives integer
8090                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false))
8091                            {
8092                               exp.expType = Type
8093                               {
8094                                  kind = intType;
8095                                  refCount = 1;
8096                               };
8097                               success = true;
8098
8099                               if(type1.type.kind == templateType)
8100                               {
8101                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8102                                  if(argExp)
8103                                  {
8104                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8105
8106                                     ProcessExpressionType(classExp);
8107
8108                                     exp.type = bracketsExp;
8109                                     exp.list = MkListOne(MkExpOp(
8110                                        MkExpBrackets(MkListOne(MkExpOp(
8111                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8112                                              , exp.op.op,
8113                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8114
8115                                              //MkExpMember(classExp, MkIdentifier("typeSize"))
8116
8117                                              // ((_class.type == noHeadClass || _class.type == normalClass) ? sizeof(void *) : type.size)
8118                                              MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(MkExpOp(
8119                                                 // noHeadClass
8120                                                 MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpIdentifier(MkIdentifier("noHeadClass"))),
8121                                                    OR_OP,
8122                                                 // normalClass
8123                                                 MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpIdentifier(MkIdentifier("normalClass")))))),
8124                                                    MkListOne(MkExpTypeSize(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(
8125                                                       MkPointer(null, null), null)))),
8126                                                       MkExpMember(classExp, MkIdentifier("typeSize")))))
8127
8128
8129                                              ));
8130
8131                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8132                                     FreeType(dummy);
8133                                     return;
8134                                  }
8135                               }
8136                            }
8137                         }
8138                      }
8139
8140                      if(!success && exp.op.exp1.type == constantExp)
8141                      {
8142                         // If first expression is constant, try to match that first
8143                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8144                         {
8145                            if(exp.expType) FreeType(exp.expType);
8146                            exp.expType = exp.op.exp1.destType;
8147                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8148                            success = true;
8149                         }
8150                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8151                         {
8152                            if(exp.expType) FreeType(exp.expType);
8153                            exp.expType = exp.op.exp2.destType;
8154                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8155                            success = true;
8156                         }
8157                      }
8158                      else if(!success)
8159                      {
8160                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8161                         {
8162                            if(exp.expType) FreeType(exp.expType);
8163                            exp.expType = exp.op.exp2.destType;
8164                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8165                            success = true;
8166                         }
8167                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8168                         {
8169                            if(exp.expType) FreeType(exp.expType);
8170                            exp.expType = exp.op.exp1.destType;
8171                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8172                            success = true;
8173                         }
8174                      }
8175                      if(!success)
8176                      {
8177                         char expString1[10240];
8178                         char expString2[10240];
8179                         char type1[1024];
8180                         char type2[1024];
8181                         expString1[0] = '\0';
8182                         expString2[0] = '\0';
8183                         type1[0] = '\0';
8184                         type2[0] = '\0';
8185                         if(inCompiler)
8186                         {
8187                            PrintExpression(exp.op.exp1, expString1);
8188                            ChangeCh(expString1, '\n', ' ');
8189                            PrintExpression(exp.op.exp2, expString2);
8190                            ChangeCh(expString2, '\n', ' ');
8191                            PrintType(exp.op.exp1.expType, type1, false, true);
8192                            PrintType(exp.op.exp2.expType, type2, false, true);
8193                         }
8194
8195                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8196                      }
8197                   }
8198                }
8199                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8200                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8201                {
8202                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8203                   // Convert e.g. / 4 into / 4.0
8204                   exp.op.exp1.destType = type2._class.registered.dataType;
8205                   if(type2._class.registered.dataType)
8206                      type2._class.registered.dataType.refCount++;
8207                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8208                   exp.expType = type2;
8209                   if(type2) type2.refCount++;
8210                }
8211                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8212                {
8213                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8214                   // Convert e.g. / 4 into / 4.0
8215                   exp.op.exp2.destType = type1._class.registered.dataType;
8216                   if(type1._class.registered.dataType)
8217                      type1._class.registered.dataType.refCount++;
8218                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8219                   exp.expType = type1;
8220                   if(type1) type1.refCount++;
8221                }
8222                else if(type1)
8223                {
8224                   bool valid = false;
8225
8226                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8227                   {
8228                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8229
8230                      if(!type1._class.registered.dataType)
8231                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8232                      exp.op.exp2.destType = type1._class.registered.dataType;
8233                      exp.op.exp2.destType.refCount++;
8234
8235                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8236                      type2 = exp.op.exp2.destType;
8237
8238                      exp.expType = type2;
8239                      type2.refCount++;
8240                   }
8241
8242                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8243                   {
8244                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8245
8246                      if(!type2._class.registered.dataType)
8247                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8248                      exp.op.exp1.destType = type2._class.registered.dataType;
8249                      exp.op.exp1.destType.refCount++;
8250
8251                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8252                      type1 = exp.op.exp1.destType;
8253                      exp.expType = type1;
8254                      type1.refCount++;
8255                   }
8256
8257                   // TESTING THIS NEW CODE
8258                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<')
8259                   {
8260                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass && exp.op.exp2.expType)
8261                      {
8262                         if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false))
8263                         {
8264                            if(exp.expType) FreeType(exp.expType);
8265                            exp.expType = exp.op.exp1.expType;
8266                            if(exp.op.exp2.expType) exp.op.exp1.expType.refCount++;
8267                            valid = true;
8268                         }
8269                      }
8270
8271                      else if(type2 && (type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass && exp.op.exp1.expType))
8272                      {
8273                         if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false))
8274                         {
8275                            if(exp.expType) FreeType(exp.expType);
8276                            exp.expType = exp.op.exp2.expType;
8277                            if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8278                            valid = true;
8279                         }
8280                      }
8281                   }
8282
8283                   if(!valid)
8284                   {
8285                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8286                      exp.op.exp2.destType = type1;
8287                      type1.refCount++;
8288
8289                      /*
8290                      // Maybe this was meant to be an enum...
8291                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8292                      {
8293                         Type oldType = exp.op.exp2.expType;
8294                         exp.op.exp2.expType = null;
8295                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8296                            FreeType(oldType);
8297                         else
8298                            exp.op.exp2.expType = oldType;
8299                      }
8300                      */
8301
8302                      /*
8303                      // TESTING THIS HERE... LATEST ADDITION
8304                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8305                      {
8306                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8307                         exp.op.exp2.destType = type2._class.registered.dataType;
8308                         if(type2._class.registered.dataType)
8309                            type2._class.registered.dataType.refCount++;
8310                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8311
8312                         //exp.expType = type2._class.registered.dataType; //type2;
8313                         //if(type2) type2.refCount++;
8314                      }
8315
8316                      // TESTING THIS HERE... LATEST ADDITION
8317                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8318                      {
8319                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8320                         exp.op.exp1.destType = type1._class.registered.dataType;
8321                         if(type1._class.registered.dataType)
8322                            type1._class.registered.dataType.refCount++;
8323                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8324                         exp.expType = type1._class.registered.dataType; //type1;
8325                         if(type1) type1.refCount++;
8326                      }
8327                      */
8328
8329                      if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8330                      {
8331                         if(exp.expType) FreeType(exp.expType);
8332                         exp.expType = exp.op.exp2.destType;
8333                         if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8334                      }
8335                      else if(type1 && type2)
8336                      {
8337                         char expString1[10240];
8338                         char expString2[10240];
8339                         char type1String[1024];
8340                         char type2String[1024];
8341                         expString1[0] = '\0';
8342                         expString2[0] = '\0';
8343                         type1String[0] = '\0';
8344                         type2String[0] = '\0';
8345                         if(inCompiler)
8346                         {
8347                            PrintExpression(exp.op.exp1, expString1);
8348                            ChangeCh(expString1, '\n', ' ');
8349                            PrintExpression(exp.op.exp2, expString2);
8350                            ChangeCh(expString2, '\n', ' ');
8351                            PrintType(exp.op.exp1.expType, type1String, false, true);
8352                            PrintType(exp.op.exp2.expType, type2String, false, true);
8353                         }
8354
8355                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
8356
8357                         if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8358                         {
8359                            exp.expType = exp.op.exp1.expType;
8360                            if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8361                         }
8362                         else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
8363                         {
8364                            exp.expType = exp.op.exp2.expType;
8365                            if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8366                         }
8367                      }
8368                   }
8369                }
8370                else if(type2)
8371                {
8372                   // Maybe this was meant to be an enum...
8373                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
8374                   {
8375                      Type oldType = exp.op.exp1.expType;
8376                      exp.op.exp1.expType = null;
8377                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8378                         FreeType(oldType);
8379                      else
8380                         exp.op.exp1.expType = oldType;
8381                   }
8382
8383                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8384                   exp.op.exp1.destType = type2;
8385                   type2.refCount++;
8386                   /*
8387                   // TESTING THIS HERE... LATEST ADDITION
8388                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8389                   {
8390                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8391                      exp.op.exp1.destType = type1._class.registered.dataType;
8392                      if(type1._class.registered.dataType)
8393                         type1._class.registered.dataType.refCount++;
8394                   }
8395
8396                   // TESTING THIS HERE... LATEST ADDITION
8397                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8398                   {
8399                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8400                      exp.op.exp2.destType = type2._class.registered.dataType;
8401                      if(type2._class.registered.dataType)
8402                         type2._class.registered.dataType.refCount++;
8403                   }
8404                   */
8405
8406                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8407                   {
8408                      if(exp.expType) FreeType(exp.expType);
8409                      exp.expType = exp.op.exp1.destType;
8410                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8411                   }
8412                }
8413             }
8414             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
8415             {
8416                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8417                {
8418                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8419                   // Convert e.g. / 4 into / 4.0
8420                   exp.op.exp1.destType = type2._class.registered.dataType;
8421                   if(type2._class.registered.dataType)
8422                      type2._class.registered.dataType.refCount++;
8423                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8424                }
8425                if(exp.op.op == '!')
8426                {
8427                   exp.expType = MkClassType("bool");
8428                   exp.expType.truth = true;
8429                }
8430                else
8431                {
8432                   exp.expType = type2;
8433                   if(type2) type2.refCount++;
8434                }
8435             }
8436             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
8437             {
8438                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8439                {
8440                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8441                   // Convert e.g. / 4 into / 4.0
8442                   exp.op.exp2.destType = type1._class.registered.dataType;
8443                   if(type1._class.registered.dataType)
8444                      type1._class.registered.dataType.refCount++;
8445                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8446                }
8447                exp.expType = type1;
8448                if(type1) type1.refCount++;
8449             }
8450          }
8451
8452          yylloc = exp.loc;
8453          if(exp.op.exp1 && !exp.op.exp1.expType)
8454          {
8455             char expString[10000];
8456             expString[0] = '\0';
8457             if(inCompiler)
8458             {
8459                PrintExpression(exp.op.exp1, expString);
8460                ChangeCh(expString, '\n', ' ');
8461             }
8462             if(expString[0])
8463                Compiler_Error($"couldn't determine type of %s\n", expString);
8464          }
8465          if(exp.op.exp2 && !exp.op.exp2.expType)
8466          {
8467             char expString[10240];
8468             expString[0] = '\0';
8469             if(inCompiler)
8470             {
8471                PrintExpression(exp.op.exp2, expString);
8472                ChangeCh(expString, '\n', ' ');
8473             }
8474             if(expString[0])
8475                Compiler_Error($"couldn't determine type of %s\n", expString);
8476          }
8477
8478          if(boolResult)
8479          {
8480             FreeType(exp.expType);
8481             exp.expType = MkClassType("bool");
8482             exp.expType.truth = true;
8483          }
8484
8485          if(exp.op.op != SIZEOF)
8486             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
8487                (!exp.op.exp2 || exp.op.exp2.isConstant);
8488
8489          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
8490          {
8491             DeclareType(exp.op.exp2.expType, false, false);
8492          }
8493
8494          yylloc = oldyylloc;
8495
8496          FreeType(dummy);
8497          break;
8498       }
8499       case bracketsExp:
8500       case extensionExpressionExp:
8501       {
8502          Expression e;
8503          exp.isConstant = true;
8504          for(e = exp.list->first; e; e = e.next)
8505          {
8506             bool inced = false;
8507             if(!e.next)
8508             {
8509                FreeType(e.destType);
8510                e.destType = exp.destType;
8511                if(e.destType) { exp.destType.refCount++; e.destType.count++; inced = true; }
8512             }
8513             ProcessExpressionType(e);
8514             if(inced)
8515                exp.destType.count--;
8516             if(!exp.expType && !e.next)
8517             {
8518                exp.expType = e.expType;
8519                if(e.expType) e.expType.refCount++;
8520             }
8521             if(!e.isConstant)
8522                exp.isConstant = false;
8523          }
8524
8525          // In case a cast became a member...
8526          e = exp.list->first;
8527          if(!e.next && e.type == memberExp)
8528          {
8529             // Preserve prev, next
8530             Expression next = exp.next, prev = exp.prev;
8531
8532
8533             FreeType(exp.expType);
8534             FreeType(exp.destType);
8535             delete exp.list;
8536
8537             *exp = *e;
8538
8539             exp.prev = prev;
8540             exp.next = next;
8541
8542             delete e;
8543
8544             ProcessExpressionType(exp);
8545          }
8546          break;
8547       }
8548       case indexExp:
8549       {
8550          Expression e;
8551          exp.isConstant = true;
8552
8553          ProcessExpressionType(exp.index.exp);
8554          if(!exp.index.exp.isConstant)
8555             exp.isConstant = false;
8556
8557          if(exp.index.exp.expType)
8558          {
8559             Type source = exp.index.exp.expType;
8560             if(source.kind == classType && source._class && source._class.registered)
8561             {
8562                Class _class = source._class.registered;
8563                Class c = _class.templateClass ? _class.templateClass : _class;
8564                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
8565                {
8566                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
8567
8568                   if(exp.index.index && exp.index.index->last)
8569                   {
8570                      ((Expression)exp.index.index->last).destType = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
8571                   }
8572                }
8573             }
8574          }
8575
8576          for(e = exp.index.index->first; e; e = e.next)
8577          {
8578             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
8579             {
8580                if(e.destType) FreeType(e.destType);
8581                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
8582             }
8583             ProcessExpressionType(e);
8584             if(!e.next)
8585             {
8586                // Check if this type is int
8587             }
8588             if(!e.isConstant)
8589                exp.isConstant = false;
8590          }
8591
8592          if(!exp.expType)
8593             exp.expType = Dereference(exp.index.exp.expType);
8594          if(exp.expType)
8595             DeclareType(exp.expType, false, false);
8596          break;
8597       }
8598       case callExp:
8599       {
8600          Expression e;
8601          Type functionType;
8602          Type methodType = null;
8603          char name[1024];
8604          name[0] = '\0';
8605
8606          if(inCompiler)
8607          {
8608             PrintExpression(exp.call.exp,  name);
8609             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
8610             {
8611                //exp.call.exp.expType = null;
8612                PrintExpression(exp.call.exp,  name);
8613             }
8614          }
8615          if(exp.call.exp.type == identifierExp)
8616          {
8617             Expression idExp = exp.call.exp;
8618             Identifier id = idExp.identifier;
8619             if(!strcmp(id.string, "__builtin_frame_address"))
8620             {
8621                exp.expType = ProcessTypeString("void *", true);
8622                if(exp.call.arguments && exp.call.arguments->first)
8623                   ProcessExpressionType(exp.call.arguments->first);
8624                break;
8625             }
8626             else if(!strcmp(id.string, "__ENDIAN_PAD"))
8627             {
8628                exp.expType = ProcessTypeString("int", true);
8629                if(exp.call.arguments && exp.call.arguments->first)
8630                   ProcessExpressionType(exp.call.arguments->first);
8631                break;
8632             }
8633             else if(!strcmp(id.string, "Max") ||
8634                !strcmp(id.string, "Min") ||
8635                !strcmp(id.string, "Sgn") ||
8636                !strcmp(id.string, "Abs"))
8637             {
8638                Expression a = null;
8639                Expression b = null;
8640                Expression tempExp1 = null, tempExp2 = null;
8641                if((!strcmp(id.string, "Max") ||
8642                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
8643                {
8644                   a = exp.call.arguments->first;
8645                   b = exp.call.arguments->last;
8646                   tempExp1 = a;
8647                   tempExp2 = b;
8648                }
8649                else if(exp.call.arguments->count == 1)
8650                {
8651                   a = exp.call.arguments->first;
8652                   tempExp1 = a;
8653                }
8654
8655                if(a)
8656                {
8657                   exp.call.arguments->Clear();
8658                   idExp.identifier = null;
8659
8660                   FreeExpContents(exp);
8661
8662                   ProcessExpressionType(a);
8663                   if(b)
8664                      ProcessExpressionType(b);
8665
8666                   exp.type = bracketsExp;
8667                   exp.list = MkList();
8668
8669                   if(a.expType && (!b || b.expType))
8670                   {
8671                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
8672                      {
8673                         // Use the simpleStruct name/ids for now...
8674                         if(inCompiler)
8675                         {
8676                            OldList * specs = MkList();
8677                            OldList * decls = MkList();
8678                            Declaration decl;
8679                            char temp1[1024], temp2[1024];
8680
8681                            GetTypeSpecs(a.expType, specs);
8682
8683                            if(a && !a.isConstant && a.type != identifierExp)
8684                            {
8685                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
8686                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
8687                               tempExp1 = QMkExpId(temp1);
8688                               tempExp1.expType = a.expType;
8689                               if(a.expType)
8690                                  a.expType.refCount++;
8691                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
8692                            }
8693                            if(b && !b.isConstant && b.type != identifierExp)
8694                            {
8695                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
8696                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
8697                               tempExp2 = QMkExpId(temp2);
8698                               tempExp2.expType = b.expType;
8699                               if(b.expType)
8700                                  b.expType.refCount++;
8701                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
8702                            }
8703
8704                            decl = MkDeclaration(specs, decls);
8705                            if(!curCompound.compound.declarations)
8706                               curCompound.compound.declarations = MkList();
8707                            curCompound.compound.declarations->Insert(null, decl);
8708                         }
8709                      }
8710                   }
8711
8712                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
8713                   {
8714                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
8715                      ListAdd(exp.list,
8716                         MkExpCondition(MkExpBrackets(MkListOne(
8717                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
8718                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
8719                      exp.expType = a.expType;
8720                      if(a.expType)
8721                         a.expType.refCount++;
8722                   }
8723                   else if(!strcmp(id.string, "Abs"))
8724                   {
8725                      ListAdd(exp.list,
8726                         MkExpCondition(MkExpBrackets(MkListOne(
8727                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
8728                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
8729                      exp.expType = a.expType;
8730                      if(a.expType)
8731                         a.expType.refCount++;
8732                   }
8733                   else if(!strcmp(id.string, "Sgn"))
8734                   {
8735                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
8736                      ListAdd(exp.list,
8737                         MkExpCondition(MkExpBrackets(MkListOne(
8738                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
8739                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
8740                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
8741                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
8742                      exp.expType = ProcessTypeString("int", false);
8743                   }
8744
8745                   FreeExpression(tempExp1);
8746                   if(tempExp2) FreeExpression(tempExp2);
8747
8748                   FreeIdentifier(id);
8749                   break;
8750                }
8751             }
8752          }
8753
8754          {
8755             Type dummy
8756             {
8757                count = 1;
8758                refCount = 1;
8759             };
8760             if(!exp.call.exp.destType)
8761             {
8762                exp.call.exp.destType = dummy;
8763                dummy.refCount++;
8764             }
8765             ProcessExpressionType(exp.call.exp);
8766             if(exp.call.exp.destType == dummy)
8767             {
8768                FreeType(dummy);
8769                exp.call.exp.destType = null;
8770             }
8771             FreeType(dummy);
8772          }
8773
8774          // Check argument types against parameter types
8775          functionType = exp.call.exp.expType;
8776
8777          if(functionType && functionType.kind == TypeKind::methodType)
8778          {
8779             methodType = functionType;
8780             functionType = methodType.method.dataType;
8781
8782             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
8783             // TOCHECK: Instead of doing this here could this be done per param?
8784             if(exp.call.exp.expType.usedClass)
8785             {
8786                char typeString[1024];
8787                typeString[0] = '\0';
8788                {
8789                   Symbol back = functionType.thisClass;
8790                   // Do not output class specifier here (thisclass was added to this)
8791                   functionType.thisClass = null;
8792                   PrintType(functionType, typeString, true, true);
8793                   functionType.thisClass = back;
8794                }
8795                if(strstr(typeString, "thisclass"))
8796                {
8797                   OldList * specs = MkList();
8798                   Declarator decl;
8799                   {
8800                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
8801
8802                      decl = SpecDeclFromString(typeString, specs, null);
8803
8804                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
8805                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
8806                         exp.call.exp.expType.usedClass))
8807                         thisClassParams = false;
8808
8809                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
8810                      {
8811                         Class backupThisClass = thisClass;
8812                         thisClass = exp.call.exp.expType.usedClass;
8813                         ProcessDeclarator(decl);
8814                         thisClass = backupThisClass;
8815                      }
8816
8817                      thisClassParams = true;
8818
8819                      functionType = ProcessType(specs, decl);
8820                      functionType.refCount = 0;
8821                      FinishTemplatesContext(context);
8822                   }
8823
8824                   FreeList(specs, FreeSpecifier);
8825                   FreeDeclarator(decl);
8826                 }
8827             }
8828          }
8829          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
8830          {
8831             Type type = functionType.type;
8832             if(!functionType.refCount)
8833             {
8834                functionType.type = null;
8835                FreeType(functionType);
8836             }
8837             //methodType = functionType;
8838             functionType = type;
8839          }
8840          if(functionType && functionType.kind != TypeKind::functionType)
8841          {
8842             Compiler_Error($"called object %s is not a function\n", name);
8843          }
8844          else if(functionType)
8845          {
8846             bool emptyParams = false, noParams = false;
8847             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
8848             Type type = functionType.params.first;
8849             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
8850             int extra = 0;
8851             Location oldyylloc = yylloc;
8852
8853             if(!type) emptyParams = true;
8854
8855             // WORKING ON THIS:
8856             if(functionType.extraParam && e && functionType.thisClass)
8857             {
8858                e.destType = MkClassType(functionType.thisClass.string);
8859                e = e.next;
8860             }
8861
8862             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
8863             // Fixed #141 by adding '&& !functionType.extraParam'
8864             if(!functionType.staticMethod && !functionType.extraParam)
8865             {
8866                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
8867                   memberExp.member.exp.expType._class)
8868                {
8869                   type = MkClassType(memberExp.member.exp.expType._class.string);
8870                   if(e)
8871                   {
8872                      e.destType = type;
8873                      e = e.next;
8874                      type = functionType.params.first;
8875                   }
8876                   else
8877                      type.refCount = 0;
8878                }
8879                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
8880                {
8881                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
8882                   type.byReference = functionType.byReference;
8883                   type.typedByReference = functionType.typedByReference;
8884                   if(e)
8885                   {
8886                      // Allow manually passing a class for typed object
8887                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
8888                         e = e.next;
8889                      e.destType = type;
8890                      e = e.next;
8891                      type = functionType.params.first;
8892                   }
8893                   else
8894                      type.refCount = 0;
8895                   //extra = 1;
8896                }
8897             }
8898
8899             if(type && type.kind == voidType)
8900             {
8901                noParams = true;
8902                if(!type.refCount) FreeType(type);
8903                type = null;
8904             }
8905
8906             for( ; e; e = e.next)
8907             {
8908                if(!type && !emptyParams)
8909                {
8910                   yylloc = e.loc;
8911                   if(methodType && methodType.methodClass)
8912                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
8913                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
8914                         noParams ? 0 : functionType.params.count);
8915                   else
8916                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
8917                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
8918                         noParams ? 0 : functionType.params.count);
8919                   break;
8920                }
8921
8922                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
8923                {
8924                   Type templatedType = null;
8925                   Class _class = methodType.usedClass;
8926                   ClassTemplateParameter curParam = null;
8927                   int id = 0;
8928                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
8929                   {
8930                      Class sClass;
8931                      for(sClass = _class; sClass; sClass = sClass.base)
8932                      {
8933                         if(sClass.templateClass) sClass = sClass.templateClass;
8934                         id = 0;
8935                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
8936                         {
8937                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
8938                            {
8939                               Class nextClass;
8940                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
8941                               {
8942                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
8943                                  id += nextClass.templateParams.count;
8944                               }
8945                               break;
8946                            }
8947                            id++;
8948                         }
8949                         if(curParam) break;
8950                      }
8951                   }
8952                   if(curParam && _class.templateArgs[id].dataTypeString)
8953                   {
8954                      ClassTemplateArgument arg = _class.templateArgs[id];
8955                      {
8956                         Context context = SetupTemplatesContext(_class);
8957
8958                         /*if(!arg.dataType)
8959                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
8960                         templatedType = ProcessTypeString(arg.dataTypeString, false);
8961                         FinishTemplatesContext(context);
8962                      }
8963                      e.destType = templatedType;
8964                      if(templatedType)
8965                      {
8966                         templatedType.passAsTemplate = true;
8967                         // templatedType.refCount++;
8968                      }
8969                   }
8970                   else
8971                   {
8972                      e.destType = type;
8973                      if(type) type.refCount++;
8974                   }
8975                }
8976                else
8977                {
8978                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
8979                   {
8980                      e.destType = type.prev;
8981                      e.destType.refCount++;
8982                   }
8983                   else
8984                   {
8985                      e.destType = type;
8986                      if(type) type.refCount++;
8987                   }
8988                }
8989                // Don't reach the end for the ellipsis
8990                if(type && type.kind != ellipsisType)
8991                {
8992                   Type next = type.next;
8993                   if(!type.refCount) FreeType(type);
8994                   type = next;
8995                }
8996             }
8997
8998             if(type && type.kind != ellipsisType)
8999             {
9000                if(methodType && methodType.methodClass)
9001                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9002                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9003                      functionType.params.count + extra);
9004                else
9005                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9006                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9007                      functionType.params.count + extra);
9008             }
9009             yylloc = oldyylloc;
9010             if(type && !type.refCount) FreeType(type);
9011          }
9012          else
9013          {
9014             functionType = Type
9015             {
9016                refCount = 0;
9017                kind = TypeKind::functionType;
9018             };
9019
9020             if(exp.call.exp.type == identifierExp)
9021             {
9022                char * string = exp.call.exp.identifier.string;
9023                if(inCompiler)
9024                {
9025                   Symbol symbol;
9026                   Location oldyylloc = yylloc;
9027
9028                   yylloc = exp.call.exp.identifier.loc;
9029                   if(strstr(string, "__builtin_") == string)
9030                   {
9031                      if(exp.destType)
9032                      {
9033                         functionType.returnType = exp.destType;
9034                         exp.destType.refCount++;
9035                      }
9036                   }
9037                   else
9038                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9039                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9040                   globalContext.symbols.Add((BTNode)symbol);
9041                   if(strstr(symbol.string, "::"))
9042                      globalContext.hasNameSpace = true;
9043
9044                   yylloc = oldyylloc;
9045                }
9046             }
9047             else if(exp.call.exp.type == memberExp)
9048             {
9049                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9050                   exp.call.exp.member.member.string);*/
9051             }
9052             else
9053                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9054
9055             if(!functionType.returnType)
9056             {
9057                functionType.returnType = Type
9058                {
9059                   refCount = 1;
9060                   kind = intType;
9061                };
9062             }
9063          }
9064          if(functionType && functionType.kind == TypeKind::functionType)
9065          {
9066             exp.expType = functionType.returnType;
9067
9068             if(functionType.returnType)
9069                functionType.returnType.refCount++;
9070
9071             if(!functionType.refCount)
9072                FreeType(functionType);
9073          }
9074
9075          if(exp.call.arguments)
9076          {
9077             for(e = exp.call.arguments->first; e; e = e.next)
9078             {
9079                Type destType = e.destType;
9080                ProcessExpressionType(e);
9081             }
9082          }
9083          break;
9084       }
9085       case memberExp:
9086       {
9087          Type type;
9088          Location oldyylloc = yylloc;
9089          bool thisPtr;
9090          Expression checkExp = exp.member.exp;
9091          while(checkExp)
9092          {
9093             if(checkExp.type == castExp)
9094                checkExp = checkExp.cast.exp;
9095             else if(checkExp.type == bracketsExp)
9096                checkExp = checkExp.list ? checkExp.list->first : null;
9097             else
9098                break;
9099          }
9100
9101          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9102          exp.thisPtr = thisPtr;
9103
9104          // DOING THIS LATER NOW...
9105          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9106          {
9107             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9108             /* TODO: Name Space Fix ups
9109             if(!exp.member.member.classSym)
9110                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9111             */
9112          }
9113
9114          ProcessExpressionType(exp.member.exp);
9115          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9116             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9117          {
9118             exp.isConstant = false;
9119          }
9120          else
9121             exp.isConstant = exp.member.exp.isConstant;
9122          type = exp.member.exp.expType;
9123
9124          yylloc = exp.loc;
9125
9126          if(type && (type.kind == templateType))
9127          {
9128             Class _class = thisClass ? thisClass : currentClass;
9129             ClassTemplateParameter param = null;
9130             if(_class)
9131             {
9132                for(param = _class.templateParams.first; param; param = param.next)
9133                {
9134                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9135                      break;
9136                }
9137             }
9138             if(param && param.defaultArg.member)
9139             {
9140                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9141                if(argExp)
9142                {
9143                   Expression expMember = exp.member.exp;
9144                   Declarator decl;
9145                   OldList * specs = MkList();
9146                   char thisClassTypeString[1024];
9147
9148                   FreeIdentifier(exp.member.member);
9149
9150                   ProcessExpressionType(argExp);
9151
9152                   {
9153                      char * colon = strstr(param.defaultArg.memberString, "::");
9154                      if(colon)
9155                      {
9156                         char className[1024];
9157                         Class sClass;
9158
9159                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9160                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9161                      }
9162                      else
9163                         strcpy(thisClassTypeString, _class.fullName);
9164                   }
9165
9166                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9167
9168                   exp.expType = ProcessType(specs, decl);
9169                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9170                   {
9171                      Class expClass = exp.expType._class.registered;
9172                      Class cClass = null;
9173                      int c;
9174                      int paramCount = 0;
9175                      int lastParam = -1;
9176
9177                      char templateString[1024];
9178                      ClassTemplateParameter param;
9179                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9180                      for(cClass = expClass; cClass; cClass = cClass.base)
9181                      {
9182                         int p = 0;
9183                         for(param = cClass.templateParams.first; param; param = param.next)
9184                         {
9185                            int id = p;
9186                            Class sClass;
9187                            ClassTemplateArgument arg;
9188                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9189                            arg = expClass.templateArgs[id];
9190
9191                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9192                            {
9193                               ClassTemplateParameter cParam;
9194                               //int p = numParams - sClass.templateParams.count;
9195                               int p = 0;
9196                               Class nextClass;
9197                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9198
9199                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9200                               {
9201                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9202                                  {
9203                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9204                                     {
9205                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9206                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9207                                        break;
9208                                     }
9209                                  }
9210                               }
9211                            }
9212
9213                            {
9214                               char argument[256];
9215                               argument[0] = '\0';
9216                               /*if(arg.name)
9217                               {
9218                                  strcat(argument, arg.name.string);
9219                                  strcat(argument, " = ");
9220                               }*/
9221                               switch(param.type)
9222                               {
9223                                  case expression:
9224                                  {
9225                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9226                                     char expString[1024];
9227                                     OldList * specs = MkList();
9228                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9229                                     Expression exp;
9230                                     char * string = PrintHexUInt64(arg.expression.ui64);
9231                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9232
9233                                     ProcessExpressionType(exp);
9234                                     ComputeExpression(exp);
9235                                     expString[0] = '\0';
9236                                     PrintExpression(exp, expString);
9237                                     strcat(argument, expString);
9238                                     // delete exp;
9239                                     FreeExpression(exp);
9240                                     break;
9241                                  }
9242                                  case identifier:
9243                                  {
9244                                     strcat(argument, arg.member.name);
9245                                     break;
9246                                  }
9247                                  case TemplateParameterType::type:
9248                                  {
9249                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9250                                     {
9251                                        if(!strcmp(arg.dataTypeString, "thisclass"))
9252                                           strcat(argument, thisClassTypeString);
9253                                        else
9254                                           strcat(argument, arg.dataTypeString);
9255                                     }
9256                                     break;
9257                                  }
9258                               }
9259                               if(argument[0])
9260                               {
9261                                  if(paramCount) strcat(templateString, ", ");
9262                                  if(lastParam != p - 1)
9263                                  {
9264                                     strcat(templateString, param.name);
9265                                     strcat(templateString, " = ");
9266                                  }
9267                                  strcat(templateString, argument);
9268                                  paramCount++;
9269                                  lastParam = p;
9270                               }
9271                               p++;
9272                            }
9273                         }
9274                      }
9275                      {
9276                         int len = strlen(templateString);
9277                         if(templateString[len-1] == '>') templateString[len++] = ' ';
9278                         templateString[len++] = '>';
9279                         templateString[len++] = '\0';
9280                      }
9281                      {
9282                         Context context = SetupTemplatesContext(_class);
9283                         FreeType(exp.expType);
9284                         exp.expType = ProcessTypeString(templateString, false);
9285                         FinishTemplatesContext(context);
9286                      }
9287                   }
9288
9289                   // *([expType] *)(((byte *)[exp.member.exp]) + [argExp].member.offset)
9290                   exp.type = bracketsExp;
9291                   exp.list = MkListOne(MkExpOp(null, '*',
9292                   /*opExp;
9293                   exp.op.op = '*';
9294                   exp.op.exp1 = null;
9295                   exp.op.exp2 = */
9296                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
9297                      MkExpBrackets(MkListOne(
9298                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), expMember))),
9299                            '+',
9300                            MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
9301                            '+',
9302                            MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
9303
9304                            ));
9305                }
9306             }
9307             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
9308                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
9309             {
9310                type = ProcessTemplateParameterType(type.templateParameter);
9311             }
9312          }
9313          // TODO: *** This seems to be where we should add method support for all basic types ***
9314          if(type && (type.kind == templateType));
9315          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
9316                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
9317                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
9318                           (type.kind == pointerType && type.type.kind == charType)))
9319          {
9320             Identifier id = exp.member.member;
9321             TypeKind typeKind = type.kind;
9322             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
9323             if(typeKind == subClassType && exp.member.exp.type == classExp)
9324             {
9325                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
9326                typeKind = classType;
9327             }
9328
9329             if(id)
9330             {
9331                if(typeKind == intType || typeKind == enumType)
9332                   _class = eSystem_FindClass(privateModule, "int");
9333                else if(!_class)
9334                {
9335                   if(type.kind == classType && type._class && type._class.registered)
9336                   {
9337                      _class = type._class.registered;
9338                   }
9339                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
9340                   {
9341                      _class = FindClass("char *").registered;
9342                   }
9343                   else if(type.kind == pointerType)
9344                   {
9345                      _class = eSystem_FindClass(privateModule, "uintptr");
9346                      FreeType(exp.expType);
9347                      exp.expType = ProcessTypeString("uintptr", false);
9348                      exp.byReference = true;
9349                   }
9350                   else
9351                   {
9352                      char string[1024] = "";
9353                      Symbol classSym;
9354                      PrintTypeNoConst(type, string, false, true);
9355                      classSym = FindClass(string);
9356                      if(classSym) _class = classSym.registered;
9357                   }
9358                }
9359             }
9360
9361             if(_class && id)
9362             {
9363                /*bool thisPtr =
9364                   (exp.member.exp.type == identifierExp &&
9365                   !strcmp(exp.member.exp.identifier.string, "this"));*/
9366                Property prop = null;
9367                Method method = null;
9368                DataMember member = null;
9369                Property revConvert = null;
9370                ClassProperty classProp = null;
9371
9372                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
9373                   exp.member.memberType = propertyMember;
9374
9375                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
9376                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
9377
9378                if(typeKind != subClassType)
9379                {
9380                   // Prioritize data members over properties for "this"
9381                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
9382                   {
9383                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
9384                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
9385                      {
9386                         prop = eClass_FindProperty(_class, id.string, privateModule);
9387                         if(prop)
9388                            member = null;
9389                      }
9390                      if(!member && !prop)
9391                         prop = eClass_FindProperty(_class, id.string, privateModule);
9392                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
9393                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
9394                         exp.member.thisPtr = true;
9395                   }
9396                   // Prioritize properties over data members otherwise
9397                   else
9398                   {
9399                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
9400                      if(!id.classSym)
9401                      {
9402                         prop = eClass_FindProperty(_class, id.string, null);
9403                         if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
9404                            member = eClass_FindDataMember(_class, id.string, null, null, null);
9405                      }
9406
9407                      if(!prop && !member)
9408                      {
9409                         method = eClass_FindMethod(_class, id.string, null);
9410                         if(!method)
9411                         {
9412                            prop = eClass_FindProperty(_class, id.string, privateModule);
9413                            if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
9414                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
9415                         }
9416                      }
9417
9418                      if(member && prop)
9419                      {
9420                         if(member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class))
9421                            prop = null;
9422                         else
9423                            member = null;
9424                      }
9425                   }
9426                }
9427                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
9428                   method = eClass_FindMethod(_class, id.string, privateModule);
9429                if(!prop && !member && !method)
9430                {
9431                   if(typeKind == subClassType)
9432                   {
9433                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
9434                      if(classProp)
9435                      {
9436                         exp.member.memberType = classPropertyMember;
9437                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
9438                      }
9439                      else
9440                      {
9441                         // Assume this is a class_data member
9442                         char structName[1024];
9443                         Identifier id = exp.member.member;
9444                         Expression classExp = exp.member.exp;
9445                         type.refCount++;
9446
9447                         FreeType(classExp.expType);
9448                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
9449
9450                         strcpy(structName, "__ecereClassData_");
9451                         FullClassNameCat(structName, type._class.string, false);
9452                         exp.type = pointerExp;
9453                         exp.member.member = id;
9454
9455                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
9456                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
9457                               MkExpBrackets(MkListOne(MkExpOp(
9458                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
9459                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
9460                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
9461                                  )));
9462
9463                         FreeType(type);
9464
9465                         ProcessExpressionType(exp);
9466                         return;
9467                      }
9468                   }
9469                   else
9470                   {
9471                      // Check for reverse conversion
9472                      // (Convert in an instantiation later, so that we can use
9473                      //  deep properties system)
9474                      Symbol classSym = FindClass(id.string);
9475                      if(classSym)
9476                      {
9477                         Class convertClass = classSym.registered;
9478                         if(convertClass)
9479                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
9480                      }
9481                   }
9482                }
9483
9484                if(prop)
9485                {
9486                   exp.member.memberType = propertyMember;
9487                   if(!prop.dataType)
9488                      ProcessPropertyType(prop);
9489                   exp.expType = prop.dataType;
9490                   if(prop.dataType) prop.dataType.refCount++;
9491                }
9492                else if(member)
9493                {
9494                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
9495                   {
9496                      FreeExpContents(exp);
9497                      exp.type = identifierExp;
9498                      exp.identifier = MkIdentifier("class");
9499                      ProcessExpressionType(exp);
9500                      return;
9501                   }
9502
9503                   exp.member.memberType = dataMember;
9504                   DeclareStruct(_class.fullName, false);
9505                   if(!member.dataType)
9506                   {
9507                      Context context = SetupTemplatesContext(_class);
9508                      member.dataType = ProcessTypeString(member.dataTypeString, false);
9509                      FinishTemplatesContext(context);
9510                   }
9511                   exp.expType = member.dataType;
9512                   if(member.dataType) member.dataType.refCount++;
9513                }
9514                else if(revConvert)
9515                {
9516                   exp.member.memberType = reverseConversionMember;
9517                   exp.expType = MkClassType(revConvert._class.fullName);
9518                }
9519                else if(method)
9520                {
9521                   //if(inCompiler)
9522                   {
9523                      /*if(id._class)
9524                      {
9525                         exp.type = identifierExp;
9526                         exp.identifier = exp.member.member;
9527                      }
9528                      else*/
9529                         exp.member.memberType = methodMember;
9530                   }
9531                   if(!method.dataType)
9532                      ProcessMethodType(method);
9533                   exp.expType = Type
9534                   {
9535                      refCount = 1;
9536                      kind = methodType;
9537                      method = method;
9538                   };
9539
9540                   // Tricky spot here... To use instance versus class virtual table
9541                   // Put it back to what it was... What did we break?
9542
9543                   // Had to put it back for overriding Main of Thread global instance
9544
9545                   //exp.expType.methodClass = _class;
9546                   exp.expType.methodClass = (id && id._class) ? _class : null;
9547
9548                   // Need the actual class used for templated classes
9549                   exp.expType.usedClass = _class;
9550                }
9551                else if(!classProp)
9552                {
9553                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
9554                   {
9555                      FreeExpContents(exp);
9556                      exp.type = identifierExp;
9557                      exp.identifier = MkIdentifier("class");
9558                      ProcessExpressionType(exp);
9559                      return;
9560                   }
9561                   yylloc = exp.member.member.loc;
9562                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
9563                   if(inCompiler)
9564                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
9565                }
9566
9567                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
9568                {
9569                   Class tClass;
9570
9571                   tClass = _class;
9572                   while(tClass && !tClass.templateClass) tClass = tClass.base;
9573
9574                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
9575                   {
9576                      int id = 0;
9577                      ClassTemplateParameter curParam = null;
9578                      Class sClass;
9579
9580                      for(sClass = tClass; sClass; sClass = sClass.base)
9581                      {
9582                         id = 0;
9583                         if(sClass.templateClass) sClass = sClass.templateClass;
9584                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9585                         {
9586                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
9587                            {
9588                               for(sClass = sClass.base; sClass; sClass = sClass.base)
9589                                  id += sClass.templateParams.count;
9590                               break;
9591                            }
9592                            id++;
9593                         }
9594                         if(curParam) break;
9595                      }
9596
9597                      if(curParam && tClass.templateArgs[id].dataTypeString)
9598                      {
9599                         ClassTemplateArgument arg = tClass.templateArgs[id];
9600                         Context context = SetupTemplatesContext(tClass);
9601                         /*if(!arg.dataType)
9602                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9603                         FreeType(exp.expType);
9604                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
9605                         if(exp.expType)
9606                         {
9607                            if(exp.expType.kind == thisClassType)
9608                            {
9609                               FreeType(exp.expType);
9610                               exp.expType = ReplaceThisClassType(_class);
9611                            }
9612
9613                            if(tClass.templateClass)
9614                               exp.expType.passAsTemplate = true;
9615                            //exp.expType.refCount++;
9616                            if(!exp.destType)
9617                            {
9618                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
9619                               //exp.destType.refCount++;
9620
9621                               if(exp.destType.kind == thisClassType)
9622                               {
9623                                  FreeType(exp.destType);
9624                                  exp.destType = ReplaceThisClassType(_class);
9625                               }
9626                            }
9627                         }
9628                         FinishTemplatesContext(context);
9629                      }
9630                   }
9631                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
9632                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
9633                   {
9634                      int id = 0;
9635                      ClassTemplateParameter curParam = null;
9636                      Class sClass;
9637
9638                      for(sClass = tClass; sClass; sClass = sClass.base)
9639                      {
9640                         id = 0;
9641                         if(sClass.templateClass) sClass = sClass.templateClass;
9642                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9643                         {
9644                            if(curParam.type == TemplateParameterType::type &&
9645                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
9646                            {
9647                               for(sClass = sClass.base; sClass; sClass = sClass.base)
9648                                  id += sClass.templateParams.count;
9649                               break;
9650                            }
9651                            id++;
9652                         }
9653                         if(curParam) break;
9654                      }
9655
9656                      if(curParam)
9657                      {
9658                         ClassTemplateArgument arg = tClass.templateArgs[id];
9659                         Context context = SetupTemplatesContext(tClass);
9660                         Type basicType;
9661                         /*if(!arg.dataType)
9662                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9663
9664                         basicType = ProcessTypeString(arg.dataTypeString, false);
9665                         if(basicType)
9666                         {
9667                            if(basicType.kind == thisClassType)
9668                            {
9669                               FreeType(basicType);
9670                               basicType = ReplaceThisClassType(_class);
9671                            }
9672
9673                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
9674                            if(tClass.templateClass)
9675                               basicType.passAsTemplate = true;
9676                            */
9677
9678                            FreeType(exp.expType);
9679
9680                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
9681                            //exp.expType.refCount++;
9682                            if(!exp.destType)
9683                            {
9684                               exp.destType = exp.expType;
9685                               exp.destType.refCount++;
9686                            }
9687
9688                            {
9689                               Expression newExp { };
9690                               OldList * specs = MkList();
9691                               Declarator decl;
9692                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
9693                               *newExp = *exp;
9694                               if(exp.destType) exp.destType.refCount++;
9695                               if(exp.expType)  exp.expType.refCount++;
9696                               exp.type = castExp;
9697                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
9698                               exp.cast.exp = newExp;
9699                               //FreeType(exp.expType);
9700                               //exp.expType = null;
9701                               //ProcessExpressionType(sourceExp);
9702                            }
9703                         }
9704                         FinishTemplatesContext(context);
9705                      }
9706                   }
9707                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
9708                   {
9709                      Class expClass = exp.expType._class.registered;
9710                      if(expClass)
9711                      {
9712                         Class cClass = null;
9713                         int c;
9714                         int p = 0;
9715                         int paramCount = 0;
9716                         int lastParam = -1;
9717                         char templateString[1024];
9718                         ClassTemplateParameter param;
9719                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
9720                         while(cClass != expClass)
9721                         {
9722                            Class sClass;
9723                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
9724                            cClass = sClass;
9725
9726                            for(param = cClass.templateParams.first; param; param = param.next)
9727                            {
9728                               Class cClassCur = null;
9729                               int c;
9730                               int cp = 0;
9731                               ClassTemplateParameter paramCur = null;
9732                               ClassTemplateArgument arg;
9733                               while(cClassCur != tClass && !paramCur)
9734                               {
9735                                  Class sClassCur;
9736                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
9737                                  cClassCur = sClassCur;
9738
9739                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
9740                                  {
9741                                     if(!strcmp(paramCur.name, param.name))
9742                                     {
9743
9744                                        break;
9745                                     }
9746                                     cp++;
9747                                  }
9748                               }
9749                               if(paramCur && paramCur.type == TemplateParameterType::type)
9750                                  arg = tClass.templateArgs[cp];
9751                               else
9752                                  arg = expClass.templateArgs[p];
9753
9754                               {
9755                                  char argument[256];
9756                                  argument[0] = '\0';
9757                                  /*if(arg.name)
9758                                  {
9759                                     strcat(argument, arg.name.string);
9760                                     strcat(argument, " = ");
9761                                  }*/
9762                                  switch(param.type)
9763                                  {
9764                                     case expression:
9765                                     {
9766                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9767                                        char expString[1024];
9768                                        OldList * specs = MkList();
9769                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9770                                        Expression exp;
9771                                        char * string = PrintHexUInt64(arg.expression.ui64);
9772                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9773
9774                                        ProcessExpressionType(exp);
9775                                        ComputeExpression(exp);
9776                                        expString[0] = '\0';
9777                                        PrintExpression(exp, expString);
9778                                        strcat(argument, expString);
9779                                        // delete exp;
9780                                        FreeExpression(exp);
9781                                        break;
9782                                     }
9783                                     case identifier:
9784                                     {
9785                                        strcat(argument, arg.member.name);
9786                                        break;
9787                                     }
9788                                     case TemplateParameterType::type:
9789                                     {
9790                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9791                                           strcat(argument, arg.dataTypeString);
9792                                        break;
9793                                     }
9794                                  }
9795                                  if(argument[0])
9796                                  {
9797                                     if(paramCount) strcat(templateString, ", ");
9798                                     if(lastParam != p - 1)
9799                                     {
9800                                        strcat(templateString, param.name);
9801                                        strcat(templateString, " = ");
9802                                     }
9803                                     strcat(templateString, argument);
9804                                     paramCount++;
9805                                     lastParam = p;
9806                                  }
9807                               }
9808                               p++;
9809                            }
9810                         }
9811                         {
9812                            int len = strlen(templateString);
9813                            if(templateString[len-1] == '>') templateString[len++] = ' ';
9814                            templateString[len++] = '>';
9815                            templateString[len++] = '\0';
9816                         }
9817
9818                         FreeType(exp.expType);
9819                         {
9820                            Context context = SetupTemplatesContext(tClass);
9821                            exp.expType = ProcessTypeString(templateString, false);
9822                            FinishTemplatesContext(context);
9823                         }
9824                      }
9825                   }
9826                }
9827             }
9828             else
9829                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
9830          }
9831          else if(type && (type.kind == structType || type.kind == unionType))
9832          {
9833             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
9834             if(memberType)
9835             {
9836                exp.expType = memberType;
9837                if(memberType)
9838                   memberType.refCount++;
9839             }
9840          }
9841          else
9842          {
9843             char expString[10240];
9844             expString[0] = '\0';
9845             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
9846             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
9847          }
9848
9849          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
9850          {
9851             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
9852             {
9853                Identifier id = exp.member.member;
9854                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
9855                if(_class)
9856                {
9857                   FreeType(exp.expType);
9858                   exp.expType = ReplaceThisClassType(_class);
9859                }
9860             }
9861          }
9862          yylloc = oldyylloc;
9863          break;
9864       }
9865       // Convert x->y into (*x).y
9866       case pointerExp:
9867       {
9868          Type destType = exp.destType;
9869
9870          // DOING THIS LATER NOW...
9871          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9872          {
9873             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9874             /* TODO: Name Space Fix ups
9875             if(!exp.member.member.classSym)
9876                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
9877             */
9878          }
9879
9880          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
9881          exp.type = memberExp;
9882          if(destType)
9883             destType.count++;
9884          ProcessExpressionType(exp);
9885          if(destType)
9886             destType.count--;
9887          break;
9888       }
9889       case classSizeExp:
9890       {
9891          //ComputeExpression(exp);
9892
9893          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
9894          if(classSym && classSym.registered)
9895          {
9896             if(classSym.registered.type == noHeadClass)
9897             {
9898                char name[1024];
9899                name[0] = '\0';
9900                DeclareStruct(classSym.string, false);
9901                FreeSpecifier(exp._class);
9902                exp.type = typeSizeExp;
9903                FullClassNameCat(name, classSym.string, false);
9904                exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
9905             }
9906             else
9907             {
9908                if(classSym.registered.fixed)
9909                {
9910                   FreeSpecifier(exp._class);
9911                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
9912                   exp.type = constantExp;
9913                }
9914                else
9915                {
9916                   char className[1024];
9917                   strcpy(className, "__ecereClass_");
9918                   FullClassNameCat(className, classSym.string, true);
9919                   MangleClassName(className);
9920
9921                   DeclareClass(classSym, className);
9922
9923                   FreeExpContents(exp);
9924                   exp.type = pointerExp;
9925                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
9926                   exp.member.member = MkIdentifier("structSize");
9927                }
9928             }
9929          }
9930
9931          exp.expType = Type
9932          {
9933             refCount = 1;
9934             kind = intType;
9935          };
9936          // exp.isConstant = true;
9937          break;
9938       }
9939       case typeSizeExp:
9940       {
9941          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
9942
9943          exp.expType = Type
9944          {
9945             refCount = 1;
9946             kind = intType;
9947          };
9948          exp.isConstant = true;
9949
9950          DeclareType(type, false, false);
9951          FreeType(type);
9952          break;
9953       }
9954       case castExp:
9955       {
9956          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
9957          type.count = 1;
9958          FreeType(exp.cast.exp.destType);
9959          exp.cast.exp.destType = type;
9960          type.refCount++;
9961          ProcessExpressionType(exp.cast.exp);
9962          type.count = 0;
9963          exp.expType = type;
9964          //type.refCount++;
9965
9966          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
9967          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
9968          {
9969             void * prev = exp.prev, * next = exp.next;
9970             Type expType = exp.cast.exp.destType;
9971             Expression castExp = exp.cast.exp;
9972             Type destType = exp.destType;
9973
9974             if(expType) expType.refCount++;
9975
9976             //FreeType(exp.destType);
9977             FreeType(exp.expType);
9978             FreeTypeName(exp.cast.typeName);
9979
9980             *exp = *castExp;
9981             FreeType(exp.expType);
9982             FreeType(exp.destType);
9983
9984             exp.expType = expType;
9985             exp.destType = destType;
9986
9987             delete castExp;
9988
9989             exp.prev = prev;
9990             exp.next = next;
9991
9992          }
9993          else
9994          {
9995             exp.isConstant = exp.cast.exp.isConstant;
9996          }
9997          //FreeType(type);
9998          break;
9999       }
10000       case extensionInitializerExp:
10001       {
10002          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10003          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10004          // ProcessInitializer(exp.initializer.initializer, type);
10005          exp.expType = type;
10006          break;
10007       }
10008       case vaArgExp:
10009       {
10010          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10011          ProcessExpressionType(exp.vaArg.exp);
10012          exp.expType = type;
10013          break;
10014       }
10015       case conditionExp:
10016       {
10017          Expression e;
10018          exp.isConstant = true;
10019
10020          FreeType(exp.cond.cond.destType);
10021          exp.cond.cond.destType = MkClassType("bool");
10022          exp.cond.cond.destType.truth = true;
10023          ProcessExpressionType(exp.cond.cond);
10024          if(!exp.cond.cond.isConstant)
10025             exp.isConstant = false;
10026          for(e = exp.cond.exp->first; e; e = e.next)
10027          {
10028             if(!e.next)
10029             {
10030                FreeType(e.destType);
10031                e.destType = exp.destType;
10032                if(e.destType) e.destType.refCount++;
10033             }
10034             ProcessExpressionType(e);
10035             if(!e.next)
10036             {
10037                exp.expType = e.expType;
10038                if(e.expType) e.expType.refCount++;
10039             }
10040             if(!e.isConstant)
10041                exp.isConstant = false;
10042          }
10043
10044          FreeType(exp.cond.elseExp.destType);
10045          // Added this check if we failed to find an expType
10046          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10047
10048          // Reversed it...
10049          exp.cond.elseExp.destType = exp.destType ? exp.destType : exp.expType;
10050
10051          if(exp.cond.elseExp.destType)
10052             exp.cond.elseExp.destType.refCount++;
10053          ProcessExpressionType(exp.cond.elseExp);
10054
10055          // FIXED THIS: Was done before calling process on elseExp
10056          if(!exp.cond.elseExp.isConstant)
10057             exp.isConstant = false;
10058          break;
10059       }
10060       case extensionCompoundExp:
10061       {
10062          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10063          {
10064             Statement last = exp.compound.compound.statements->last;
10065             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10066             {
10067                ((Expression)last.expressions->last).destType = exp.destType;
10068                if(exp.destType)
10069                   exp.destType.refCount++;
10070             }
10071             ProcessStatement(exp.compound);
10072             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10073             if(exp.expType)
10074                exp.expType.refCount++;
10075          }
10076          break;
10077       }
10078       case classExp:
10079       {
10080          Specifier spec = exp._classExp.specifiers->first;
10081          if(spec && spec.type == nameSpecifier)
10082          {
10083             exp.expType = MkClassType(spec.name);
10084             exp.expType.kind = subClassType;
10085             exp.byReference = true;
10086          }
10087          else
10088          {
10089             exp.expType = MkClassType("ecere::com::Class");
10090             exp.byReference = true;
10091          }
10092          break;
10093       }
10094       case classDataExp:
10095       {
10096          Class _class = thisClass ? thisClass : currentClass;
10097          if(_class)
10098          {
10099             Identifier id = exp.classData.id;
10100             char structName[1024];
10101             Expression classExp;
10102             strcpy(structName, "__ecereClassData_");
10103             FullClassNameCat(structName, _class.fullName, false);
10104             exp.type = pointerExp;
10105             exp.member.member = id;
10106             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10107                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10108             else
10109                classExp = MkExpIdentifier(MkIdentifier("class"));
10110
10111             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10112                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10113                   MkExpBrackets(MkListOne(MkExpOp(
10114                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10115                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10116                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10117                      )));
10118
10119             ProcessExpressionType(exp);
10120             return;
10121          }
10122          break;
10123       }
10124       case arrayExp:
10125       {
10126          Type type = null;
10127          char * typeString = null;
10128          char typeStringBuf[1024];
10129          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
10130             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
10131          {
10132             Class templateClass = exp.destType._class.registered;
10133             typeString = templateClass.templateArgs[2].dataTypeString;
10134          }
10135          else if(exp.list)
10136          {
10137             // Guess type from expressions in the array
10138             Expression e;
10139             for(e = exp.list->first; e; e = e.next)
10140             {
10141                ProcessExpressionType(e);
10142                if(e.expType)
10143                {
10144                   if(!type) { type = e.expType; type.refCount++; }
10145                   else
10146                   {
10147                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
10148                      if(!MatchTypeExpression(e, type, null, false))
10149                      {
10150                         FreeType(type);
10151                         type = e.expType;
10152                         e.expType = null;
10153
10154                         e = exp.list->first;
10155                         ProcessExpressionType(e);
10156                         if(e.expType)
10157                         {
10158                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
10159                            if(!MatchTypeExpression(e, type, null, false))
10160                            {
10161                               FreeType(e.expType);
10162                               e.expType = null;
10163                               FreeType(type);
10164                               type = null;
10165                               break;
10166                            }
10167                         }
10168                      }
10169                   }
10170                   if(e.expType)
10171                   {
10172                      FreeType(e.expType);
10173                      e.expType = null;
10174                   }
10175                }
10176             }
10177             if(type)
10178             {
10179                typeStringBuf[0] = '\0';
10180                PrintTypeNoConst(type, typeStringBuf, false, true);
10181                typeString = typeStringBuf;
10182                FreeType(type);
10183                type = null;
10184             }
10185          }
10186          if(typeString)
10187          {
10188             /*
10189             (Container)& (struct BuiltInContainer)
10190             {
10191                ._vTbl = class(BuiltInContainer)._vTbl,
10192                ._class = class(BuiltInContainer),
10193                .refCount = 0,
10194                .data = (int[]){ 1, 7, 3, 4, 5 },
10195                .count = 5,
10196                .type = class(int),
10197             }
10198             */
10199             char templateString[1024];
10200             OldList * initializers = MkList();
10201             OldList * structInitializers = MkList();
10202             OldList * specs = MkList();
10203             Expression expExt;
10204             Declarator decl = SpecDeclFromString(typeString, specs, null);
10205             sprintf(templateString, "Container<%s>", typeString);
10206
10207             if(exp.list)
10208             {
10209                Expression e;
10210                type = ProcessTypeString(typeString, false);
10211                while(e = exp.list->first)
10212                {
10213                   exp.list->Remove(e);
10214                   e.destType = type;
10215                   type.refCount++;
10216                   ProcessExpressionType(e);
10217                   ListAdd(initializers, MkInitializerAssignment(e));
10218                }
10219                FreeType(type);
10220                delete exp.list;
10221             }
10222
10223             DeclareStruct("ecere::com::BuiltInContainer", false);
10224
10225             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
10226                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10227             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
10228                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10229             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
10230                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10231             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
10232                MkTypeName(specs, MkDeclaratorArray(decl, null)),
10233                MkInitializerList(initializers))));
10234                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10235             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
10236                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10237             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
10238                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10239             exp.expType = ProcessTypeString(templateString, false);
10240             exp.type = bracketsExp;
10241             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
10242                MkExpOp(null, '&',
10243                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
10244                   MkInitializerList(structInitializers)))));
10245             ProcessExpressionType(expExt);
10246          }
10247          else
10248          {
10249             exp.expType = ProcessTypeString("Container", false);
10250             Compiler_Error($"Couldn't determine type of array elements\n");
10251          }
10252          break;
10253       }
10254    }
10255
10256    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
10257    {
10258       FreeType(exp.expType);
10259       exp.expType = ReplaceThisClassType(thisClass);
10260    }
10261
10262    // Resolve structures here
10263    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
10264    {
10265       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
10266       // TODO: Fix members reference...
10267       if(symbol)
10268       {
10269          if(exp.expType.kind != enumType)
10270          {
10271             Type member;
10272             String enumName = CopyString(exp.expType.enumName);
10273
10274             // Fixed a memory leak on self-referencing C structs typedefs
10275             // by instantiating a new type rather than simply copying members
10276             // into exp.expType
10277             FreeType(exp.expType);
10278             exp.expType = Type { };
10279             exp.expType.kind = symbol.type.kind;
10280             exp.expType.refCount++;
10281             exp.expType.enumName = enumName;
10282
10283             exp.expType.members = symbol.type.members;
10284             for(member = symbol.type.members.first; member; member = member.next)
10285                member.refCount++;
10286          }
10287          else
10288          {
10289             NamedLink member;
10290             for(member = symbol.type.members.first; member; member = member.next)
10291             {
10292                NamedLink value { name = CopyString(member.name) };
10293                exp.expType.members.Add(value);
10294             }
10295          }
10296       }
10297    }
10298
10299    yylloc = exp.loc;
10300    if(exp.destType && (exp.destType.kind == voidType || exp.destType.kind == dummyType) );
10301    else if(exp.destType && !exp.destType.keepCast)
10302    {
10303       if(!CheckExpressionType(exp, exp.destType, false))
10304       {
10305          if(!exp.destType.count || unresolved)
10306          {
10307             if(!exp.expType)
10308             {
10309                yylloc = exp.loc;
10310                if(exp.destType.kind != ellipsisType)
10311                {
10312                   char type2[1024];
10313                   type2[0] = '\0';
10314                   if(inCompiler)
10315                   {
10316                      char expString[10240];
10317                      expString[0] = '\0';
10318
10319                      PrintType(exp.destType, type2, false, true);
10320
10321                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10322                      if(unresolved)
10323                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
10324                      else if(exp.type != dummyExp)
10325                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
10326                   }
10327                }
10328                else
10329                {
10330                   char expString[10240] ;
10331                   expString[0] = '\0';
10332                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10333
10334                   if(unresolved)
10335                      Compiler_Error($"unresolved identifier %s\n", expString);
10336                   else if(exp.type != dummyExp)
10337                      Compiler_Error($"couldn't determine type of %s\n", expString);
10338                }
10339             }
10340             else
10341             {
10342                char type1[1024];
10343                char type2[1024];
10344                type1[0] = '\0';
10345                type2[0] = '\0';
10346                if(inCompiler)
10347                {
10348                   PrintType(exp.expType, type1, false, true);
10349                   PrintType(exp.destType, type2, false, true);
10350                }
10351
10352                //CheckExpressionType(exp, exp.destType, false);
10353
10354                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
10355                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
10356                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
10357                else
10358                {
10359                   char expString[10240];
10360                   expString[0] = '\0';
10361                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10362
10363 #ifdef _DEBUG
10364                   CheckExpressionType(exp, exp.destType, false);
10365 #endif
10366                   // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
10367                   if(!sourceFile || (strcmp(sourceFile, "src\\lexer.ec") && strcmp(sourceFile, "src/lexer.ec") && strcmp(sourceFile, "src\\grammar.ec") && strcmp(sourceFile, "src/grammar.ec")))
10368                      Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
10369
10370                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
10371                   FreeType(exp.expType);
10372                   exp.destType.refCount++;
10373                   exp.expType = exp.destType;
10374                }
10375             }
10376          }
10377       }
10378       else if(exp.destType && exp.destType.kind == ellipsisType && exp.expType && exp.expType.passAsTemplate)
10379       {
10380          Expression newExp { };
10381          char typeString[1024];
10382          OldList * specs = MkList();
10383          Declarator decl;
10384
10385          typeString[0] = '\0';
10386
10387          *newExp = *exp;
10388
10389          if(exp.expType)  exp.expType.refCount++;
10390          if(exp.expType)  exp.expType.refCount++;
10391          exp.type = castExp;
10392          newExp.destType = exp.expType;
10393
10394          PrintType(exp.expType, typeString, false, false);
10395          decl = SpecDeclFromString(typeString, specs, null);
10396
10397          exp.cast.typeName = MkTypeName(specs, decl);
10398          exp.cast.exp = newExp;
10399       }
10400    }
10401    else if(unresolved)
10402    {
10403       if(exp.identifier._class && exp.identifier._class.name)
10404          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
10405       else if(exp.identifier.string && exp.identifier.string[0])
10406          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
10407    }
10408    else if(!exp.expType && exp.type != dummyExp)
10409    {
10410       char expString[10240];
10411       expString[0] = '\0';
10412       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10413       Compiler_Error($"couldn't determine type of %s\n", expString);
10414    }
10415
10416    // Let's try to support any_object & typed_object here:
10417    if(inCompiler)
10418       ApplyAnyObjectLogic(exp);
10419
10420    // Mark nohead classes as by reference, unless we're casting them to an integral type
10421    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
10422       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
10423          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
10424           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
10425    {
10426       exp.byReference = true;
10427    }
10428    yylloc = oldyylloc;
10429 }
10430
10431 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
10432 {
10433    // THIS CODE WILL FIND NEXT MEMBER...
10434    if(*curMember)
10435    {
10436       *curMember = (*curMember).next;
10437
10438       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
10439       {
10440          *curMember = subMemberStack[--(*subMemberStackPos)];
10441          *curMember = (*curMember).next;
10442       }
10443
10444       // SKIP ALL PROPERTIES HERE...
10445       while((*curMember) && (*curMember).isProperty)
10446          *curMember = (*curMember).next;
10447
10448       if(subMemberStackPos)
10449       {
10450          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
10451          {
10452             subMemberStack[(*subMemberStackPos)++] = *curMember;
10453
10454             *curMember = (*curMember).members.first;
10455             while(*curMember && (*curMember).isProperty)
10456                *curMember = (*curMember).next;
10457          }
10458       }
10459    }
10460    while(!*curMember)
10461    {
10462       if(!*curMember)
10463       {
10464          if(subMemberStackPos && *subMemberStackPos)
10465          {
10466             *curMember = subMemberStack[--(*subMemberStackPos)];
10467             *curMember = (*curMember).next;
10468          }
10469          else
10470          {
10471             Class lastCurClass = *curClass;
10472
10473             if(*curClass == _class) break;     // REACHED THE END
10474
10475             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
10476             *curMember = (*curClass).membersAndProperties.first;
10477          }
10478
10479          while((*curMember) && (*curMember).isProperty)
10480             *curMember = (*curMember).next;
10481          if(subMemberStackPos)
10482          {
10483             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
10484             {
10485                subMemberStack[(*subMemberStackPos)++] = *curMember;
10486
10487                *curMember = (*curMember).members.first;
10488                while(*curMember && (*curMember).isProperty)
10489                   *curMember = (*curMember).next;
10490             }
10491          }
10492       }
10493    }
10494 }
10495
10496
10497 static void ProcessInitializer(Initializer init, Type type)
10498 {
10499    switch(init.type)
10500    {
10501       case expInitializer:
10502          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
10503          {
10504             // TESTING THIS FOR SHUTTING = 0 WARNING
10505             if(init.exp && !init.exp.destType)
10506             {
10507                FreeType(init.exp.destType);
10508                init.exp.destType = type;
10509                if(type) type.refCount++;
10510             }
10511             if(init.exp)
10512             {
10513                ProcessExpressionType(init.exp);
10514                init.isConstant = init.exp.isConstant;
10515             }
10516             break;
10517          }
10518          else
10519          {
10520             Expression exp = init.exp;
10521             Instantiation inst = exp.instance;
10522             MembersInit members;
10523
10524             init.type = listInitializer;
10525             init.list = MkList();
10526
10527             if(inst.members)
10528             {
10529                for(members = inst.members->first; members; members = members.next)
10530                {
10531                   if(members.type == dataMembersInit)
10532                   {
10533                      MemberInit member;
10534                      for(member = members.dataMembers->first; member; member = member.next)
10535                      {
10536                         ListAdd(init.list, member.initializer);
10537                         member.initializer = null;
10538                      }
10539                   }
10540                   // Discard all MembersInitMethod
10541                }
10542             }
10543             FreeExpression(exp);
10544          }
10545       case listInitializer:
10546       {
10547          Initializer i;
10548          Type initializerType = null;
10549          Class curClass = null;
10550          DataMember curMember = null;
10551          DataMember subMemberStack[256];
10552          int subMemberStackPos = 0;
10553
10554          if(type && type.kind == arrayType)
10555             initializerType = Dereference(type);
10556          else if(type && (type.kind == structType || type.kind == unionType))
10557             initializerType = type.members.first;
10558
10559          for(i = init.list->first; i; i = i.next)
10560          {
10561             if(type && type.kind == classType && type._class && type._class.registered)
10562             {
10563                // 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)
10564                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
10565                // TODO: Generate error on initializing a private data member this way from another module...
10566                if(curMember)
10567                {
10568                   if(!curMember.dataType)
10569                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
10570                   initializerType = curMember.dataType;
10571                }
10572             }
10573             ProcessInitializer(i, initializerType);
10574             if(initializerType && type && (type.kind == structType || type.kind == unionType))
10575                initializerType = initializerType.next;
10576             if(!i.isConstant)
10577                init.isConstant = false;
10578          }
10579
10580          if(type && type.kind == arrayType)
10581             FreeType(initializerType);
10582
10583          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
10584          {
10585             Compiler_Error($"Assigning list initializer to non list\n");
10586          }
10587          break;
10588       }
10589    }
10590 }
10591
10592 static void ProcessSpecifier(Specifier spec, bool declareStruct)
10593 {
10594    switch(spec.type)
10595    {
10596       case baseSpecifier:
10597       {
10598          if(spec.specifier == THISCLASS)
10599          {
10600             if(thisClass)
10601             {
10602                spec.type = nameSpecifier;
10603                spec.name = ReplaceThisClass(thisClass);
10604                spec.symbol = FindClass(spec.name);
10605                ProcessSpecifier(spec, declareStruct);
10606             }
10607          }
10608          break;
10609       }
10610       case nameSpecifier:
10611       {
10612          Symbol symbol = FindType(curContext, spec.name);
10613          if(symbol)
10614             DeclareType(symbol.type, true, true);
10615          else if((symbol = spec.symbol /*FindClass(spec.name)*/) && symbol.registered && symbol.registered.type == structClass && declareStruct)
10616             DeclareStruct(spec.name, false);
10617          break;
10618       }
10619       case enumSpecifier:
10620       {
10621          Enumerator e;
10622          if(spec.list)
10623          {
10624             for(e = spec.list->first; e; e = e.next)
10625             {
10626                if(e.exp)
10627                   ProcessExpressionType(e.exp);
10628             }
10629          }
10630          break;
10631       }
10632       case structSpecifier:
10633       case unionSpecifier:
10634       {
10635          if(spec.definitions)
10636          {
10637             ClassDef def;
10638             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
10639             //if(symbol)
10640                ProcessClass(spec.definitions, symbol);
10641             /*else
10642             {
10643                for(def = spec.definitions->first; def; def = def.next)
10644                {
10645                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
10646                      ProcessDeclaration(def.decl);
10647                }
10648             }*/
10649          }
10650          break;
10651       }
10652       /*
10653       case classSpecifier:
10654       {
10655          Symbol classSym = FindClass(spec.name);
10656          if(classSym && classSym.registered && classSym.registered.type == structClass)
10657             DeclareStruct(spec.name, false);
10658          break;
10659       }
10660       */
10661    }
10662 }
10663
10664
10665 static void ProcessDeclarator(Declarator decl)
10666 {
10667    switch(decl.type)
10668    {
10669       case identifierDeclarator:
10670          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
10671          {
10672             FreeSpecifier(decl.identifier._class);
10673             decl.identifier._class = null;
10674          }
10675          break;
10676       case arrayDeclarator:
10677          if(decl.array.exp)
10678             ProcessExpressionType(decl.array.exp);
10679       case structDeclarator:
10680       case bracketsDeclarator:
10681       case functionDeclarator:
10682       case pointerDeclarator:
10683       case extendedDeclarator:
10684       case extendedDeclaratorEnd:
10685          if(decl.declarator)
10686             ProcessDeclarator(decl.declarator);
10687          if(decl.type == functionDeclarator)
10688          {
10689             Identifier id = GetDeclId(decl);
10690             if(id && id._class)
10691             {
10692                TypeName param
10693                {
10694                   qualifiers = MkListOne(id._class);
10695                   declarator = null;
10696                };
10697                if(!decl.function.parameters)
10698                   decl.function.parameters = MkList();
10699                decl.function.parameters->Insert(null, param);
10700                id._class = null;
10701             }
10702             if(decl.function.parameters)
10703             {
10704                TypeName param;
10705
10706                for(param = decl.function.parameters->first; param; param = param.next)
10707                {
10708                   if(param.qualifiers && param.qualifiers->first)
10709                   {
10710                      Specifier spec = param.qualifiers->first;
10711                      if(spec && spec.specifier == TYPED_OBJECT)
10712                      {
10713                         Declarator d = param.declarator;
10714                         TypeName newParam
10715                         {
10716                            qualifiers = MkListOne(MkSpecifier(VOID));
10717                            declarator = MkDeclaratorPointer(MkPointer(null,null), d);
10718                         };
10719
10720                         FreeList(param.qualifiers, FreeSpecifier);
10721
10722                         param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
10723                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
10724
10725                         decl.function.parameters->Insert(param, newParam);
10726                         param = newParam;
10727                      }
10728                      else if(spec && spec.specifier == ANY_OBJECT)
10729                      {
10730                         Declarator d = param.declarator;
10731
10732                         FreeList(param.qualifiers, FreeSpecifier);
10733
10734                         param.qualifiers = MkListOne(MkSpecifier(VOID));
10735                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
10736                      }
10737                      else if(spec.specifier == THISCLASS)
10738                      {
10739                         if(thisClass)
10740                         {
10741                            spec.type = nameSpecifier;
10742                            spec.name = ReplaceThisClass(thisClass);
10743                            spec.symbol = FindClass(spec.name);
10744                            ProcessSpecifier(spec, false);
10745                         }
10746                      }
10747                   }
10748
10749                   if(param.declarator)
10750                      ProcessDeclarator(param.declarator);
10751                }
10752             }
10753          }
10754          break;
10755    }
10756 }
10757
10758 static void ProcessDeclaration(Declaration decl)
10759 {
10760    yylloc = decl.loc;
10761    switch(decl.type)
10762    {
10763       case initDeclaration:
10764       {
10765          bool declareStruct = false;
10766          /*
10767          lineNum = decl.pos.line;
10768          column = decl.pos.col;
10769          */
10770
10771          if(decl.declarators)
10772          {
10773             InitDeclarator d;
10774
10775             for(d = decl.declarators->first; d; d = d.next)
10776             {
10777                Type type, subType;
10778                ProcessDeclarator(d.declarator);
10779
10780                type = ProcessType(decl.specifiers, d.declarator);
10781
10782                if(d.initializer)
10783                {
10784                   ProcessInitializer(d.initializer, type);
10785
10786                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
10787
10788                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
10789                      d.initializer.exp.type == instanceExp)
10790                   {
10791                      if(type.kind == classType && type._class ==
10792                         d.initializer.exp.expType._class)
10793                      {
10794                         Instantiation inst = d.initializer.exp.instance;
10795                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
10796
10797                         d.initializer.exp.instance = null;
10798                         if(decl.specifiers)
10799                            FreeList(decl.specifiers, FreeSpecifier);
10800                         FreeList(decl.declarators, FreeInitDeclarator);
10801
10802                         d = null;
10803
10804                         decl.type = instDeclaration;
10805                         decl.inst = inst;
10806                      }
10807                   }
10808                }
10809                for(subType = type; subType;)
10810                {
10811                   if(subType.kind == classType)
10812                   {
10813                      declareStruct = true;
10814                      break;
10815                   }
10816                   else if(subType.kind == pointerType)
10817                      break;
10818                   else if(subType.kind == arrayType)
10819                      subType = subType.arrayType;
10820                   else
10821                      break;
10822                }
10823
10824                FreeType(type);
10825                if(!d) break;
10826             }
10827          }
10828
10829          if(decl.specifiers)
10830          {
10831             Specifier s;
10832             for(s = decl.specifiers->first; s; s = s.next)
10833             {
10834                ProcessSpecifier(s, declareStruct);
10835             }
10836          }
10837          break;
10838       }
10839       case instDeclaration:
10840       {
10841          ProcessInstantiationType(decl.inst);
10842          break;
10843       }
10844       case structDeclaration:
10845       {
10846          Specifier spec;
10847          Declarator d;
10848          bool declareStruct = false;
10849
10850          if(decl.declarators)
10851          {
10852             for(d = decl.declarators->first; d; d = d.next)
10853             {
10854                Type type = ProcessType(decl.specifiers, d.declarator);
10855                Type subType;
10856                ProcessDeclarator(d);
10857                for(subType = type; subType;)
10858                {
10859                   if(subType.kind == classType)
10860                   {
10861                      declareStruct = true;
10862                      break;
10863                   }
10864                   else if(subType.kind == pointerType)
10865                      break;
10866                   else if(subType.kind == arrayType)
10867                      subType = subType.arrayType;
10868                   else
10869                      break;
10870                }
10871                FreeType(type);
10872             }
10873          }
10874          if(decl.specifiers)
10875          {
10876             for(spec = decl.specifiers->first; spec; spec = spec.next)
10877                ProcessSpecifier(spec, declareStruct);
10878          }
10879          break;
10880       }
10881    }
10882 }
10883
10884 static FunctionDefinition curFunction;
10885
10886 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
10887 {
10888    char propName[1024], propNameM[1024];
10889    char getName[1024], setName[1024];
10890    OldList * args;
10891
10892    DeclareProperty(prop, setName, getName);
10893
10894    // eInstance_FireWatchers(object, prop);
10895    strcpy(propName, "__ecereProp_");
10896    FullClassNameCat(propName, prop._class.fullName, false);
10897    strcat(propName, "_");
10898    // strcat(propName, prop.name);
10899    FullClassNameCat(propName, prop.name, true);
10900    MangleClassName(propName);
10901
10902    strcpy(propNameM, "__ecerePropM_");
10903    FullClassNameCat(propNameM, prop._class.fullName, false);
10904    strcat(propNameM, "_");
10905    // strcat(propNameM, prop.name);
10906    FullClassNameCat(propNameM, prop.name, true);
10907    MangleClassName(propNameM);
10908
10909    if(prop.isWatchable)
10910    {
10911       args = MkList();
10912       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
10913       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
10914       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
10915
10916       args = MkList();
10917       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
10918       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
10919       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
10920    }
10921
10922
10923    {
10924       args = MkList();
10925       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
10926       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
10927       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
10928
10929       args = MkList();
10930       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
10931       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
10932       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
10933    }
10934
10935    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
10936       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
10937       curFunction.propSet.fireWatchersDone = true;
10938 }
10939
10940 static void ProcessStatement(Statement stmt)
10941 {
10942    yylloc = stmt.loc;
10943    /*
10944    lineNum = stmt.pos.line;
10945    column = stmt.pos.col;
10946    */
10947    switch(stmt.type)
10948    {
10949       case labeledStmt:
10950          ProcessStatement(stmt.labeled.stmt);
10951          break;
10952       case caseStmt:
10953          // This expression should be constant...
10954          if(stmt.caseStmt.exp)
10955          {
10956             FreeType(stmt.caseStmt.exp.destType);
10957             stmt.caseStmt.exp.destType = curSwitchType;
10958             if(curSwitchType) curSwitchType.refCount++;
10959             ProcessExpressionType(stmt.caseStmt.exp);
10960             ComputeExpression(stmt.caseStmt.exp);
10961          }
10962          if(stmt.caseStmt.stmt)
10963             ProcessStatement(stmt.caseStmt.stmt);
10964          break;
10965       case compoundStmt:
10966       {
10967          if(stmt.compound.context)
10968          {
10969             Declaration decl;
10970             Statement s;
10971
10972             Statement prevCompound = curCompound;
10973             Context prevContext = curContext;
10974
10975             if(!stmt.compound.isSwitch)
10976             {
10977                curCompound = stmt;
10978                curContext = stmt.compound.context;
10979             }
10980
10981             if(stmt.compound.declarations)
10982             {
10983                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
10984                   ProcessDeclaration(decl);
10985             }
10986             if(stmt.compound.statements)
10987             {
10988                for(s = stmt.compound.statements->first; s; s = s.next)
10989                   ProcessStatement(s);
10990             }
10991
10992             curContext = prevContext;
10993             curCompound = prevCompound;
10994          }
10995          break;
10996       }
10997       case expressionStmt:
10998       {
10999          Expression exp;
11000          if(stmt.expressions)
11001          {
11002             for(exp = stmt.expressions->first; exp; exp = exp.next)
11003                ProcessExpressionType(exp);
11004          }
11005          break;
11006       }
11007       case ifStmt:
11008       {
11009          Expression exp;
11010
11011          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
11012          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
11013          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
11014          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
11015          {
11016             ProcessExpressionType(exp);
11017          }
11018          if(stmt.ifStmt.stmt)
11019             ProcessStatement(stmt.ifStmt.stmt);
11020          if(stmt.ifStmt.elseStmt)
11021             ProcessStatement(stmt.ifStmt.elseStmt);
11022          break;
11023       }
11024       case switchStmt:
11025       {
11026          Type oldSwitchType = curSwitchType;
11027          if(stmt.switchStmt.exp)
11028          {
11029             Expression exp;
11030             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
11031             {
11032                if(!exp.next)
11033                {
11034                   /*
11035                   Type destType
11036                   {
11037                      kind = intType;
11038                      refCount = 1;
11039                   };
11040                   e.exp.destType = destType;
11041                   */
11042
11043                   ProcessExpressionType(exp);
11044                }
11045                if(!exp.next)
11046                   curSwitchType = exp.expType;
11047             }
11048          }
11049          ProcessStatement(stmt.switchStmt.stmt);
11050          curSwitchType = oldSwitchType;
11051          break;
11052       }
11053       case whileStmt:
11054       {
11055          if(stmt.whileStmt.exp)
11056          {
11057             Expression exp;
11058
11059             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
11060             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
11061             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
11062             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
11063             {
11064                ProcessExpressionType(exp);
11065             }
11066          }
11067          if(stmt.whileStmt.stmt)
11068             ProcessStatement(stmt.whileStmt.stmt);
11069          break;
11070       }
11071       case doWhileStmt:
11072       {
11073          if(stmt.doWhile.exp)
11074          {
11075             Expression exp;
11076
11077             if(stmt.doWhile.exp->last)
11078             {
11079                FreeType(((Expression)stmt.doWhile.exp->last).destType);
11080                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
11081                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
11082             }
11083             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
11084             {
11085                ProcessExpressionType(exp);
11086             }
11087          }
11088          if(stmt.doWhile.stmt)
11089             ProcessStatement(stmt.doWhile.stmt);
11090          break;
11091       }
11092       case forStmt:
11093       {
11094          Expression exp;
11095          if(stmt.forStmt.init)
11096             ProcessStatement(stmt.forStmt.init);
11097
11098          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
11099          {
11100             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
11101             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
11102             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
11103          }
11104
11105          if(stmt.forStmt.check)
11106             ProcessStatement(stmt.forStmt.check);
11107          if(stmt.forStmt.increment)
11108          {
11109             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
11110                ProcessExpressionType(exp);
11111          }
11112
11113          if(stmt.forStmt.stmt)
11114             ProcessStatement(stmt.forStmt.stmt);
11115          break;
11116       }
11117       case forEachStmt:
11118       {
11119          Identifier id = stmt.forEachStmt.id;
11120          OldList * exp = stmt.forEachStmt.exp;
11121          OldList * filter = stmt.forEachStmt.filter;
11122          Statement block = stmt.forEachStmt.stmt;
11123          char iteratorType[1024];
11124          Type source;
11125          Expression e;
11126          bool isBuiltin = exp && exp->last &&
11127             (((Expression)exp->last).type == ExpressionType::arrayExp ||
11128               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
11129          Expression arrayExp;
11130          char * typeString = null;
11131          int builtinCount = 0;
11132
11133          for(e = exp ? exp->first : null; e; e = e.next)
11134          {
11135             if(!e.next)
11136             {
11137                FreeType(e.destType);
11138                e.destType = ProcessTypeString("Container", false);
11139             }
11140             if(!isBuiltin || e.next)
11141                ProcessExpressionType(e);
11142          }
11143
11144          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
11145          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
11146             eClass_IsDerived(source._class.registered, containerClass)))
11147          {
11148             Class _class = source ? source._class.registered : null;
11149             Symbol symbol;
11150             Expression expIt = null;
11151             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false, isAVLTree = false;
11152             Class arrayClass = eSystem_FindClass(privateModule, "Array");
11153             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
11154             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
11155             stmt.type = compoundStmt;
11156
11157             stmt.compound.context = Context { };
11158             stmt.compound.context.parent = curContext;
11159             curContext = stmt.compound.context;
11160
11161             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
11162             {
11163                Class mapClass = eSystem_FindClass(privateModule, "Map");
11164                Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
11165                isCustomAVLTree = true;
11166                if(eClass_IsDerived(source._class.registered, avlTreeClass))
11167                   isAVLTree = true;
11168                else if(eClass_IsDerived(source._class.registered, mapClass))
11169                   isMap = true;
11170             }
11171             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
11172             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
11173             {
11174                Class listClass = eSystem_FindClass(privateModule, "List");
11175                isLinkList = true;
11176                isList = eClass_IsDerived(source._class.registered, listClass);
11177             }
11178
11179             if(isArray)
11180             {
11181                Declarator decl;
11182                OldList * specs = MkList();
11183                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
11184                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
11185                stmt.compound.declarations = MkListOne(
11186                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11187                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11188                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
11189                      MkInitializerAssignment(MkExpBrackets(exp))))));
11190             }
11191             else if(isBuiltin)
11192             {
11193                Type type = null;
11194                char typeStringBuf[1024];
11195
11196                // TODO: Merge this code?
11197                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
11198                if(((Expression)exp->last).type == castExp)
11199                {
11200                   TypeName typeName = ((Expression)exp->last).cast.typeName;
11201                   if(typeName)
11202                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
11203                }
11204
11205                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
11206                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
11207                   arrayExp.destType._class.registered.templateArgs)
11208                {
11209                   Class templateClass = arrayExp.destType._class.registered;
11210                   typeString = templateClass.templateArgs[2].dataTypeString;
11211                }
11212                else if(arrayExp.list)
11213                {
11214                   // Guess type from expressions in the array
11215                   Expression e;
11216                   for(e = arrayExp.list->first; e; e = e.next)
11217                   {
11218                      ProcessExpressionType(e);
11219                      if(e.expType)
11220                      {
11221                         if(!type) { type = e.expType; type.refCount++; }
11222                         else
11223                         {
11224                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11225                            if(!MatchTypeExpression(e, type, null, false))
11226                            {
11227                               FreeType(type);
11228                               type = e.expType;
11229                               e.expType = null;
11230
11231                               e = arrayExp.list->first;
11232                               ProcessExpressionType(e);
11233                               if(e.expType)
11234                               {
11235                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
11236                                  if(!MatchTypeExpression(e, type, null, false))
11237                                  {
11238                                     FreeType(e.expType);
11239                                     e.expType = null;
11240                                     FreeType(type);
11241                                     type = null;
11242                                     break;
11243                                  }
11244                               }
11245                            }
11246                         }
11247                         if(e.expType)
11248                         {
11249                            FreeType(e.expType);
11250                            e.expType = null;
11251                         }
11252                      }
11253                   }
11254                   if(type)
11255                   {
11256                      typeStringBuf[0] = '\0';
11257                      PrintType(type, typeStringBuf, false, true);
11258                      typeString = typeStringBuf;
11259                      FreeType(type);
11260                   }
11261                }
11262                if(typeString)
11263                {
11264                   OldList * initializers = MkList();
11265                   Declarator decl;
11266                   OldList * specs = MkList();
11267                   if(arrayExp.list)
11268                   {
11269                      Expression e;
11270
11271                      builtinCount = arrayExp.list->count;
11272                      type = ProcessTypeString(typeString, false);
11273                      while(e = arrayExp.list->first)
11274                      {
11275                         arrayExp.list->Remove(e);
11276                         e.destType = type;
11277                         type.refCount++;
11278                         ProcessExpressionType(e);
11279                         ListAdd(initializers, MkInitializerAssignment(e));
11280                      }
11281                      FreeType(type);
11282                      delete arrayExp.list;
11283                   }
11284                   decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
11285                   stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
11286                      MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
11287
11288                   ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
11289                      PlugDeclarator(
11290                         /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
11291                         ), MkInitializerList(initializers)))));
11292                   FreeList(exp, FreeExpression);
11293                }
11294                else
11295                {
11296                   arrayExp.expType = ProcessTypeString("Container", false);
11297                   Compiler_Error($"Couldn't determine type of array elements\n");
11298                }
11299
11300                /*
11301                Declarator decl;
11302                OldList * specs = MkList();
11303
11304                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
11305                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
11306                stmt.compound.declarations = MkListOne(
11307                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11308                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
11309                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
11310                      MkInitializerAssignment(MkExpBrackets(exp))))));
11311                */
11312             }
11313             else if(isLinkList && !isList)
11314             {
11315                Declarator decl;
11316                OldList * specs = MkList();
11317                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
11318                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11319                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11320                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
11321                      MkInitializerAssignment(MkExpBrackets(exp))))));
11322             }
11323             /*else if(isCustomAVLTree)
11324             {
11325                Declarator decl;
11326                OldList * specs = MkList();
11327                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
11328                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11329                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11330                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
11331                      MkInitializerAssignment(MkExpBrackets(exp))))));
11332             }*/
11333             else if(_class.templateArgs)
11334             {
11335                if(isMap)
11336                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
11337                else
11338                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
11339
11340                stmt.compound.declarations = MkListOne(
11341                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
11342                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
11343                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
11344             }
11345             symbol = FindSymbol(id.string, curContext, curContext, false, false);
11346
11347             if(block)
11348             {
11349                // Reparent sub-contexts in this statement
11350                switch(block.type)
11351                {
11352                   case compoundStmt:
11353                      if(block.compound.context)
11354                         block.compound.context.parent = stmt.compound.context;
11355                      break;
11356                   case ifStmt:
11357                      if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
11358                         block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
11359                      if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
11360                         block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
11361                      break;
11362                   case switchStmt:
11363                      if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
11364                         block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
11365                      break;
11366                   case whileStmt:
11367                      if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
11368                         block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
11369                      break;
11370                   case doWhileStmt:
11371                      if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
11372                         block.doWhile.stmt.compound.context.parent = stmt.compound.context;
11373                      break;
11374                   case forStmt:
11375                      if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
11376                         block.forStmt.stmt.compound.context.parent = stmt.compound.context;
11377                      break;
11378                   case forEachStmt:
11379                      if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
11380                         block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
11381                      break;
11382                   /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
11383                   case labeledStmt:
11384                   case caseStmt
11385                   case expressionStmt:
11386                   case gotoStmt:
11387                   case continueStmt:
11388                   case breakStmt
11389                   case returnStmt:
11390                   case asmStmt:
11391                   case badDeclarationStmt:
11392                   case fireWatchersStmt:
11393                   case stopWatchingStmt:
11394                   case watchStmt:
11395                   */
11396                }
11397             }
11398             if(filter)
11399             {
11400                block = MkIfStmt(filter, block, null);
11401             }
11402             if(isArray)
11403             {
11404                stmt.compound.statements = MkListOne(MkForStmt(
11405                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
11406                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
11407                      MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
11408                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
11409                   block));
11410               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11411               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11412               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11413             }
11414             else if(isBuiltin)
11415             {
11416                char count[128];
11417                //OldList * specs = MkList();
11418                // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
11419
11420                sprintf(count, "%d", builtinCount);
11421
11422                stmt.compound.statements = MkListOne(MkForStmt(
11423                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
11424                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
11425                      MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
11426                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
11427                   block));
11428
11429                /*
11430                Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
11431                stmt.compound.statements = MkListOne(MkForStmt(
11432                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
11433                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
11434                      MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
11435                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
11436                   block));
11437               */
11438               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11439               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11440               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11441             }
11442             else if(isLinkList && !isList)
11443             {
11444                Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
11445                Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
11446                if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
11447                   !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
11448                {
11449                   stmt.compound.statements = MkListOne(MkForStmt(
11450                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
11451                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
11452                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
11453                      block));
11454                }
11455                else
11456                {
11457                   OldList * specs = MkList();
11458                   Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
11459                   stmt.compound.statements = MkListOne(MkForStmt(
11460                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
11461                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
11462                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
11463                         MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
11464                            MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
11465                      block));
11466                }
11467                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11468                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11469                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11470             }
11471             /*else if(isCustomAVLTree)
11472             {
11473                stmt.compound.statements = MkListOne(MkForStmt(
11474                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
11475                      MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
11476                   MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
11477                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
11478                   block));
11479
11480                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11481                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11482                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11483             }*/
11484             else
11485             {
11486                stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
11487                   MkIdentifier("Next")), null)), block));
11488             }
11489             ProcessExpressionType(expIt);
11490             if(stmt.compound.declarations->first)
11491                ProcessDeclaration(stmt.compound.declarations->first);
11492
11493             if(symbol)
11494                symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
11495
11496             ProcessStatement(stmt);
11497             curContext = stmt.compound.context.parent;
11498             break;
11499          }
11500          else
11501          {
11502             Compiler_Error($"Expression is not a container\n");
11503          }
11504          break;
11505       }
11506       case gotoStmt:
11507          break;
11508       case continueStmt:
11509          break;
11510       case breakStmt:
11511          break;
11512       case returnStmt:
11513       {
11514          Expression exp;
11515          if(stmt.expressions)
11516          {
11517             for(exp = stmt.expressions->first; exp; exp = exp.next)
11518             {
11519                if(!exp.next)
11520                {
11521                   if(curFunction && !curFunction.type)
11522                      curFunction.type = ProcessType(
11523                         curFunction.specifiers, curFunction.declarator);
11524                   FreeType(exp.destType);
11525                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
11526                   if(exp.destType) exp.destType.refCount++;
11527                }
11528                ProcessExpressionType(exp);
11529             }
11530          }
11531          break;
11532       }
11533       case badDeclarationStmt:
11534       {
11535          ProcessDeclaration(stmt.decl);
11536          break;
11537       }
11538       case asmStmt:
11539       {
11540          AsmField field;
11541          if(stmt.asmStmt.inputFields)
11542          {
11543             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
11544                if(field.expression)
11545                   ProcessExpressionType(field.expression);
11546          }
11547          if(stmt.asmStmt.outputFields)
11548          {
11549             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
11550                if(field.expression)
11551                   ProcessExpressionType(field.expression);
11552          }
11553          if(stmt.asmStmt.clobberedFields)
11554          {
11555             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
11556             {
11557                if(field.expression)
11558                   ProcessExpressionType(field.expression);
11559             }
11560          }
11561          break;
11562       }
11563       case watchStmt:
11564       {
11565          PropertyWatch propWatch;
11566          OldList * watches = stmt._watch.watches;
11567          Expression object = stmt._watch.object;
11568          Expression watcher = stmt._watch.watcher;
11569          if(watcher)
11570             ProcessExpressionType(watcher);
11571          if(object)
11572             ProcessExpressionType(object);
11573
11574          if(inCompiler)
11575          {
11576             if(watcher || thisClass)
11577             {
11578                External external = curExternal;
11579                Context context = curContext;
11580
11581                stmt.type = expressionStmt;
11582                stmt.expressions = MkList();
11583
11584                curExternal = external.prev;
11585
11586                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
11587                {
11588                   ClassFunction func;
11589                   char watcherName[1024];
11590                   Class watcherClass = watcher ?
11591                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
11592                   External createdExternal;
11593
11594                   // Create a declaration above
11595                   External externalDecl = MkExternalDeclaration(null);
11596                   ast->Insert(curExternal.prev, externalDecl);
11597
11598                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
11599                   if(propWatch.deleteWatch)
11600                      strcat(watcherName, "_delete");
11601                   else
11602                   {
11603                      Identifier propID;
11604                      for(propID = propWatch.properties->first; propID; propID = propID.next)
11605                      {
11606                         strcat(watcherName, "_");
11607                         strcat(watcherName, propID.string);
11608                      }
11609                   }
11610
11611                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
11612                   {
11613                      // TESTING THIS STUFF... BEWARE OF SYMBOL ID ISSUES
11614                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
11615                         //MkListOne(MkTypeName(MkListOne(MkSpecifier(VOID)), null))), null);
11616                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
11617                      ProcessClassFunctionBody(func, propWatch.compound);
11618                      propWatch.compound = null;
11619
11620                      //afterExternal = afterExternal ? afterExternal : curExternal;
11621
11622                      //createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal.prev);
11623                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
11624                      // TESTING THIS...
11625                      createdExternal.symbol.idCode = external.symbol.idCode;
11626
11627                      curExternal = createdExternal;
11628                      ProcessFunction(createdExternal.function);
11629
11630
11631                      // Create a declaration above
11632                      {
11633                         Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
11634                            MkListOne(MkInitDeclarator(CopyDeclarator(createdExternal.function.declarator), null)));
11635                         externalDecl.declaration = decl;
11636                         if(decl.symbol && !decl.symbol.pointerExternal)
11637                            decl.symbol.pointerExternal = externalDecl;
11638                      }
11639
11640                      if(propWatch.deleteWatch)
11641                      {
11642                         OldList * args = MkList();
11643                         ListAdd(args, CopyExpression(object));
11644                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
11645                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
11646                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
11647                      }
11648                      else
11649                      {
11650                         Class _class = object.expType._class.registered;
11651                         Identifier propID;
11652
11653                         for(propID = propWatch.properties->first; propID; propID = propID.next)
11654                         {
11655                            char propName[1024];
11656                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
11657                            if(prop)
11658                            {
11659                               char getName[1024], setName[1024];
11660                               OldList * args = MkList();
11661
11662                               DeclareProperty(prop, setName, getName);
11663
11664                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
11665                               strcpy(propName, "__ecereProp_");
11666                               FullClassNameCat(propName, prop._class.fullName, false);
11667                               strcat(propName, "_");
11668                               // strcat(propName, prop.name);
11669                               FullClassNameCat(propName, prop.name, true);
11670
11671                               ListAdd(args, CopyExpression(object));
11672                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11673                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
11674                               ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
11675
11676                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
11677                            }
11678                            else
11679                               Compiler_Error($"Property %s not found in class %s\n", prop.name, _class.fullName);
11680                         }
11681                      }
11682                   }
11683                   else
11684                      Compiler_Error($"Invalid watched object\n");
11685                }
11686
11687                curExternal = external;
11688                curContext = context;
11689
11690                if(watcher)
11691                   FreeExpression(watcher);
11692                if(object)
11693                   FreeExpression(object);
11694                FreeList(watches, FreePropertyWatch);
11695             }
11696             else
11697                Compiler_Error($"No observer specified and not inside a _class\n");
11698          }
11699          else
11700          {
11701             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
11702             {
11703                ProcessStatement(propWatch.compound);
11704             }
11705
11706          }
11707          break;
11708       }
11709       case fireWatchersStmt:
11710       {
11711          OldList * watches = stmt._watch.watches;
11712          Expression object = stmt._watch.object;
11713          Class _class;
11714          // DEBUGGER BUG: Why doesn't watches evaluate to null??
11715          // printf("%X\n", watches);
11716          // printf("%X\n", stmt._watch.watches);
11717          if(object)
11718             ProcessExpressionType(object);
11719
11720          if(inCompiler)
11721          {
11722             _class = object ?
11723                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
11724
11725             if(_class)
11726             {
11727                Identifier propID;
11728
11729                stmt.type = expressionStmt;
11730                stmt.expressions = MkList();
11731
11732                // Check if we're inside a property set
11733                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11734                {
11735                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
11736                }
11737                else if(!watches)
11738                {
11739                   //Compiler_Error($"No property specified and not inside a property set\n");
11740                }
11741                if(watches)
11742                {
11743                   for(propID = watches->first; propID; propID = propID.next)
11744                   {
11745                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
11746                      if(prop)
11747                      {
11748                         CreateFireWatcher(prop, object, stmt);
11749                      }
11750                      else
11751                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
11752                   }
11753                }
11754                else
11755                {
11756                   // Fire all properties!
11757                   Property prop;
11758                   Class base;
11759                   for(base = _class; base; base = base.base)
11760                   {
11761                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
11762                      {
11763                         if(prop.isProperty && prop.isWatchable)
11764                         {
11765                            CreateFireWatcher(prop, object, stmt);
11766                         }
11767                      }
11768                   }
11769                }
11770
11771                if(object)
11772                   FreeExpression(object);
11773                FreeList(watches, FreeIdentifier);
11774             }
11775             else
11776                Compiler_Error($"Invalid object specified and not inside a class\n");
11777          }
11778          break;
11779       }
11780       case stopWatchingStmt:
11781       {
11782          OldList * watches = stmt._watch.watches;
11783          Expression object = stmt._watch.object;
11784          Expression watcher = stmt._watch.watcher;
11785          Class _class;
11786          if(object)
11787             ProcessExpressionType(object);
11788          if(watcher)
11789             ProcessExpressionType(watcher);
11790          if(inCompiler)
11791          {
11792             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
11793
11794             if(watcher || thisClass)
11795             {
11796                if(_class)
11797                {
11798                   Identifier propID;
11799
11800                   stmt.type = expressionStmt;
11801                   stmt.expressions = MkList();
11802
11803                   if(!watches)
11804                   {
11805                      OldList * args;
11806                      // eInstance_StopWatching(object, null, watcher);
11807                      args = MkList();
11808                      ListAdd(args, CopyExpression(object));
11809                      ListAdd(args, MkExpConstant("0"));
11810                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
11811                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
11812                   }
11813                   else
11814                   {
11815                      for(propID = watches->first; propID; propID = propID.next)
11816                      {
11817                         char propName[1024];
11818                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
11819                         if(prop)
11820                         {
11821                            char getName[1024], setName[1024];
11822                            OldList * args = MkList();
11823
11824                            DeclareProperty(prop, setName, getName);
11825
11826                            // eInstance_StopWatching(object, prop, watcher);
11827                            strcpy(propName, "__ecereProp_");
11828                            FullClassNameCat(propName, prop._class.fullName, false);
11829                            strcat(propName, "_");
11830                            // strcat(propName, prop.name);
11831                            FullClassNameCat(propName, prop.name, true);
11832                            MangleClassName(propName);
11833
11834                            ListAdd(args, CopyExpression(object));
11835                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11836                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
11837                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
11838                         }
11839                         else
11840                            Compiler_Error($"Property %s not found in class %s\n", prop.name, _class.fullName);
11841                      }
11842                   }
11843
11844                   if(object)
11845                      FreeExpression(object);
11846                   if(watcher)
11847                      FreeExpression(watcher);
11848                   FreeList(watches, FreeIdentifier);
11849                }
11850                else
11851                   Compiler_Error($"Invalid object specified and not inside a class\n");
11852             }
11853             else
11854                Compiler_Error($"No observer specified and not inside a class\n");
11855          }
11856          break;
11857       }
11858    }
11859 }
11860
11861 static void ProcessFunction(FunctionDefinition function)
11862 {
11863    Identifier id = GetDeclId(function.declarator);
11864    Symbol symbol = function.declarator ? function.declarator.symbol : null;
11865    Type type = symbol ? symbol.type : null;
11866    Class oldThisClass = thisClass;
11867    Context oldTopContext = topContext;
11868
11869    yylloc = function.loc;
11870    // Process thisClass
11871
11872    if(type && type.thisClass)
11873    {
11874       Symbol classSym = type.thisClass;
11875       Class _class = type.thisClass.registered;
11876       char className[1024];
11877       char structName[1024];
11878       Declarator funcDecl;
11879       Symbol thisSymbol;
11880
11881       bool typedObject = false;
11882
11883       if(_class && !_class.base)
11884       {
11885          _class = currentClass;
11886          if(_class && !_class.symbol)
11887             _class.symbol = FindClass(_class.fullName);
11888          classSym = _class ? _class.symbol : null;
11889          typedObject = true;
11890       }
11891
11892       thisClass = _class;
11893
11894       if(inCompiler && _class)
11895       {
11896          if(type.kind == functionType)
11897          {
11898             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
11899             {
11900                //TypeName param = symbol.type.params.first;
11901                Type param = symbol.type.params.first;
11902                symbol.type.params.Remove(param);
11903                //FreeTypeName(param);
11904                FreeType(param);
11905             }
11906             if(type.classObjectType != classPointer)
11907             {
11908                symbol.type.params.Insert(null, MkClassType(_class.fullName));
11909                symbol.type.staticMethod = true;
11910                symbol.type.thisClass = null;
11911
11912                // HIGH DANGER: VERIFYING THIS...
11913                symbol.type.extraParam = false;
11914             }
11915          }
11916
11917          strcpy(className, "__ecereClass_");
11918          FullClassNameCat(className, _class.fullName, true);
11919
11920          MangleClassName(className);
11921
11922          structName[0] = 0;
11923          FullClassNameCat(structName, _class.fullName, false);
11924
11925          // [class] this
11926
11927
11928          funcDecl = GetFuncDecl(function.declarator);
11929          if(funcDecl)
11930          {
11931             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
11932             {
11933                TypeName param = funcDecl.function.parameters->first;
11934                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
11935                {
11936                   funcDecl.function.parameters->Remove(param);
11937                   FreeTypeName(param);
11938                }
11939             }
11940
11941             // DANGER: Watch for this... Check if it's a Conversion?
11942             // if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
11943
11944             // WAS TRYING THIS FOR CONVERSION PROPERTIES ON NOHEAD CLASSES: if((_class.type == structClass) || function != (FunctionDefinition)symbol.externalSet)
11945             if(!function.propertyNoThis)
11946             {
11947                TypeName thisParam;
11948
11949                if(type.classObjectType != classPointer)
11950                {
11951                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
11952                   if(!funcDecl.function.parameters)
11953                      funcDecl.function.parameters = MkList();
11954                   funcDecl.function.parameters->Insert(null, thisParam);
11955                }
11956
11957                if(typedObject)
11958                {
11959                   if(type.classObjectType != classPointer)
11960                   {
11961                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
11962                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
11963                   }
11964
11965                   thisParam = TypeName
11966                   {
11967                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11968                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11969                   };
11970                   funcDecl.function.parameters->Insert(null, thisParam);
11971                }
11972             }
11973          }
11974
11975          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
11976          {
11977             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
11978             funcDecl = GetFuncDecl(initDecl.declarator);
11979             if(funcDecl)
11980             {
11981                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
11982                {
11983                   TypeName param = funcDecl.function.parameters->first;
11984                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
11985                   {
11986                      funcDecl.function.parameters->Remove(param);
11987                      FreeTypeName(param);
11988                   }
11989                }
11990
11991                if(type.classObjectType != classPointer)
11992                {
11993                   // DANGER: Watch for this... Check if it's a Conversion?
11994                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
11995                   {
11996                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
11997
11998                      if(!funcDecl.function.parameters)
11999                         funcDecl.function.parameters = MkList();
12000                      funcDecl.function.parameters->Insert(null, thisParam);
12001                   }
12002                }
12003             }
12004          }
12005       }
12006
12007       // Add this to the context
12008       if(function.body)
12009       {
12010          if(type.classObjectType != classPointer)
12011          {
12012             thisSymbol = Symbol
12013             {
12014                string = CopyString("this");
12015                type = classSym ? MkClassType(classSym.string) : null; //_class.fullName);
12016             };
12017             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
12018
12019             if(typedObject && thisSymbol.type)
12020             {
12021                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
12022                thisSymbol.type.byReference = type.byReference;
12023                thisSymbol.type.typedByReference = type.byReference;
12024                /*
12025                thisSymbol = Symbol { string = CopyString("class") };
12026                function.body.compound.context.symbols.Add(thisSymbol);
12027                */
12028             }
12029          }
12030       }
12031
12032       // Pointer to class data
12033
12034       if(inCompiler && _class && (_class.type == normalClass /*|| _class.type == noHeadClass*/) && type.classObjectType != classPointer)
12035       {
12036          DataMember member = null;
12037          {
12038             Class base;
12039             for(base = _class; base && base.type != systemClass; base = base.next)
12040             {
12041                for(member = base.membersAndProperties.first; member; member = member.next)
12042                   if(!member.isProperty)
12043                      break;
12044                if(member)
12045                   break;
12046             }
12047          }
12048          for(member = _class.membersAndProperties.first; member; member = member.next)
12049             if(!member.isProperty)
12050                break;
12051          if(member)
12052          {
12053             char pointerName[1024];
12054
12055             Declaration decl;
12056             Initializer initializer;
12057             Expression exp, bytePtr;
12058
12059             strcpy(pointerName, "__ecerePointer_");
12060             FullClassNameCat(pointerName, _class.fullName, false);
12061             {
12062                char className[1024];
12063                strcpy(className, "__ecereClass_");
12064                FullClassNameCat(className, classSym.string, true);
12065                MangleClassName(className);
12066
12067                // Testing This
12068                DeclareClass(classSym, className);
12069             }
12070
12071             // ((byte *) this)
12072             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
12073
12074             if(_class.fixed)
12075             {
12076                char string[256];
12077                sprintf(string, "%d", _class.offset);
12078                exp = QBrackets(MkExpOp(bytePtr, '+', MkExpConstant(string)));
12079             }
12080             else
12081             {
12082                // ([bytePtr] + [className]->offset)
12083                exp = QBrackets(MkExpOp(bytePtr, '+',
12084                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
12085             }
12086
12087             // (this ? [exp] : 0)
12088             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
12089             exp.expType = Type
12090             {
12091                refCount = 1;
12092                kind = pointerType;
12093                type = Type { refCount = 1, kind = voidType };
12094             };
12095
12096             if(function.body)
12097             {
12098                yylloc = function.body.loc;
12099                // ([structName] *) [exp]
12100                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
12101                initializer = MkInitializerAssignment(
12102                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
12103
12104                // [structName] * [pointerName] = [initializer];
12105                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
12106
12107                {
12108                   Context prevContext = curContext;
12109                   curContext = function.body.compound.context;
12110
12111                   decl = MkDeclaration(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)),
12112                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
12113
12114                   curContext = prevContext;
12115                }
12116
12117                // WHY?
12118                decl.symbol = null;
12119
12120                if(!function.body.compound.declarations)
12121                   function.body.compound.declarations = MkList();
12122                function.body.compound.declarations->Insert(null, decl);
12123             }
12124          }
12125       }
12126
12127
12128       // Loop through the function and replace undeclared identifiers
12129       // which are a member of the class (methods, properties or data)
12130       // by "this.[member]"
12131    }
12132    else
12133       thisClass = null;
12134
12135    if(id)
12136    {
12137       FreeSpecifier(id._class);
12138       id._class = null;
12139
12140       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12141       {
12142          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12143          id = GetDeclId(initDecl.declarator);
12144
12145          FreeSpecifier(id._class);
12146          id._class = null;
12147       }
12148    }
12149    if(function.body)
12150       topContext = function.body.compound.context;
12151    {
12152       FunctionDefinition oldFunction = curFunction;
12153       curFunction = function;
12154       if(function.body)
12155          ProcessStatement(function.body);
12156
12157       // If this is a property set and no firewatchers has been done yet, add one here
12158       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
12159       {
12160          Statement prevCompound = curCompound;
12161          Context prevContext = curContext;
12162
12163          Statement fireWatchers = MkFireWatchersStmt(null, null);
12164          if(!function.body.compound.statements) function.body.compound.statements = MkList();
12165          ListAdd(function.body.compound.statements, fireWatchers);
12166
12167          curCompound = function.body;
12168          curContext = function.body.compound.context;
12169
12170          ProcessStatement(fireWatchers);
12171
12172          curContext = prevContext;
12173          curCompound = prevCompound;
12174
12175       }
12176
12177       curFunction = oldFunction;
12178    }
12179
12180    if(function.declarator)
12181    {
12182       ProcessDeclarator(function.declarator);
12183    }
12184
12185    topContext = oldTopContext;
12186    thisClass = oldThisClass;
12187 }
12188
12189 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
12190 static void ProcessClass(OldList definitions, Symbol symbol)
12191 {
12192    ClassDef def;
12193    External external = curExternal;
12194    Class regClass = symbol ? symbol.registered : null;
12195
12196    // Process all functions
12197    for(def = definitions.first; def; def = def.next)
12198    {
12199       if(def.type == functionClassDef)
12200       {
12201          if(def.function.declarator)
12202             curExternal = def.function.declarator.symbol.pointerExternal;
12203          else
12204             curExternal = external;
12205
12206          ProcessFunction((FunctionDefinition)def.function);
12207       }
12208       else if(def.type == declarationClassDef)
12209       {
12210          if(def.decl.type == instDeclaration)
12211          {
12212             thisClass = regClass;
12213             ProcessInstantiationType(def.decl.inst);
12214             thisClass = null;
12215          }
12216          // Testing this
12217          else
12218          {
12219             Class backThisClass = thisClass;
12220             if(regClass) thisClass = regClass;
12221             ProcessDeclaration(def.decl);
12222             thisClass = backThisClass;
12223          }
12224       }
12225       else if(def.type == defaultPropertiesClassDef && def.defProperties)
12226       {
12227          MemberInit defProperty;
12228
12229          // Add this to the context
12230          Symbol thisSymbol = Symbol
12231          {
12232             string = CopyString("this");
12233             type = regClass ? MkClassType(regClass.fullName) : null;
12234          };
12235          globalContext.symbols.Add((BTNode)thisSymbol);
12236
12237          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
12238          {
12239             thisClass = regClass;
12240             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
12241             thisClass = null;
12242          }
12243
12244          globalContext.symbols.Remove((BTNode)thisSymbol);
12245          FreeSymbol(thisSymbol);
12246       }
12247       else if(def.type == propertyClassDef && def.propertyDef)
12248       {
12249          PropertyDef prop = def.propertyDef;
12250
12251          // Add this to the context
12252          /*
12253          Symbol thisSymbol = Symbol { string = CopyString("this"), type = MkClassType(regClass.fullName) };
12254          globalContext.symbols.Add(thisSymbol);
12255          */
12256
12257          thisClass = regClass;
12258          if(prop.setStmt)
12259          {
12260             if(regClass)
12261             {
12262                Symbol thisSymbol
12263                {
12264                   string = CopyString("this");
12265                   type = MkClassType(regClass.fullName);
12266                };
12267                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
12268             }
12269
12270             curExternal = prop.symbol ? prop.symbol.externalSet : null;
12271             ProcessStatement(prop.setStmt);
12272          }
12273          if(prop.getStmt)
12274          {
12275             if(regClass)
12276             {
12277                Symbol thisSymbol
12278                {
12279                   string = CopyString("this");
12280                   type = MkClassType(regClass.fullName);
12281                };
12282                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
12283             }
12284
12285             curExternal = prop.symbol ? prop.symbol.externalGet : null;
12286             ProcessStatement(prop.getStmt);
12287          }
12288          if(prop.issetStmt)
12289          {
12290             if(regClass)
12291             {
12292                Symbol thisSymbol
12293                {
12294                   string = CopyString("this");
12295                   type = MkClassType(regClass.fullName);
12296                };
12297                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
12298             }
12299
12300             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
12301             ProcessStatement(prop.issetStmt);
12302          }
12303
12304          thisClass = null;
12305
12306          /*
12307          globalContext.symbols.Remove(thisSymbol);
12308          FreeSymbol(thisSymbol);
12309          */
12310       }
12311       else if(def.type == propertyWatchClassDef && def.propertyWatch)
12312       {
12313          PropertyWatch propertyWatch = def.propertyWatch;
12314
12315          thisClass = regClass;
12316          if(propertyWatch.compound)
12317          {
12318             Symbol thisSymbol
12319             {
12320                string = CopyString("this");
12321                type = regClass ? MkClassType(regClass.fullName) : null;
12322             };
12323
12324             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
12325
12326             curExternal = null;
12327             ProcessStatement(propertyWatch.compound);
12328          }
12329          thisClass = null;
12330       }
12331    }
12332 }
12333
12334 void DeclareFunctionUtil(String s)
12335 {
12336    GlobalFunction function = eSystem_FindFunction(privateModule, s);
12337    if(function)
12338    {
12339       char name[1024];
12340       name[0] = 0;
12341       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
12342          strcpy(name, "__ecereFunction_");
12343       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
12344       DeclareFunction(function, name);
12345    }
12346 }
12347
12348 void ComputeDataTypes()
12349 {
12350    External external;
12351    External temp { };
12352    External after = null;
12353
12354    currentClass = null;
12355
12356    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
12357
12358    for(external = ast->first; external; external = external.next)
12359    {
12360       if(external.type == declarationExternal)
12361       {
12362          Declaration decl = external.declaration;
12363          if(decl)
12364          {
12365             OldList * decls = decl.declarators;
12366             if(decls)
12367             {
12368                InitDeclarator initDecl = decls->first;
12369                if(initDecl)
12370                {
12371                   Declarator declarator = initDecl.declarator;
12372                   if(declarator && declarator.type == identifierDeclarator)
12373                   {
12374                      Identifier id = declarator.identifier;
12375                      if(id && id.string)
12376                      {
12377                         if(!strcmp(id.string, "uintptr_t") || !strcmp(id.string, "intptr_t") || !strcmp(id.string, "size_t") || !strcmp(id.string, "ssize_t"))
12378                         {
12379                            external.symbol.id = -1001, external.symbol.idCode = -1001;
12380                            after = external;
12381                         }
12382                      }
12383                   }
12384                }
12385             }
12386          }
12387        }
12388    }
12389
12390    temp.symbol = Symbol { id = -1000, idCode = -1000 };
12391    ast->Insert(after, temp);
12392    curExternal = temp;
12393
12394    DeclareFunctionUtil("eSystem_New");
12395    DeclareFunctionUtil("eSystem_New0");
12396    DeclareFunctionUtil("eSystem_Renew");
12397    DeclareFunctionUtil("eSystem_Renew0");
12398    DeclareFunctionUtil("eClass_GetProperty");
12399
12400    DeclareStruct("ecere::com::Class", false);
12401    DeclareStruct("ecere::com::Instance", false);
12402    DeclareStruct("ecere::com::Property", false);
12403    DeclareStruct("ecere::com::DataMember", false);
12404    DeclareStruct("ecere::com::Method", false);
12405    DeclareStruct("ecere::com::SerialBuffer", false);
12406    DeclareStruct("ecere::com::ClassTemplateArgument", false);
12407
12408    ast->Remove(temp);
12409
12410    for(external = ast->first; external; external = external.next)
12411    {
12412       afterExternal = curExternal = external;
12413       if(external.type == functionExternal)
12414       {
12415          currentClass = external.function._class;
12416          ProcessFunction(external.function);
12417       }
12418       // There shouldn't be any _class member access here anyways...
12419       else if(external.type == declarationExternal)
12420       {
12421          currentClass = null;
12422          ProcessDeclaration(external.declaration);
12423       }
12424       else if(external.type == classExternal)
12425       {
12426          ClassDefinition _class = external._class;
12427          currentClass = external.symbol.registered;
12428          if(_class.definitions)
12429          {
12430             ProcessClass(_class.definitions, _class.symbol);
12431          }
12432          if(inCompiler)
12433          {
12434             // Free class data...
12435             ast->Remove(external);
12436             delete external;
12437          }
12438       }
12439       else if(external.type == nameSpaceExternal)
12440       {
12441          thisNameSpace = external.id.string;
12442       }
12443    }
12444    currentClass = null;
12445    thisNameSpace = null;
12446
12447    delete temp.symbol;
12448    delete temp;
12449 }