compiler/libec: Fixed crash on 'property not found' message
[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 > MAXINT)
205       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
206    else
207       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
208    if(result > MAXINT || result < MININT)
209       strcat(temp, "LL");
210    return CopyString(temp);
211 }
212
213 public char * PrintUInt(uint64 result)
214 {
215    char temp[100];
216    if(result > MAXDWORD)
217       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
218    else if(result > MAXINT)
219       sprintf(temp, FORMAT64HEX /*"0x%I64X"*/, result);
220    else
221       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
222    return CopyString(temp);
223 }
224
225 public char * PrintInt64(int64 result)
226 {
227    char temp[100];
228    sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
229    return CopyString(temp);
230 }
231
232 public char * PrintUInt64(uint64 result)
233 {
234    char temp[100];
235    if(result > MAXINT64)
236       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
237    else
238       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
239    return CopyString(temp);
240 }
241
242 public char * PrintHexUInt(uint64 result)
243 {
244    char temp[100];
245    if(result > MAXDWORD)
246       sprintf(temp, FORMAT64HEX /*"0x%I64xLL"*/, result);
247    else
248       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
249    if(result > MAXDWORD)
250       strcat(temp, "LL");
251    return CopyString(temp);
252 }
253
254 public char * PrintHexUInt64(uint64 result)
255 {
256    char temp[100];
257    if(result > MAXDWORD)
258       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
259    else
260       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
261    return CopyString(temp);
262 }
263
264 public char * PrintShort(short result)
265 {
266    char temp[100];
267    sprintf(temp, "%d", (unsigned short)result);
268    return CopyString(temp);
269 }
270
271 public char * PrintUShort(unsigned short result)
272 {
273    char temp[100];
274    if(result > 32767)
275       sprintf(temp, "0x%X", (int)result);
276    else
277       sprintf(temp, "%d", (int)result);
278    return CopyString(temp);
279 }
280
281 public char * PrintChar(char result)
282 {
283    char temp[100];
284    if(result > 0 && isprint(result))
285       sprintf(temp, "'%c'", result);
286    else if(result < 0)
287       sprintf(temp, "%d", (int)result);
288    else
289       //sprintf(temp, "%#X", result);
290       sprintf(temp, "0x%X", (unsigned char)result);
291    return CopyString(temp);
292 }
293
294 public char * PrintUChar(unsigned char result)
295 {
296    char temp[100];
297    sprintf(temp, "0x%X", result);
298    return CopyString(temp);
299 }
300
301 public char * PrintFloat(float result)
302 {
303    char temp[350];
304    if(result.isInf)
305    {
306       if(result.signBit)
307          strcpy(temp, "-inf");
308       else
309          strcpy(temp, "inf");
310    }
311    else if(result.isNan)
312    {
313       if(result.signBit)
314          strcpy(temp, "-nan");
315       else
316          strcpy(temp, "nan");
317    }
318    else
319       sprintf(temp, "%.16ff", result);
320    return CopyString(temp);
321 }
322
323 public char * PrintDouble(double result)
324 {
325    char temp[350];
326    if(result.isInf)
327    {
328       if(result.signBit)
329          strcpy(temp, "-inf");
330       else
331          strcpy(temp, "inf");
332    }
333    else if(result.isNan)
334    {
335       if(result.signBit)
336          strcpy(temp, "-nan");
337       else
338          strcpy(temp, "nan");
339    }
340    else
341       sprintf(temp, "%.16f", result);
342    return CopyString(temp);
343 }
344
345 ////////////////////////////////////////////////////////////////////////
346 ////////////////////////////////////////////////////////////////////////
347
348 //public Operand GetOperand(Expression exp);
349
350 #define GETVALUE(name, t) \
351    public bool GetOp##name(Operand op2, t * value2) \
352    {                                                        \
353       if(op2.kind == intType && op2.type.isSigned) *value2 = (t) op2.i; \
354       else if(op2.kind == intType) *value2 = (t) op2.ui;                 \
355       else if(op2.kind == int64Type && op2.type.isSigned) *value2 = (t) op2.i64; \
356       else if(op2.kind == int64Type) *value2 = (t) op2.ui64;                 \
357       else if(op2.kind == intSizeType && op2.type.isSigned) *value2 = (t) op2.i64; \
358       else if(op2.kind == intSizeType) *value2 = (t) op2.ui64; \
359       else if(op2.kind == intPtrType && op2.type.isSigned) *value2 = (t) op2.i64; \
360       else if(op2.kind == intPtrType) *value2 = (t) op2.ui64;                 \
361       else if(op2.kind == shortType && op2.type.isSigned) *value2 = (t) op2.s;   \
362       else if(op2.kind == shortType) *value2 = (t) op2.us;                        \
363       else if(op2.kind == charType && op2.type.isSigned) *value2 = (t) op2.c;    \
364       else if(op2.kind == _BoolType || op2.kind == charType) *value2 = (t) op2.uc; \
365       else if(op2.kind == floatType) *value2 = (t) op2.f;                         \
366       else if(op2.kind == doubleType) *value2 = (t) op2.d;                        \
367       else if(op2.kind == pointerType) *value2 = (t) op2.ui64;                    \
368       else                                                                          \
369          return false;                                                              \
370       return true;                                                                  \
371    } \
372    public bool Get##name(Expression exp, t * value2) \
373    {                                                        \
374       Operand op2 = GetOperand(exp);                        \
375       return GetOp##name(op2, value2); \
376    }
377
378 // To help the deubugger currently not preprocessing...
379 #define HELP(x) x
380
381 GETVALUE(Int, HELP(int));
382 GETVALUE(UInt, HELP(unsigned int));
383 GETVALUE(Int64, HELP(int64));
384 GETVALUE(UInt64, HELP(uint64));
385 GETVALUE(IntPtr, HELP(intptr));
386 GETVALUE(UIntPtr, HELP(uintptr));
387 GETVALUE(IntSize, HELP(intsize));
388 GETVALUE(UIntSize, HELP(uintsize));
389 GETVALUE(Short, HELP(short));
390 GETVALUE(UShort, HELP(unsigned short));
391 GETVALUE(Char, HELP(char));
392 GETVALUE(UChar, HELP(unsigned char));
393 GETVALUE(Float, HELP(float));
394 GETVALUE(Double, HELP(double));
395
396 void ComputeExpression(Expression exp);
397
398 void ComputeClassMembers(Class _class, bool isMember)
399 {
400    DataMember member = isMember ? (DataMember) _class : null;
401    Context context = isMember ? null : SetupTemplatesContext(_class);
402    if(member || ((_class.type == bitClass || _class.type == normalClass || _class.type == structClass || _class.type == noHeadClass) &&
403                  (_class.type == bitClass || (!_class.structSize || _class.structSize == _class.offset)) && _class.computeSize))
404    {
405       int c;
406       int unionMemberOffset = 0;
407       int bitFields = 0;
408
409       /*
410       if(!member && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass) && _class.memberOffset && _class.memberOffset > _class.base.structSize)
411          _class.memberOffset = (_class.base && _class.base.type != systemClass) ? _class.base.structSize : 0;
412       */
413
414       if(member)
415       {
416          member.memberOffset = 0;
417          if(targetBits < sizeof(void *) * 8)
418             member.structAlignment = 0;
419       }
420       else if(targetBits < sizeof(void *) * 8)
421          _class.structAlignment = 0;
422
423       // Confusion here: non struct classes seem to have their memberOffset restart at 0 at each hierarchy level
424       if(!member && ((_class.type == normalClass || _class.type == noHeadClass) || (_class.type == structClass && _class.memberOffset && _class.memberOffset > _class.base.structSize)))
425          _class.memberOffset = (_class.base && _class.type == structClass) ? _class.base.structSize : 0;
426
427       if(!member && _class.destructionWatchOffset)
428          _class.memberOffset += sizeof(OldList);
429
430       // To avoid reentrancy...
431       //_class.structSize = -1;
432
433       {
434          DataMember dataMember;
435          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
436          {
437             if(!dataMember.isProperty)
438             {
439                if(dataMember.type == normalMember && dataMember.dataTypeString && !dataMember.dataType)
440                {
441                   dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
442                   /*if(!dataMember.dataType)
443                      dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
444                      */
445                }
446             }
447          }
448       }
449
450       {
451          DataMember dataMember;
452          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
453          {
454             if(!dataMember.isProperty && (dataMember.type != normalMember || dataMember.dataTypeString))
455             {
456                if(!isMember && _class.type == bitClass && dataMember.dataType)
457                {
458                   BitMember bitMember = (BitMember) dataMember;
459                   uint64 mask = 0;
460                   int d;
461
462                   ComputeTypeSize(dataMember.dataType);
463
464                   if(bitMember.pos == -1) bitMember.pos = _class.memberOffset;
465                   if(!bitMember.size) bitMember.size = dataMember.dataType.size * 8;
466
467                   _class.memberOffset = bitMember.pos + bitMember.size;
468                   for(d = 0; d<bitMember.size; d++)
469                   {
470                      if(d)
471                         mask <<= 1;
472                      mask |= 1;
473                   }
474                   bitMember.mask = mask << bitMember.pos;
475                }
476                else if(dataMember.type == normalMember && dataMember.dataType)
477                {
478                   int size;
479                   int alignment = 0;
480
481                   // Prevent infinite recursion
482                   if(dataMember.dataType.kind != classType ||
483                      ((!dataMember.dataType._class || !dataMember.dataType._class.registered || dataMember.dataType._class.registered != _class ||
484                      _class.type != structClass)))
485                      ComputeTypeSize(dataMember.dataType);
486
487                   if(dataMember.dataType.bitFieldCount)
488                   {
489                      bitFields += dataMember.dataType.bitFieldCount;
490                      size = 0;
491                   }
492                   else
493                   {
494                      if(bitFields)
495                      {
496                         int size = (bitFields + 7) / 8;
497
498                         if(isMember)
499                         {
500                            // TESTING THIS PADDING CODE
501                            if(alignment)
502                            {
503                               member.structAlignment = Max(member.structAlignment, alignment);
504
505                               if(member.memberOffset % alignment)
506                                  member.memberOffset += alignment - (member.memberOffset % alignment);
507                            }
508
509                            dataMember.offset = member.memberOffset;
510                            if(member.type == unionMember)
511                               unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
512                            else
513                            {
514                               member.memberOffset += size;
515                            }
516                         }
517                         else
518                         {
519                            // TESTING THIS PADDING CODE
520                            if(alignment)
521                            {
522                               _class.structAlignment = Max(_class.structAlignment, alignment);
523
524                               if(_class.memberOffset % alignment)
525                                  _class.memberOffset += alignment - (_class.memberOffset % alignment);
526                            }
527
528                            dataMember.offset = _class.memberOffset;
529                            _class.memberOffset += size;
530                         }
531                         bitFields = 0;
532                      }
533                      size = dataMember.dataType.size;
534                      alignment = dataMember.dataType.alignment;
535                   }
536
537                   if(isMember)
538                   {
539                      // TESTING THIS PADDING CODE
540                      if(alignment)
541                      {
542                         member.structAlignment = Max(member.structAlignment, alignment);
543
544                         if(member.memberOffset % alignment)
545                            member.memberOffset += alignment - (member.memberOffset % alignment);
546                      }
547
548                      dataMember.offset = member.memberOffset;
549                      if(member.type == unionMember)
550                         unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
551                      else
552                      {
553                         member.memberOffset += size;
554                      }
555                   }
556                   else
557                   {
558                      // TESTING THIS PADDING CODE
559                      if(alignment)
560                      {
561                         _class.structAlignment = Max(_class.structAlignment, alignment);
562
563                         if(_class.memberOffset % alignment)
564                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
565                      }
566
567                      dataMember.offset = _class.memberOffset;
568                      _class.memberOffset += size;
569                   }
570                }
571                else
572                {
573                   int alignment;
574
575                   ComputeClassMembers((Class)dataMember, true);
576                   alignment = dataMember.structAlignment;
577
578                   if(isMember)
579                   {
580                      if(alignment)
581                      {
582                         if(member.memberOffset % alignment)
583                            member.memberOffset += alignment - (member.memberOffset % alignment);
584
585                         member.structAlignment = Max(member.structAlignment, alignment);
586                      }
587                      dataMember.offset = member.memberOffset;
588                      if(member.type == unionMember)
589                         unionMemberOffset = Max(unionMemberOffset, dataMember.memberOffset);
590                      else
591                         member.memberOffset += dataMember.memberOffset;
592                   }
593                   else
594                   {
595                      if(alignment)
596                      {
597                         if(_class.memberOffset % alignment)
598                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
599                         _class.structAlignment = Max(_class.structAlignment, alignment);
600                      }
601                      dataMember.offset = _class.memberOffset;
602                      _class.memberOffset += dataMember.memberOffset;
603                   }
604                }
605             }
606          }
607          if(bitFields)
608          {
609             int alignment = 0;
610             int size = (bitFields + 7) / 8;
611
612             if(isMember)
613             {
614                // TESTING THIS PADDING CODE
615                if(alignment)
616                {
617                   member.structAlignment = Max(member.structAlignment, alignment);
618
619                   if(member.memberOffset % alignment)
620                      member.memberOffset += alignment - (member.memberOffset % alignment);
621                }
622
623                if(member.type == unionMember)
624                   unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
625                else
626                {
627                   member.memberOffset += size;
628                }
629             }
630             else
631             {
632                // TESTING THIS PADDING CODE
633                if(alignment)
634                {
635                   _class.structAlignment = Max(_class.structAlignment, alignment);
636
637                   if(_class.memberOffset % alignment)
638                      _class.memberOffset += alignment - (_class.memberOffset % alignment);
639                }
640                _class.memberOffset += size;
641             }
642             bitFields = 0;
643          }
644       }
645       if(member && member.type == unionMember)
646       {
647          member.memberOffset = unionMemberOffset;
648       }
649
650       if(!isMember)
651       {
652          /*if(_class.type == structClass)
653             _class.size = _class.memberOffset;
654          else
655          */
656
657          if(_class.type != bitClass)
658          {
659             int extra = 0;
660             if(_class.structAlignment)
661             {
662                if(_class.memberOffset % _class.structAlignment)
663                   extra += _class.structAlignment - (_class.memberOffset % _class.structAlignment);
664             }
665             _class.structSize = (_class.base ? (_class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize) : 0) + _class.memberOffset + extra;
666             if(!member)
667             {
668                Property prop;
669                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
670                {
671                   if(prop.isProperty && prop.isWatchable)
672                   {
673                      prop.watcherOffset = _class.structSize;
674                      _class.structSize += sizeof(OldList);
675                   }
676                }
677             }
678
679             // Fix Derivatives
680             {
681                OldLink derivative;
682                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
683                {
684                   Class deriv = derivative.data;
685
686                   if(deriv.computeSize)
687                   {
688                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
689                      deriv.offset = /*_class.offset + */_class.structSize;
690                      deriv.memberOffset = 0;
691                      // ----------------------
692
693                      deriv.structSize = deriv.offset;
694
695                      ComputeClassMembers(deriv, false);
696                   }
697                }
698             }
699          }
700       }
701    }
702    if(context)
703       FinishTemplatesContext(context);
704 }
705
706 public void ComputeModuleClasses(Module module)
707 {
708    Class _class;
709    OldLink subModule;
710
711    for(subModule = module.modules.first; subModule; subModule = subModule.next)
712       ComputeModuleClasses(subModule.data);
713    for(_class = module.classes.first; _class; _class = _class.next)
714       ComputeClassMembers(_class, false);
715 }
716
717
718 public int ComputeTypeSize(Type type)
719 {
720    uint size = type ? type.size : 0;
721    if(!size && type && !type.computing)
722    {
723       type.computing = true;
724       switch(type.kind)
725       {
726          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
727          case charType: type.alignment = size = sizeof(char); break;
728          case intType: type.alignment = size = sizeof(int); break;
729          case int64Type: type.alignment = size = sizeof(int64); break;
730          case intPtrType: type.alignment = size = targetBits / 8; break;
731          case intSizeType: type.alignment = size = targetBits / 8; break;
732          case longType: type.alignment = size = sizeof(long); break;
733          case shortType: type.alignment = size = sizeof(short); break;
734          case floatType: type.alignment = size = sizeof(float); break;
735          case doubleType: type.alignment = size = sizeof(double); break;
736          case classType:
737          {
738             Class _class = type._class ? type._class.registered : null;
739
740             if(_class && _class.type == structClass)
741             {
742                // Ensure all members are properly registered
743                ComputeClassMembers(_class, false);
744                type.alignment = _class.structAlignment;
745                size = _class.structSize;
746                if(type.alignment && size % type.alignment)
747                   size += type.alignment - (size % type.alignment);
748
749             }
750             else if(_class && (_class.type == unitClass ||
751                    _class.type == enumClass ||
752                    _class.type == bitClass))
753             {
754                if(!_class.dataType)
755                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
756                size = type.alignment = ComputeTypeSize(_class.dataType);
757             }
758             else
759                size = type.alignment = targetBits / 8; // sizeof(Instance *);
760             break;
761          }
762          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */break;
763          case arrayType:
764             if(type.arraySizeExp)
765             {
766                ProcessExpressionType(type.arraySizeExp);
767                ComputeExpression(type.arraySizeExp);
768                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType && type.arraySizeExp.expType.kind != enumType &&
769                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
770                {
771                   Location oldLoc = yylloc;
772                   // bool isConstant = type.arraySizeExp.isConstant;
773                   char expression[10240];
774                   expression[0] = '\0';
775                   type.arraySizeExp.expType = null;
776                   yylloc = type.arraySizeExp.loc;
777                   if(inCompiler)
778                      PrintExpression(type.arraySizeExp, expression);
779                   Compiler_Error($"Array size not constant int (%s)\n", expression);
780                   yylloc = oldLoc;
781                }
782                GetInt(type.arraySizeExp, &type.arraySize);
783             }
784             else if(type.enumClass)
785             {
786                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
787                {
788                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
789                }
790                else
791                   type.arraySize = 0;
792             }
793             else
794             {
795                // Unimplemented auto size
796                type.arraySize = 0;
797             }
798
799             size = ComputeTypeSize(type.type) * type.arraySize;
800             if(type.type)
801                type.alignment = type.type.alignment;
802
803             break;
804          case structType:
805          {
806             Type member;
807             for(member = type.members.first; member; member = member.next)
808             {
809                uint addSize = ComputeTypeSize(member);
810
811                member.offset = size;
812                if(member.alignment && size % member.alignment)
813                   member.offset += member.alignment - (size % member.alignment);
814                size = member.offset;
815
816                type.alignment = Max(type.alignment, member.alignment);
817                size += addSize;
818             }
819             if(type.alignment && size % type.alignment)
820                size += type.alignment - (size % type.alignment);
821             break;
822          }
823          case unionType:
824          {
825             Type member;
826             for(member = type.members.first; member; member = member.next)
827             {
828                uint addSize = ComputeTypeSize(member);
829
830                member.offset = size;
831                if(member.alignment && size % member.alignment)
832                   member.offset += member.alignment - (size % member.alignment);
833                size = member.offset;
834
835                type.alignment = Max(type.alignment, member.alignment);
836                size = Max(size, addSize);
837             }
838             if(type.alignment && size % type.alignment)
839                size += type.alignment - (size % type.alignment);
840             break;
841          }
842          case templateType:
843          {
844             TemplateParameter param = type.templateParameter;
845             Type baseType = ProcessTemplateParameterType(param);
846             if(baseType)
847             {
848                size = ComputeTypeSize(baseType);
849                type.alignment = baseType.alignment;
850             }
851             else
852                type.alignment = size = sizeof(uint64);
853             break;
854          }
855          case enumType:
856          {
857             type.alignment = size = sizeof(enum { test });
858             break;
859          }
860          case thisClassType:
861          {
862             type.alignment = size = targetBits / 8; //sizeof(void *);
863             break;
864          }
865       }
866       type.size = size;
867       type.computing = false;
868    }
869    return size;
870 }
871
872
873 /*static */int AddMembers(OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
874 {
875    // This function is in need of a major review when implementing private members etc.
876    DataMember topMember = isMember ? (DataMember) _class : null;
877    uint totalSize = 0;
878    uint maxSize = 0;
879    int alignment, size;
880    DataMember member;
881    Context context = isMember ? null : SetupTemplatesContext(_class);
882    if(addedPadding)
883       *addedPadding = false;
884
885    if(!isMember && _class.base)
886    {
887       maxSize = _class.structSize;
888       //if(_class.base.type != systemClass) // Commented out with new Instance _class
889       {
890          // DANGER: Testing this noHeadClass here...
891          if(_class.type == structClass || _class.type == noHeadClass)
892             /*totalSize = */AddMembers(declarations, _class.base, false, &totalSize, topClass, null);
893          else
894          {
895             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
896             if(maxSize > baseSize)
897                maxSize -= baseSize;
898             else
899                maxSize = 0;
900          }
901       }
902    }
903
904    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
905    {
906       if(!member.isProperty)
907       {
908          switch(member.type)
909          {
910             case normalMember:
911             {
912                if(member.dataTypeString)
913                {
914                   OldList * specs = MkList(), * decls = MkList();
915                   Declarator decl;
916
917                   decl = SpecDeclFromString(member.dataTypeString, specs,
918                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
919                   ListAdd(decls, MkStructDeclarator(decl, null));
920                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
921
922                   if(!member.dataType)
923                      member.dataType = ProcessType(specs, decl);
924
925                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
926
927                   {
928                      Type type = ProcessType(specs, decl);
929                      DeclareType(member.dataType, false, false);
930                      FreeType(type);
931                   }
932                   /*
933                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
934                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
935                      DeclareStruct(member.dataType._class.string, false);
936                   */
937
938                   ComputeTypeSize(member.dataType);
939                   size = member.dataType.size;
940                   alignment = member.dataType.alignment;
941
942                   if(alignment)
943                   {
944                      if(totalSize % alignment)
945                         totalSize += alignment - (totalSize % alignment);
946                   }
947                   totalSize += size;
948                }
949                break;
950             }
951             case unionMember:
952             case structMember:
953             {
954                OldList * specs = MkList(), * list = MkList();
955
956                size = 0;
957                AddMembers(list, (Class)member, true, &size, topClass, null);
958                ListAdd(specs,
959                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
960                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, null, null)));
961                alignment = member.structAlignment;
962
963                if(alignment)
964                {
965                   if(totalSize % alignment)
966                      totalSize += alignment - (totalSize % alignment);
967                }
968                totalSize += size;
969                break;
970             }
971          }
972       }
973    }
974    if(retSize)
975    {
976       if(topMember && topMember.type == unionMember)
977          *retSize = Max(*retSize, totalSize);
978       else
979          *retSize += totalSize;
980    }
981    else if(totalSize < maxSize && _class.type != systemClass)
982    {
983       int autoPadding = 0;
984       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
985          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
986       if(totalSize + autoPadding < maxSize)
987       {
988          char sizeString[50];
989          sprintf(sizeString, "%d", maxSize - totalSize);
990          ListAdd(declarations,
991             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
992             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
993          if(addedPadding)
994             *addedPadding = true;
995       }
996    }
997    if(context)
998       FinishTemplatesContext(context);
999    return topMember ? topMember.memberID : _class.memberID;
1000 }
1001
1002 static int DeclareMembers(Class _class, bool isMember)
1003 {
1004    DataMember topMember = isMember ? (DataMember) _class : null;
1005    uint totalSize = 0;
1006    DataMember member;
1007    Context context = isMember ? null : SetupTemplatesContext(_class);
1008
1009    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1010       DeclareMembers(_class.base, false);
1011
1012    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1013    {
1014       if(!member.isProperty)
1015       {
1016          switch(member.type)
1017          {
1018             case normalMember:
1019             {
1020                /*
1021                if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
1022                   member.dataType._class.registered && member.dataType._class.registered.type == structClass)
1023                   DeclareStruct(member.dataType._class.string, false);
1024                   */
1025                if(!member.dataType && member.dataTypeString)
1026                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1027                if(member.dataType)
1028                   DeclareType(member.dataType, false, false);
1029                break;
1030             }
1031             case unionMember:
1032             case structMember:
1033             {
1034                DeclareMembers((Class)member, true);
1035                break;
1036             }
1037          }
1038       }
1039    }
1040    if(context)
1041       FinishTemplatesContext(context);
1042
1043    return topMember ? topMember.memberID : _class.memberID;
1044 }
1045
1046 void DeclareStruct(char * name, bool skipNoHead)
1047 {
1048    External external = null;
1049    Symbol classSym = FindClass(name);
1050
1051    if(!inCompiler || !classSym) return;
1052
1053    // We don't need any declaration for bit classes...
1054    if(classSym.registered &&
1055       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1056       return;
1057
1058    /*if(classSym.registered.templateClass)
1059       return DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1060    */
1061
1062    if(classSym.registered && classSym.imported && !classSym.declaredStructSym)
1063    {
1064       // Add typedef struct
1065       Declaration decl;
1066       OldList * specifiers, * declarators;
1067       OldList * declarations = null;
1068       char structName[1024];
1069       external = (classSym.registered && classSym.registered.type == structClass) ?
1070          classSym.pointerExternal : classSym.structExternal;
1071
1072       // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1073       // Moved this one up because DeclareClass done later will need it
1074
1075       classSym.declaring++;
1076
1077       if(strchr(classSym.string, '<'))
1078       {
1079          if(classSym.registered.templateClass)
1080          {
1081             DeclareStruct(classSym.registered.templateClass.fullName, skipNoHead);
1082             classSym.declaring--;
1083          }
1084          return;
1085       }
1086
1087       //if(!skipNoHead)
1088          DeclareMembers(classSym.registered, false);
1089
1090       structName[0] = 0;
1091       FullClassNameCat(structName, name, false);
1092
1093       /*if(!external)
1094          external = MkExternalDeclaration(null);*/
1095
1096       if(!skipNoHead)
1097       {
1098          bool addedPadding = false;
1099          classSym.declaredStructSym = true;
1100
1101          declarations = MkList();
1102
1103          AddMembers(declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1104
1105          //ListAdd(specifiers, MkSpecifier(TYPEDEF));
1106          //ListAdd(specifiers, MkStructOrUnion(structSpecifier, null, declarations));
1107
1108          if(!declarations->count || (declarations->count == 1 && addedPadding))
1109          {
1110             FreeList(declarations, FreeClassDef);
1111             declarations = null;
1112          }
1113       }
1114       if(skipNoHead || declarations)
1115       {
1116          if(external && external.declaration)
1117          {
1118             ((Specifier)external.declaration.specifiers->first).definitions = declarations;
1119
1120             if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1121             {
1122                // TODO: Fix this
1123                //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1124
1125                // DANGER
1126                if(classSym.structExternal)
1127                   ast->Move(classSym.structExternal, curExternal.prev);
1128                ast->Move(classSym.pointerExternal, curExternal.prev);
1129
1130                classSym.id = curExternal.symbol.idCode;
1131                classSym.idCode = curExternal.symbol.idCode;
1132                // external = classSym.pointerExternal;
1133                //external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1134             }
1135          }
1136          else
1137          {
1138             if(!external)
1139                external = MkExternalDeclaration(null);
1140
1141             specifiers = MkList();
1142             declarators = MkList();
1143             ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1144
1145             /*
1146             d = MkDeclaratorIdentifier(MkIdentifier(structName));
1147             ListAdd(declarators, MkInitDeclarator(d, null));
1148             */
1149             external.declaration = decl = MkDeclaration(specifiers, declarators);
1150             if(decl.symbol && !decl.symbol.pointerExternal)
1151                decl.symbol.pointerExternal = external;
1152
1153             // For simple classes, keep the declaration as the external to move around
1154             if(classSym.registered && classSym.registered.type == structClass)
1155             {
1156                char className[1024];
1157                strcpy(className, "__ecereClass_");
1158                FullClassNameCat(className, classSym.string, true);
1159                MangleClassName(className);
1160
1161                // Testing This
1162                DeclareClass(classSym, className);
1163
1164                external.symbol = classSym;
1165                classSym.pointerExternal = external;
1166                classSym.id = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1167                classSym.idCode = (curExternal && curExternal.symbol) ? curExternal.symbol.idCode : 0;
1168             }
1169             else
1170             {
1171                char className[1024];
1172                strcpy(className, "__ecereClass_");
1173                FullClassNameCat(className, classSym.string, true);
1174                MangleClassName(className);
1175
1176                // TOFIX: TESTING THIS...
1177                classSym.structExternal = external;
1178                DeclareClass(classSym, className);
1179                external.symbol = classSym;
1180             }
1181
1182             //if(curExternal)
1183                ast->Insert(curExternal ? curExternal.prev : null, external);
1184          }
1185       }
1186
1187       classSym.declaring--;
1188    }
1189    else if(curExternal && curExternal.symbol && curExternal.symbol.idCode < classSym.id)
1190    {
1191       // TEMPORARY HACK: Pass 3 will move up struct declarations without moving members
1192       // Moved this one up because DeclareClass done later will need it
1193
1194       // TESTING THIS:
1195       classSym.declaring++;
1196
1197       //if(!skipNoHead)
1198       {
1199          if(classSym.registered)
1200             DeclareMembers(classSym.registered, false);
1201       }
1202
1203       if(classSym.registered && (classSym.registered.type == structClass || classSym.registered.type == noHeadClass))
1204       {
1205          // TODO: Fix this
1206          //ast->Move(classSym.structExternal ? classSym.structExternal : classSym.pointerExternal, curExternal.prev);
1207
1208          // DANGER
1209          if(classSym.structExternal)
1210             ast->Move(classSym.structExternal, curExternal.prev);
1211          ast->Move(classSym.pointerExternal, curExternal.prev);
1212
1213          classSym.id = curExternal.symbol.idCode;
1214          classSym.idCode = curExternal.symbol.idCode;
1215          // external = classSym.pointerExternal;
1216          // external = classSym.structExternal ? classSym.structExternal : classSym.pointerExternal;
1217       }
1218
1219       classSym.declaring--;
1220    }
1221    //return external;
1222 }
1223
1224 void DeclareProperty(Property prop, char * setName, char * getName)
1225 {
1226    Symbol symbol = prop.symbol;
1227    char propName[1024];
1228
1229    strcpy(setName, "__ecereProp_");
1230    FullClassNameCat(setName, prop._class.fullName, false);
1231    strcat(setName, "_Set_");
1232    // strcat(setName, prop.name);
1233    FullClassNameCat(setName, prop.name, true);
1234
1235    strcpy(getName, "__ecereProp_");
1236    FullClassNameCat(getName, prop._class.fullName, false);
1237    strcat(getName, "_Get_");
1238    FullClassNameCat(getName, prop.name, true);
1239    // strcat(getName, prop.name);
1240
1241    strcpy(propName, "__ecereProp_");
1242    FullClassNameCat(propName, prop._class.fullName, false);
1243    strcat(propName, "_");
1244    FullClassNameCat(propName, prop.name, true);
1245    // strcat(propName, prop.name);
1246
1247    // To support "char *" property
1248    MangleClassName(getName);
1249    MangleClassName(setName);
1250    MangleClassName(propName);
1251
1252    if(prop._class.type == structClass)
1253       DeclareStruct(prop._class.fullName, false);
1254
1255    if(!symbol || curExternal.symbol.idCode < symbol.id)
1256    {
1257       bool imported = false;
1258       bool dllImport = false;
1259       if(!symbol || symbol._import)
1260       {
1261          if(!symbol)
1262          {
1263             Symbol classSym;
1264             if(!prop._class.symbol)
1265                prop._class.symbol = FindClass(prop._class.fullName);
1266             classSym = prop._class.symbol;
1267             if(classSym && !classSym._import)
1268             {
1269                ModuleImport module;
1270
1271                if(prop._class.module)
1272                   module = FindModule(prop._class.module);
1273                else
1274                   module = mainModule;
1275
1276                classSym._import = ClassImport
1277                {
1278                   name = CopyString(prop._class.fullName);
1279                   isRemote = prop._class.isRemote;
1280                };
1281                module.classes.Add(classSym._import);
1282             }
1283             symbol = prop.symbol = Symbol { };
1284             symbol._import = (ClassImport)PropertyImport
1285             {
1286                name = CopyString(prop.name);
1287                isVirtual = false; //prop.isVirtual;
1288                hasSet = prop.Set ? true : false;
1289                hasGet = prop.Get ? true : false;
1290             };
1291             if(classSym)
1292                classSym._import.properties.Add(symbol._import);
1293          }
1294          imported = true;
1295          // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1296          if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1297             prop._class.module.importType != staticImport)
1298             dllImport = true;
1299       }
1300
1301       if(!symbol.type)
1302       {
1303          Context context = SetupTemplatesContext(prop._class);
1304          symbol.type = ProcessTypeString(prop.dataTypeString, false);
1305          FinishTemplatesContext(context);
1306       }
1307
1308       // Get
1309       if(prop.Get)
1310       {
1311          if(!symbol.externalGet || symbol.externalGet.type == functionExternal)
1312          {
1313             Declaration decl;
1314             OldList * specifiers, * declarators;
1315             Declarator d;
1316             OldList * params;
1317             Specifier spec;
1318             External external;
1319             Declarator typeDecl;
1320             bool simple = false;
1321
1322             specifiers = MkList();
1323             declarators = MkList();
1324             params = MkList();
1325
1326             ListAdd(params, MkTypeName(MkListOne(MkSpecifierName /*MkClassName*/(prop._class.fullName)),
1327                MkDeclaratorIdentifier(MkIdentifier("this"))));
1328
1329             d = MkDeclaratorIdentifier(MkIdentifier(getName));
1330             //if(imported)
1331             if(dllImport)
1332                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1333
1334             {
1335                Context context = SetupTemplatesContext(prop._class);
1336                typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1337                FinishTemplatesContext(context);
1338             }
1339
1340             // Make sure the simple _class's type is declared
1341             for(spec = specifiers->first; spec; spec = spec.next)
1342             {
1343                if(spec.type == nameSpecifier /*SpecifierClass*/)
1344                {
1345                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1346                   {
1347                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1348                      symbol._class = classSym.registered;
1349                      if(classSym.registered && classSym.registered.type == structClass)
1350                      {
1351                         DeclareStruct(spec.name, false);
1352                         simple = true;
1353                      }
1354                   }
1355                }
1356             }
1357
1358             if(!simple)
1359                d = PlugDeclarator(typeDecl, d);
1360             else
1361             {
1362                ListAdd(params, MkTypeName(specifiers,
1363                   PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1364                specifiers = MkList();
1365             }
1366
1367             d = MkDeclaratorFunction(d, params);
1368
1369             //if(imported)
1370             if(dllImport)
1371                specifiers->Insert(null, MkSpecifier(EXTERN));
1372             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1373                specifiers->Insert(null, MkSpecifier(STATIC));
1374             if(simple)
1375                ListAdd(specifiers, MkSpecifier(VOID));
1376
1377             ListAdd(declarators, MkInitDeclarator(d, null));
1378
1379             decl = MkDeclaration(specifiers, declarators);
1380
1381             external = MkExternalDeclaration(decl);
1382             ast->Insert(curExternal.prev, external);
1383             external.symbol = symbol;
1384             symbol.externalGet = external;
1385
1386             ReplaceThisClassSpecifiers(specifiers, prop._class);
1387
1388             if(typeDecl)
1389                FreeDeclarator(typeDecl);
1390          }
1391          else
1392          {
1393             // Move declaration higher...
1394             ast->Move(symbol.externalGet, curExternal.prev);
1395          }
1396       }
1397
1398       // Set
1399       if(prop.Set)
1400       {
1401          if(!symbol.externalSet || symbol.externalSet.type == functionExternal)
1402          {
1403             Declaration decl;
1404             OldList * specifiers, * declarators;
1405             Declarator d;
1406             OldList * params;
1407             Specifier spec;
1408             External external;
1409             Declarator typeDecl;
1410
1411             declarators = MkList();
1412             params = MkList();
1413
1414             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1415             if(!prop.conversion || prop._class.type == structClass)
1416             {
1417                ListAdd(params, MkTypeName(MkListOne(MkSpecifierName/*MkClassName*/(prop._class.fullName)),
1418                   MkDeclaratorIdentifier(MkIdentifier("this"))));
1419             }
1420
1421             specifiers = MkList();
1422
1423             {
1424                Context context = SetupTemplatesContext(prop._class);
1425                typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1426                   MkDeclaratorIdentifier(MkIdentifier("value")));
1427                FinishTemplatesContext(context);
1428             }
1429             ListAdd(params, MkTypeName(specifiers, d));
1430
1431             d = MkDeclaratorIdentifier(MkIdentifier(setName));
1432             //if(imported)
1433             if(dllImport)
1434                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1435             d = MkDeclaratorFunction(d, params);
1436
1437             // Make sure the simple _class's type is declared
1438             for(spec = specifiers->first; spec; spec = spec.next)
1439             {
1440                if(spec.type == nameSpecifier /*SpecifierClass*/)
1441                {
1442                   if((!typeDecl || typeDecl.type == identifierDeclarator))
1443                   {
1444                      Symbol classSym = spec.symbol; // FindClass(spec.name);
1445                      symbol._class = classSym.registered;
1446                      if(classSym.registered && classSym.registered.type == structClass)
1447                         DeclareStruct(spec.name, false);
1448                   }
1449                }
1450             }
1451
1452             ListAdd(declarators, MkInitDeclarator(d, null));
1453
1454             specifiers = MkList();
1455             //if(imported)
1456             if(dllImport)
1457                specifiers->Insert(null, MkSpecifier(EXTERN));
1458             else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1459                specifiers->Insert(null, MkSpecifier(STATIC));
1460
1461             // TESTING COMMENTING THIS FIRST LINE OUT, what was the problem? Trying to add noHeadClass here ...
1462             if(!prop.conversion || prop._class.type == structClass)
1463                ListAdd(specifiers, MkSpecifier(VOID));
1464             else
1465                ListAdd(specifiers, MkSpecifierName/*MkClassName*/(prop._class.fullName));
1466
1467             decl = MkDeclaration(specifiers, declarators);
1468
1469             external = MkExternalDeclaration(decl);
1470             ast->Insert(curExternal.prev, external);
1471             external.symbol = symbol;
1472             symbol.externalSet = external;
1473
1474             ReplaceThisClassSpecifiers(specifiers, prop._class);
1475          }
1476          else
1477          {
1478             // Move declaration higher...
1479             ast->Move(symbol.externalSet, curExternal.prev);
1480          }
1481       }
1482
1483       // Property (for Watchers)
1484       if(!symbol.externalPtr)
1485       {
1486          Declaration decl;
1487          External external;
1488          OldList * specifiers = MkList();
1489
1490          if(imported)
1491             specifiers->Insert(null, MkSpecifier(EXTERN));
1492          else
1493             specifiers->Insert(null, MkSpecifier(STATIC));
1494
1495          ListAdd(specifiers, MkSpecifierName("Property"));
1496
1497          {
1498             OldList * list = MkList();
1499             ListAdd(list, MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null),
1500                   MkDeclaratorIdentifier(MkIdentifier(propName))), null));
1501
1502             if(!imported)
1503             {
1504                strcpy(propName, "__ecerePropM_");
1505                FullClassNameCat(propName, prop._class.fullName, false);
1506                strcat(propName, "_");
1507                // strcat(propName, prop.name);
1508                FullClassNameCat(propName, prop.name, true);
1509
1510                MangleClassName(propName);
1511
1512                ListAdd(list, MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null),
1513                      MkDeclaratorIdentifier(MkIdentifier(propName))), null));
1514             }
1515             decl = MkDeclaration(specifiers, list);
1516          }
1517
1518          external = MkExternalDeclaration(decl);
1519          ast->Insert(curExternal.prev, external);
1520          external.symbol = symbol;
1521          symbol.externalPtr = external;
1522       }
1523       else
1524       {
1525          // Move declaration higher...
1526          ast->Move(symbol.externalPtr, curExternal.prev);
1527       }
1528
1529       symbol.id = curExternal.symbol.idCode;
1530    }
1531 }
1532
1533 // ***************** EXPRESSION PROCESSING ***************************
1534 public Type Dereference(Type source)
1535 {
1536    Type type = null;
1537    if(source)
1538    {
1539       if(source.kind == pointerType || source.kind == arrayType)
1540       {
1541          type = source.type;
1542          source.type.refCount++;
1543       }
1544       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1545       {
1546          type = Type
1547          {
1548             kind = charType;
1549             refCount = 1;
1550          };
1551       }
1552       // Support dereferencing of no head classes for now...
1553       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1554       {
1555          type = source;
1556          source.refCount++;
1557       }
1558       else
1559          Compiler_Error($"cannot dereference type\n");
1560    }
1561    return type;
1562 }
1563
1564 static Type Reference(Type source)
1565 {
1566    Type type = null;
1567    if(source)
1568    {
1569       type = Type
1570       {
1571          kind = pointerType;
1572          type = source;
1573          refCount = 1;
1574       };
1575       source.refCount++;
1576    }
1577    return type;
1578 }
1579
1580 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1581 {
1582    Identifier ident = member.identifiers ? member.identifiers->first : null;
1583    bool found = false;
1584    DataMember dataMember = null;
1585    Method method = null;
1586    bool freeType = false;
1587
1588    yylloc = member.loc;
1589
1590    if(!ident)
1591    {
1592       if(curMember)
1593       {
1594          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1595          if(*curMember)
1596          {
1597             found = true;
1598             dataMember = *curMember;
1599          }
1600       }
1601    }
1602    else
1603    {
1604       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1605       DataMember _subMemberStack[256];
1606       int _subMemberStackPos = 0;
1607
1608       // FILL MEMBER STACK
1609       if(!thisMember)
1610          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1611       if(thisMember)
1612       {
1613          dataMember = thisMember;
1614          if(curMember && thisMember.memberAccess == publicAccess)
1615          {
1616             *curMember = thisMember;
1617             *curClass = thisMember._class;
1618             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1619             *subMemberStackPos = _subMemberStackPos;
1620          }
1621          found = true;
1622       }
1623       else
1624       {
1625          // Setting a method
1626          method = eClass_FindMethod(_class, ident.string, privateModule);
1627          if(method && method.type == virtualMethod)
1628             found = true;
1629          else
1630             method = null;
1631       }
1632    }
1633
1634    if(found)
1635    {
1636       Type type = null;
1637       if(dataMember)
1638       {
1639          if(!dataMember.dataType && dataMember.dataTypeString)
1640          {
1641             //Context context = SetupTemplatesContext(dataMember._class);
1642             Context context = SetupTemplatesContext(_class);
1643             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1644             FinishTemplatesContext(context);
1645          }
1646          type = dataMember.dataType;
1647       }
1648       else if(method)
1649       {
1650          // This is for destination type...
1651          if(!method.dataType)
1652             ProcessMethodType(method);
1653          //DeclareMethod(method);
1654          // method.dataType = ((Symbol)method.symbol)->type;
1655          type = method.dataType;
1656       }
1657
1658       if(ident && ident.next)
1659       {
1660          for(ident = ident.next; ident && type; ident = ident.next)
1661          {
1662             if(type.kind == classType)
1663             {
1664                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1665                if(!dataMember)
1666                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1667                if(dataMember)
1668                   type = dataMember.dataType;
1669             }
1670             else if(type.kind == structType || type.kind == unionType)
1671             {
1672                Type memberType;
1673                for(memberType = type.members.first; memberType; memberType = memberType.next)
1674                {
1675                   if(!strcmp(memberType.name, ident.string))
1676                   {
1677                      type = memberType;
1678                      break;
1679                   }
1680                }
1681             }
1682          }
1683       }
1684
1685       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1686       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1687       {
1688          int id = 0;
1689          ClassTemplateParameter curParam = null;
1690          Class sClass;
1691          for(sClass = _class; sClass; sClass = sClass.base)
1692          {
1693             id = 0;
1694             if(sClass.templateClass) sClass = sClass.templateClass;
1695             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1696             {
1697                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1698                {
1699                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1700                   {
1701                      if(sClass.templateClass) sClass = sClass.templateClass;
1702                      id += sClass.templateParams.count;
1703                   }
1704                   break;
1705                }
1706                id++;
1707             }
1708             if(curParam) break;
1709          }
1710
1711          if(curParam)
1712          {
1713             ClassTemplateArgument arg = _class.templateArgs[id];
1714             if(arg.dataTypeString)
1715             {
1716                // FreeType(type);
1717                type = ProcessTypeString(arg.dataTypeString, false);
1718                freeType = true;
1719                if(type && _class.templateClass)
1720                   type.passAsTemplate = true;
1721                if(type)
1722                {
1723                   // type.refCount++;
1724                   /*if(!exp.destType)
1725                   {
1726                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1727                      exp.destType.refCount++;
1728                   }*/
1729                }
1730             }
1731          }
1732       }
1733       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1734       {
1735          Class expClass = type._class.registered;
1736          Class cClass = null;
1737          int c;
1738          int paramCount = 0;
1739          int lastParam = -1;
1740
1741          char templateString[1024];
1742          ClassTemplateParameter param;
1743          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1744          for(cClass = expClass; cClass; cClass = cClass.base)
1745          {
1746             int p = 0;
1747             if(cClass.templateClass) cClass = cClass.templateClass;
1748             for(param = cClass.templateParams.first; param; param = param.next)
1749             {
1750                int id = p;
1751                Class sClass;
1752                ClassTemplateArgument arg;
1753                for(sClass = cClass.base; sClass; sClass = sClass.base)
1754                {
1755                   if(sClass.templateClass) sClass = sClass.templateClass;
1756                   id += sClass.templateParams.count;
1757                }
1758                arg = expClass.templateArgs[id];
1759
1760                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1761                {
1762                   ClassTemplateParameter cParam;
1763                   //int p = numParams - sClass.templateParams.count;
1764                   int p = 0;
1765                   Class nextClass;
1766                   if(sClass.templateClass) sClass = sClass.templateClass;
1767
1768                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1769                   {
1770                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1771                      p += nextClass.templateParams.count;
1772                   }
1773
1774                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1775                   {
1776                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1777                      {
1778                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1779                         {
1780                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1781                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1782                            break;
1783                         }
1784                      }
1785                   }
1786                }
1787
1788                {
1789                   char argument[256];
1790                   argument[0] = '\0';
1791                   /*if(arg.name)
1792                   {
1793                      strcat(argument, arg.name.string);
1794                      strcat(argument, " = ");
1795                   }*/
1796                   switch(param.type)
1797                   {
1798                      case expression:
1799                      {
1800                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1801                         char expString[1024];
1802                         OldList * specs = MkList();
1803                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1804                         Expression exp;
1805                         char * string = PrintHexUInt64(arg.expression.ui64);
1806                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1807                         delete string;
1808
1809                         ProcessExpressionType(exp);
1810                         ComputeExpression(exp);
1811                         expString[0] = '\0';
1812                         PrintExpression(exp, expString);
1813                         strcat(argument, expString);
1814                         //delete exp;
1815                         FreeExpression(exp);
1816                         break;
1817                      }
1818                      case identifier:
1819                      {
1820                         strcat(argument, arg.member.name);
1821                         break;
1822                      }
1823                      case TemplateParameterType::type:
1824                      {
1825                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1826                            strcat(argument, arg.dataTypeString);
1827                         break;
1828                      }
1829                   }
1830                   if(argument[0])
1831                   {
1832                      if(paramCount) strcat(templateString, ", ");
1833                      if(lastParam != p - 1)
1834                      {
1835                         strcat(templateString, param.name);
1836                         strcat(templateString, " = ");
1837                      }
1838                      strcat(templateString, argument);
1839                      paramCount++;
1840                      lastParam = p;
1841                   }
1842                   p++;
1843                }
1844             }
1845          }
1846          {
1847             int len = strlen(templateString);
1848             if(templateString[len-1] == '<')
1849                len--;
1850             else
1851             {
1852                if(templateString[len-1] == '>')
1853                   templateString[len++] = ' ';
1854                templateString[len++] = '>';
1855             }
1856             templateString[len++] = '\0';
1857          }
1858          {
1859             Context context = SetupTemplatesContext(_class);
1860             if(freeType) FreeType(type);
1861             type = ProcessTypeString(templateString, false);
1862             freeType = true;
1863             FinishTemplatesContext(context);
1864          }
1865       }
1866
1867       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1868       {
1869          ProcessExpressionType(member.initializer.exp);
1870          if(!member.initializer.exp.expType)
1871          {
1872             if(inCompiler)
1873             {
1874                char expString[10240];
1875                expString[0] = '\0';
1876                PrintExpression(member.initializer.exp, expString);
1877                ChangeCh(expString, '\n', ' ');
1878                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1879             }
1880          }
1881          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1882          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false))
1883          {
1884             Compiler_Error($"incompatible instance method %s\n", ident.string);
1885          }
1886       }
1887       else if(member.initializer)
1888       {
1889          /*
1890          FreeType(member.exp.destType);
1891          member.exp.destType = type;
1892          if(member.exp.destType)
1893             member.exp.destType.refCount++;
1894          ProcessExpressionType(member.exp);
1895          */
1896
1897          ProcessInitializer(member.initializer, type);
1898       }
1899       if(freeType) FreeType(type);
1900    }
1901    else
1902    {
1903       if(_class && _class.type == unitClass)
1904       {
1905          if(member.initializer)
1906          {
1907             /*
1908             FreeType(member.exp.destType);
1909             member.exp.destType = MkClassType(_class.fullName);
1910             ProcessExpressionType(member.initializer, type);
1911             */
1912             Type type = MkClassType(_class.fullName);
1913             ProcessInitializer(member.initializer, type);
1914             FreeType(type);
1915          }
1916       }
1917       else
1918       {
1919          if(member.initializer)
1920          {
1921             //ProcessExpressionType(member.exp);
1922             ProcessInitializer(member.initializer, null);
1923          }
1924          if(ident)
1925          {
1926             if(method)
1927             {
1928                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
1929             }
1930             else if(_class)
1931             {
1932                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
1933                if(inCompiler)
1934                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
1935             }
1936          }
1937          else if(_class)
1938             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
1939       }
1940    }
1941 }
1942
1943 void ProcessInstantiationType(Instantiation inst)
1944 {
1945    yylloc = inst.loc;
1946    if(inst._class)
1947    {
1948       MembersInit members;
1949       Symbol classSym; // = inst._class.symbol; // FindClass(inst._class.name);
1950       Class _class;
1951
1952       /*if(!inst._class.symbol)
1953          inst._class.symbol = FindClass(inst._class.name);*/
1954       classSym = inst._class.symbol;
1955       _class = classSym ? classSym.registered : null;
1956
1957       // DANGER: Patch for mutex not declaring its struct when not needed
1958       if(!_class || _class.type != noHeadClass)
1959          DeclareStruct(inst._class.name, false); //_class && _class.type == noHeadClass);
1960
1961       afterExternal = afterExternal ? afterExternal : curExternal;
1962
1963       if(inst.exp)
1964          ProcessExpressionType(inst.exp);
1965
1966       inst.isConstant = true;
1967       if(inst.members)
1968       {
1969          DataMember curMember = null;
1970          Class curClass = null;
1971          DataMember subMemberStack[256];
1972          int subMemberStackPos = 0;
1973
1974          for(members = inst.members->first; members; members = members.next)
1975          {
1976             switch(members.type)
1977             {
1978                case methodMembersInit:
1979                {
1980                   char name[1024];
1981                   static uint instMethodID = 0;
1982                   External external = curExternal;
1983                   Context context = curContext;
1984                   Declarator declarator = members.function.declarator;
1985                   Identifier nameID = GetDeclId(declarator);
1986                   char * unmangled = nameID ? nameID.string : null;
1987                   Expression exp;
1988                   External createdExternal = null;
1989
1990                   if(inCompiler)
1991                   {
1992                      char number[16];
1993                      //members.function.dontMangle = true;
1994                      strcpy(name, "__ecereInstMeth_");
1995                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
1996                      strcat(name, "_");
1997                      strcat(name, nameID.string);
1998                      strcat(name, "_");
1999                      sprintf(number, "_%08d", instMethodID++);
2000                      strcat(name, number);
2001                      nameID.string = CopyString(name);
2002                   }
2003
2004                   // Do modifications here...
2005                   if(declarator)
2006                   {
2007                      Symbol symbol = declarator.symbol;
2008                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2009
2010                      if(method && method.type == virtualMethod)
2011                      {
2012                         symbol.method = method;
2013                         ProcessMethodType(method);
2014
2015                         if(!symbol.type.thisClass)
2016                         {
2017                            if(method.dataType.thisClass && currentClass &&
2018                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2019                            {
2020                               if(!currentClass.symbol)
2021                                  currentClass.symbol = FindClass(currentClass.fullName);
2022                               symbol.type.thisClass = currentClass.symbol;
2023                            }
2024                            else
2025                            {
2026                               if(!_class.symbol)
2027                                  _class.symbol = FindClass(_class.fullName);
2028                               symbol.type.thisClass = _class.symbol;
2029                            }
2030                         }
2031                         // TESTING THIS HERE:
2032                         DeclareType(symbol.type, true, true);
2033
2034                      }
2035                      else if(classSym)
2036                      {
2037                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2038                            unmangled, classSym.string);
2039                      }
2040                   }
2041
2042                   //declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2043                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2044
2045                   if(nameID)
2046                   {
2047                      FreeSpecifier(nameID._class);
2048                      nameID._class = null;
2049                   }
2050
2051                   if(inCompiler)
2052                   {
2053
2054                      Type type = declarator.symbol.type;
2055                      External oldExternal = curExternal;
2056
2057                      // *** Commented this out... Any negative impact? Yes: makes double prototypes declarations... Why was it commented out?
2058                      // *** It was commented out for problems such as
2059                      /*
2060                            class VirtualDesktop : Window
2061                            {
2062                               clientSize = Size { };
2063                               Timer timer
2064                               {
2065                                  bool DelayExpired()
2066                                  {
2067                                     clientSize.w;
2068                                     return true;
2069                                  }
2070                               };
2071                            }
2072                      */
2073                      // Commented Out: Good for bet.ec in Poker (Otherwise: obj\bet.c:187: error: `currentBet' undeclared (first use in this function))
2074
2075                      declarator.symbol.id = declarator.symbol.idCode = curExternal.symbol.idCode;
2076
2077                      /*
2078                      if(strcmp(declarator.symbol.string, name))
2079                      {
2080                         printf("TOCHECK: Look out for this\n");
2081                         delete declarator.symbol.string;
2082                         declarator.symbol.string = CopyString(name);
2083                      }
2084
2085                      if(!declarator.symbol.parent && globalContext.symbols.root != (BTNode)declarator.symbol)
2086                      {
2087                         printf("TOCHECK: Will this ever be in a list? Yes.\n");
2088                         excludedSymbols->Remove(declarator.symbol);
2089                         globalContext.symbols.Add((BTNode)declarator.symbol);
2090                         if(strstr(declarator.symbol.string), "::")
2091                            globalContext.hasNameSpace = true;
2092
2093                      }
2094                      */
2095
2096                      //curExternal = curExternal.prev;
2097                      //afterExternal = afterExternal->next;
2098
2099                      //ProcessFunction(afterExternal->function);
2100
2101                      //curExternal = afterExternal;
2102                      {
2103                         External externalDecl;
2104                         externalDecl = MkExternalDeclaration(null);
2105                         ast->Insert(oldExternal.prev, externalDecl);
2106
2107                         // Which function does this process?
2108                         if(createdExternal.function)
2109                         {
2110                            ProcessFunction(createdExternal.function);
2111
2112                            //curExternal = oldExternal;
2113
2114                            {
2115                               //Declaration decl = MkDeclaration(members.function.specifiers, MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2116
2117                               Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
2118                                  MkListOne(MkInitDeclarator(CopyDeclarator(declarator), null)));
2119
2120                               //externalDecl = MkExternalDeclaration(decl);
2121
2122                               //***** ast->Insert(external.prev, externalDecl);
2123                               //ast->Insert(curExternal.prev, externalDecl);
2124                               externalDecl.declaration = decl;
2125                               if(decl.symbol && !decl.symbol.pointerExternal)
2126                                  decl.symbol.pointerExternal = externalDecl;
2127
2128                               // Trying this out...
2129                               declarator.symbol.pointerExternal = externalDecl;
2130                            }
2131                         }
2132                      }
2133                   }
2134                   else if(declarator)
2135                   {
2136                      curExternal = declarator.symbol.pointerExternal;
2137                      ProcessFunction((FunctionDefinition)members.function);
2138                   }
2139                   curExternal = external;
2140                   curContext = context;
2141
2142                   if(inCompiler)
2143                   {
2144                      FreeClassFunction(members.function);
2145
2146                      // In this pass, turn this into a MemberInitData
2147                      exp = QMkExpId(name);
2148                      members.type = dataMembersInit;
2149                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2150
2151                      delete unmangled;
2152                   }
2153                   break;
2154                }
2155                case dataMembersInit:
2156                {
2157                   if(members.dataMembers && classSym)
2158                   {
2159                      MemberInit member;
2160                      Location oldyyloc = yylloc;
2161                      for(member = members.dataMembers->first; member; member = member.next)
2162                      {
2163                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2164                         if(member.initializer && !member.initializer.isConstant)
2165                            inst.isConstant = false;
2166                      }
2167                      yylloc = oldyyloc;
2168                   }
2169                   break;
2170                }
2171             }
2172          }
2173       }
2174    }
2175 }
2176
2177 static void DeclareType(Type type, bool declarePointers, bool declareParams)
2178 {
2179    // OPTIMIZATIONS: TESTING THIS...
2180    if(inCompiler)
2181    {
2182       if(type.kind == functionType)
2183       {
2184          Type param;
2185          if(declareParams)
2186          {
2187             for(param = type.params.first; param; param = param.next)
2188                DeclareType(param, declarePointers, true);
2189          }
2190          DeclareType(type.returnType, declarePointers, true);
2191       }
2192       else if(type.kind == pointerType && declarePointers)
2193          DeclareType(type.type, declarePointers, false);
2194       else if(type.kind == classType)
2195       {
2196          if(type._class.registered && (type._class.registered.type == structClass || type._class.registered.type == noHeadClass) && !type._class.declaring)
2197             DeclareStruct(type._class.registered.fullName, type._class.registered.type == noHeadClass);
2198       }
2199       else if(type.kind == structType || type.kind == unionType)
2200       {
2201          Type member;
2202          for(member = type.members.first; member; member = member.next)
2203             DeclareType(member, false, false);
2204       }
2205       else if(type.kind == arrayType)
2206          DeclareType(type.arrayType, declarePointers, false);
2207    }
2208 }
2209
2210 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2211 {
2212    ClassTemplateArgument * arg = null;
2213    int id = 0;
2214    ClassTemplateParameter curParam = null;
2215    Class sClass;
2216    for(sClass = _class; sClass; sClass = sClass.base)
2217    {
2218       id = 0;
2219       if(sClass.templateClass) sClass = sClass.templateClass;
2220       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2221       {
2222          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2223          {
2224             for(sClass = sClass.base; sClass; sClass = sClass.base)
2225             {
2226                if(sClass.templateClass) sClass = sClass.templateClass;
2227                id += sClass.templateParams.count;
2228             }
2229             break;
2230          }
2231          id++;
2232       }
2233       if(curParam) break;
2234    }
2235    if(curParam)
2236    {
2237       arg = &_class.templateArgs[id];
2238       if(arg && param.type == type)
2239          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2240    }
2241    return arg;
2242 }
2243
2244 public Context SetupTemplatesContext(Class _class)
2245 {
2246    Context context = PushContext();
2247    context.templateTypesOnly = true;
2248    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2249    {
2250       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2251       for(; param; param = param.next)
2252       {
2253          if(param.type == type && param.identifier)
2254          {
2255             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2256             curContext.templateTypes.Add((BTNode)type);
2257          }
2258       }
2259    }
2260    else if(_class)
2261    {
2262       Class sClass;
2263       for(sClass = _class; sClass; sClass = sClass.base)
2264       {
2265          ClassTemplateParameter p;
2266          for(p = sClass.templateParams.first; p; p = p.next)
2267          {
2268             //OldList * specs = MkList();
2269             //Declarator decl = null;
2270             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2271             if(p.type == type)
2272             {
2273                TemplateParameter param = p.param;
2274                TemplatedType type;
2275                if(!param)
2276                {
2277                   // ADD DATA TYPE HERE...
2278                   p.param = param = TemplateParameter
2279                   {
2280                      identifier = MkIdentifier(p.name), type = p.type,
2281                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2282                   };
2283                }
2284                type = TemplatedType { key = (uintptr)p.name, param = param };
2285                curContext.templateTypes.Add((BTNode)type);
2286             }
2287          }
2288       }
2289    }
2290    return context;
2291 }
2292
2293 public void FinishTemplatesContext(Context context)
2294 {
2295    PopContext(context);
2296    FreeContext(context);
2297    delete context;
2298 }
2299
2300 public void ProcessMethodType(Method method)
2301 {
2302    if(!method.dataType)
2303    {
2304       Context context = SetupTemplatesContext(method._class);
2305
2306       method.dataType = ProcessTypeString(method.dataTypeString, false);
2307
2308       FinishTemplatesContext(context);
2309
2310       if(method.type != virtualMethod && method.dataType)
2311       {
2312          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2313          {
2314             if(!method._class.symbol)
2315                method._class.symbol = FindClass(method._class.fullName);
2316             method.dataType.thisClass = method._class.symbol;
2317          }
2318       }
2319
2320       // Why was this commented out? Working fine without now...
2321
2322       /*
2323       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2324          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2325          */
2326    }
2327
2328    /*
2329    if(type)
2330    {
2331       char * par = strstr(type, "(");
2332       char * classOp = null;
2333       int classOpLen = 0;
2334       if(par)
2335       {
2336          int c;
2337          for(c = par-type-1; c >= 0; c++)
2338          {
2339             if(type[c] == ':' && type[c+1] == ':')
2340             {
2341                classOp = type + c - 1;
2342                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2343                {
2344                   classOp--;
2345                   classOpLen++;
2346                }
2347                break;
2348             }
2349             else if(!isspace(type[c]))
2350                break;
2351          }
2352       }
2353       if(classOp)
2354       {
2355          char temp[1024];
2356          int typeLen = strlen(type);
2357          memcpy(temp, classOp, classOpLen);
2358          temp[classOpLen] = '\0';
2359          if(temp[0])
2360             _class = eSystem_FindClass(module, temp);
2361          else
2362             _class = null;
2363          method.dataTypeString = new char[typeLen - classOpLen + 1];
2364          memcpy(method.dataTypeString, type, classOp - type);
2365          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2366       }
2367       else
2368          method.dataTypeString = type;
2369    }
2370    */
2371 }
2372
2373
2374 public void ProcessPropertyType(Property prop)
2375 {
2376    if(!prop.dataType)
2377    {
2378       Context context = SetupTemplatesContext(prop._class);
2379       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2380       FinishTemplatesContext(context);
2381    }
2382 }
2383
2384 public void DeclareMethod(Method method, char * name)
2385 {
2386    Symbol symbol = method.symbol;
2387    if(!symbol || (!symbol.pointerExternal && method.type == virtualMethod) || symbol.id > (curExternal ? curExternal.symbol.idCode : -1))
2388    {
2389       bool imported = false;
2390       bool dllImport = false;
2391
2392       if(!method.dataType)
2393          method.dataType = ProcessTypeString(method.dataTypeString, false);
2394
2395       if(!symbol || symbol._import || method.type == virtualMethod)
2396       {
2397          if(!symbol || method.type == virtualMethod)
2398          {
2399             Symbol classSym;
2400             if(!method._class.symbol)
2401                method._class.symbol = FindClass(method._class.fullName);
2402             classSym = method._class.symbol;
2403             if(!classSym._import)
2404             {
2405                ModuleImport module;
2406
2407                if(method._class.module && method._class.module.name)
2408                   module = FindModule(method._class.module);
2409                else
2410                   module = mainModule;
2411                classSym._import = ClassImport
2412                {
2413                   name = CopyString(method._class.fullName);
2414                   isRemote = method._class.isRemote;
2415                };
2416                module.classes.Add(classSym._import);
2417             }
2418             if(!symbol)
2419             {
2420                symbol = method.symbol = Symbol { };
2421             }
2422             if(!symbol._import)
2423             {
2424                symbol._import = (ClassImport)MethodImport
2425                {
2426                   name = CopyString(method.name);
2427                   isVirtual = method.type == virtualMethod;
2428                };
2429                classSym._import.methods.Add(symbol._import);
2430             }
2431             if(!symbol)
2432             {
2433                // Set the symbol type
2434                /*
2435                if(!type.thisClass)
2436                {
2437                   type.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2438                }
2439                else if(type.thisClass == (void *)-1)
2440                {
2441                   type.thisClass = null;
2442                }
2443                */
2444                // symbol.type = ProcessTypeString(method.dataTypeString, false);
2445                symbol.type = method.dataType;
2446                if(symbol.type) symbol.type.refCount++;
2447             }
2448             /*
2449             if(!method.thisClass || strcmp(method.thisClass, "void"))
2450                symbol.type.params.Insert(null,
2451                   MkClassType(method.thisClass ? method.thisClass : method._class.fullName));
2452             */
2453          }
2454          if(!method.dataType.dllExport)
2455          {
2456             imported = true;
2457             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2458                dllImport = true;
2459          }
2460       }
2461
2462       /* MOVING THIS UP
2463       if(!method.dataType)
2464          method.dataType = ((Symbol)method.symbol).type;
2465          //ProcessMethodType(method);
2466       */
2467
2468       if(method.type != virtualMethod && method.dataType)
2469          DeclareType(method.dataType, true, true);
2470
2471       if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2472       {
2473          // We need a declaration here :)
2474          Declaration decl;
2475          OldList * specifiers, * declarators;
2476          Declarator d;
2477          Declarator funcDecl;
2478          External external;
2479
2480          specifiers = MkList();
2481          declarators = MkList();
2482
2483          //if(imported)
2484          if(dllImport)
2485             ListAdd(specifiers, MkSpecifier(EXTERN));
2486          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2487             ListAdd(specifiers, MkSpecifier(STATIC));
2488
2489          if(method.type == virtualMethod)
2490          {
2491             ListAdd(specifiers, MkSpecifier(INT));
2492             d = MkDeclaratorIdentifier(MkIdentifier(name));
2493          }
2494          else
2495          {
2496             d = MkDeclaratorIdentifier(MkIdentifier(name));
2497             //if(imported)
2498             if(dllImport)
2499                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2500             {
2501                Context context = SetupTemplatesContext(method._class);
2502                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2503                FinishTemplatesContext(context);
2504             }
2505             funcDecl = GetFuncDecl(d);
2506
2507             if(dllImport)
2508             {
2509                Specifier spec, next;
2510                for(spec = specifiers->first; spec; spec = next)
2511                {
2512                   next = spec.next;
2513                   if(spec.type == extendedSpecifier)
2514                   {
2515                      specifiers->Remove(spec);
2516                      FreeSpecifier(spec);
2517                   }
2518                }
2519             }
2520
2521             // Add this parameter if not a static method
2522             if(method.dataType && !method.dataType.staticMethod)
2523             {
2524                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2525                {
2526                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2527                   TypeName thisParam = MkTypeName(MkListOne(
2528                      MkSpecifierName/*MkClassName*/(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2529                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2530                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2531                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2532
2533                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2534                   {
2535                      TypeName param = funcDecl.function.parameters->first;
2536                      funcDecl.function.parameters->Remove(param);
2537                      FreeTypeName(param);
2538                   }
2539
2540                   if(!funcDecl.function.parameters)
2541                      funcDecl.function.parameters = MkList();
2542                   funcDecl.function.parameters->Insert(null, thisParam);
2543                }
2544             }
2545             // Make sure we don't have empty parameter declarations for static methods...
2546             /*
2547             else if(!funcDecl.function.parameters)
2548             {
2549                funcDecl.function.parameters = MkList();
2550                funcDecl.function.parameters->Insert(null,
2551                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2552             }*/
2553          }
2554          // TESTING THIS:
2555          ProcessDeclarator(d);
2556
2557          ListAdd(declarators, MkInitDeclarator(d, null));
2558
2559          decl = MkDeclaration(specifiers, declarators);
2560
2561          ReplaceThisClassSpecifiers(specifiers, method._class);
2562
2563          // Keep a different symbol for the function definition than the declaration...
2564          if(symbol.pointerExternal)
2565          {
2566             Symbol functionSymbol { };
2567
2568             // Copy symbol
2569             {
2570                *functionSymbol = *symbol;
2571                functionSymbol.string = CopyString(symbol.string);
2572                if(functionSymbol.type)
2573                   functionSymbol.type.refCount++;
2574             }
2575
2576             excludedSymbols->Add(functionSymbol);
2577             symbol.pointerExternal.symbol = functionSymbol;
2578          }
2579          external = MkExternalDeclaration(decl);
2580          if(curExternal)
2581             ast->Insert(curExternal ? curExternal.prev : null, external);
2582          external.symbol = symbol;
2583          symbol.pointerExternal = external;
2584       }
2585       else if(ast)
2586       {
2587          // Move declaration higher...
2588          ast->Move(symbol.pointerExternal, curExternal.prev);
2589       }
2590
2591       symbol.id = curExternal ? curExternal.symbol.idCode : MAXINT;
2592    }
2593 }
2594
2595 char * ReplaceThisClass(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
2604       char className[1024];
2605       strcpy(className, _class.fullName);
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 CopyString(className);
2631    }
2632    else
2633       return CopyString(_class.fullName);
2634 }
2635
2636 Type ReplaceThisClassType(Class _class)
2637 {
2638    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2639    {
2640       bool first = true;
2641       int p = 0;
2642       ClassTemplateParameter param;
2643       int lastParam = -1;
2644       char className[1024];
2645       strcpy(className, _class.fullName);
2646
2647       for(param = _class.templateParams.first; param; param = param.next)
2648       {
2649          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2650          {
2651             if(first) strcat(className, "<");
2652             if(!first) strcat(className, ", ");
2653             if(lastParam + 1 != p)
2654             {
2655                strcat(className, param.name);
2656                strcat(className, " = ");
2657             }
2658             strcat(className, param.name);
2659             first = false;
2660             lastParam = p;
2661          }
2662          p++;
2663       }
2664       if(!first)
2665       {
2666          int len = strlen(className);
2667          if(className[len-1] == '>') className[len++] = ' ';
2668          className[len++] = '>';
2669          className[len++] = '\0';
2670       }
2671       return MkClassType(className);
2672       //return ProcessTypeString(className, false);
2673    }
2674    else
2675    {
2676       return MkClassType(_class.fullName);
2677       //return ProcessTypeString(_class.fullName, false);
2678    }
2679 }
2680
2681 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2682 {
2683    if(specs != null && _class)
2684    {
2685       Specifier spec;
2686       for(spec = specs.first; spec; spec = spec.next)
2687       {
2688          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2689          {
2690             spec.type = nameSpecifier;
2691             spec.name = ReplaceThisClass(_class);
2692             spec.symbol = FindClass(spec.name); //_class.symbol;
2693          }
2694       }
2695    }
2696 }
2697
2698 // Returns imported or not
2699 bool DeclareFunction(GlobalFunction function, char * name)
2700 {
2701    Symbol symbol = function.symbol;
2702    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2703    {
2704       bool imported = false;
2705       bool dllImport = false;
2706
2707       if(!function.dataType)
2708       {
2709          function.dataType = ProcessTypeString(function.dataTypeString, false);
2710          if(!function.dataType.thisClass)
2711             function.dataType.staticMethod = true;
2712       }
2713
2714       if(inCompiler)
2715       {
2716          if(!symbol)
2717          {
2718             ModuleImport module = FindModule(function.module);
2719             // WARNING: This is not added anywhere...
2720             symbol = function.symbol = Symbol {  };
2721
2722             if(module.name)
2723             {
2724                if(!function.dataType.dllExport)
2725                {
2726                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2727                   module.functions.Add(symbol._import);
2728                }
2729             }
2730             // Set the symbol type
2731             {
2732                symbol.type = ProcessTypeString(function.dataTypeString, false);
2733                if(!symbol.type.thisClass)
2734                   symbol.type.staticMethod = true;
2735             }
2736          }
2737          imported = symbol._import ? true : false;
2738          if(imported && function.module != privateModule && function.module.importType != staticImport)
2739             dllImport = true;
2740       }
2741
2742       DeclareType(function.dataType, true, true);
2743
2744       if(inCompiler)
2745       {
2746          if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2747          {
2748             // We need a declaration here :)
2749             Declaration decl;
2750             OldList * specifiers, * declarators;
2751             Declarator d;
2752             Declarator funcDecl;
2753             External external;
2754
2755             specifiers = MkList();
2756             declarators = MkList();
2757
2758             //if(imported)
2759                ListAdd(specifiers, MkSpecifier(EXTERN));
2760             /*
2761             else
2762                ListAdd(specifiers, MkSpecifier(STATIC));
2763             */
2764
2765             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2766             //if(imported)
2767             if(dllImport)
2768                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2769
2770             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2771             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2772             if(function.module.importType == staticImport)
2773             {
2774                Specifier spec;
2775                for(spec = specifiers->first; spec; spec = spec.next)
2776                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2777                   {
2778                      specifiers->Remove(spec);
2779                      FreeSpecifier(spec);
2780                      break;
2781                   }
2782             }
2783
2784             funcDecl = GetFuncDecl(d);
2785
2786             // Make sure we don't have empty parameter declarations for static methods...
2787             if(funcDecl && !funcDecl.function.parameters)
2788             {
2789                funcDecl.function.parameters = MkList();
2790                funcDecl.function.parameters->Insert(null,
2791                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2792             }
2793
2794             ListAdd(declarators, MkInitDeclarator(d, null));
2795
2796             {
2797                Context oldCtx = curContext;
2798                curContext = globalContext;
2799                decl = MkDeclaration(specifiers, declarators);
2800                curContext = oldCtx;
2801             }
2802
2803             // Keep a different symbol for the function definition than the declaration...
2804             if(symbol.pointerExternal)
2805             {
2806                Symbol functionSymbol { };
2807                // Copy symbol
2808                {
2809                   *functionSymbol = *symbol;
2810                   functionSymbol.string = CopyString(symbol.string);
2811                   if(functionSymbol.type)
2812                      functionSymbol.type.refCount++;
2813                }
2814
2815                excludedSymbols->Add(functionSymbol);
2816
2817                symbol.pointerExternal.symbol = functionSymbol;
2818             }
2819             external = MkExternalDeclaration(decl);
2820             if(curExternal)
2821                ast->Insert(curExternal.prev, external);
2822             external.symbol = symbol;
2823             symbol.pointerExternal = external;
2824          }
2825          else
2826          {
2827             // Move declaration higher...
2828             ast->Move(symbol.pointerExternal, curExternal.prev);
2829          }
2830
2831          if(curExternal)
2832             symbol.id = curExternal.symbol.idCode;
2833       }
2834    }
2835    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2836 }
2837
2838 void DeclareGlobalData(GlobalData data)
2839 {
2840    Symbol symbol = data.symbol;
2841    if(curExternal && (!symbol || symbol.id > curExternal.symbol.idCode))
2842    {
2843       if(inCompiler)
2844       {
2845          if(!symbol)
2846             symbol = data.symbol = Symbol { };
2847       }
2848       if(!data.dataType)
2849          data.dataType = ProcessTypeString(data.dataTypeString, false);
2850       DeclareType(data.dataType, true, true);
2851       if(inCompiler)
2852       {
2853          if(!symbol.pointerExternal)
2854          {
2855             // We need a declaration here :)
2856             Declaration decl;
2857             OldList * specifiers, * declarators;
2858             Declarator d;
2859             External external;
2860
2861             specifiers = MkList();
2862             declarators = MkList();
2863
2864             ListAdd(specifiers, MkSpecifier(EXTERN));
2865             d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2866             d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2867
2868             ListAdd(declarators, MkInitDeclarator(d, null));
2869
2870             decl = MkDeclaration(specifiers, declarators);
2871             external = MkExternalDeclaration(decl);
2872             if(curExternal)
2873                ast->Insert(curExternal.prev, external);
2874             external.symbol = symbol;
2875             symbol.pointerExternal = external;
2876          }
2877          else
2878          {
2879             // Move declaration higher...
2880             ast->Move(symbol.pointerExternal, curExternal.prev);
2881          }
2882
2883          if(curExternal)
2884             symbol.id = curExternal.symbol.idCode;
2885       }
2886    }
2887 }
2888
2889 class Conversion : struct
2890 {
2891    Conversion prev, next;
2892    Property convert;
2893    bool isGet;
2894    Type resultType;
2895 };
2896
2897 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams, bool isConversionExploration)
2898 {
2899    if(source && dest)
2900    {
2901       // Property convert;
2902
2903       if(source.kind == templateType && dest.kind != templateType)
2904       {
2905          Type type = ProcessTemplateParameterType(source.templateParameter);
2906          if(type) source = type;
2907       }
2908
2909       if(dest.kind == templateType && source.kind != templateType)
2910       {
2911          Type type = ProcessTemplateParameterType(dest.templateParameter);
2912          if(type) dest = type;
2913       }
2914
2915       if(dest.classObjectType == typedObject)
2916       {
2917          if(source.classObjectType != anyObject)
2918             return true;
2919          else
2920          {
2921             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
2922             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
2923             {
2924                return true;
2925             }
2926          }
2927       }
2928       else
2929       {
2930          if(source.classObjectType == anyObject)
2931             return true;
2932          if(dest.classObjectType == anyObject && source.classObjectType != typedObject)
2933             return true;
2934       }
2935
2936       if((dest.kind == structType && source.kind == structType) ||
2937          (dest.kind == unionType && source.kind == unionType))
2938       {
2939          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
2940              (source.members.first && source.members.first == dest.members.first))
2941             return true;
2942       }
2943
2944       if(dest.kind == ellipsisType && source.kind != voidType)
2945          return true;
2946
2947       if(dest.kind == pointerType && dest.type.kind == voidType &&
2948          ((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))
2949          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
2950
2951          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
2952
2953          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
2954          return true;
2955       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
2956          ((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))
2957          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
2958
2959          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
2960
2961          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
2962          return true;
2963
2964       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
2965       {
2966          if(source._class.registered && source._class.registered.type == unitClass)
2967          {
2968             if(conversions != null)
2969             {
2970                if(source._class.registered == dest._class.registered)
2971                   return true;
2972             }
2973             else
2974             {
2975                Class sourceBase, destBase;
2976                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
2977                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
2978                if(sourceBase == destBase)
2979                   return true;
2980             }
2981          }
2982          // Don't match enum inheriting from other enum if resolving enumeration values
2983          // TESTING: !dest.classObjectType
2984          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
2985             (enumBaseType ||
2986                (!source._class.registered || source._class.registered.type != enumClass) ||
2987                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
2988             return true;
2989          else
2990          {
2991             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
2992             if(enumBaseType &&
2993                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
2994                ((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)
2995             {
2996                if(eClass_IsDerived(dest._class.registered, source._class.registered))
2997                {
2998                   return true;
2999                }
3000             }
3001          }
3002       }
3003
3004       // JUST ADDED THIS...
3005       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
3006          return true;
3007
3008       if(doConversion)
3009       {
3010          // Just added this for Straight conversion of ColorAlpha => Color
3011          if(source.kind == classType)
3012          {
3013             Class _class;
3014             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3015             {
3016                Property convert;
3017                for(convert = _class.conversions.first; convert; convert = convert.next)
3018                {
3019                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3020                   {
3021                      Conversion after = (conversions != null) ? conversions.last : null;
3022
3023                      if(!convert.dataType)
3024                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3025                      if(MatchTypes(convert.dataType, dest, conversions, null, null, false, true, false, true))
3026                      {
3027                         if(!conversions && !convert.Get)
3028                            return true;
3029                         else if(conversions != null)
3030                         {
3031                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3032                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3033                               (dest.kind != classType || dest._class.registered != _class.base))
3034                               return true;
3035                            else
3036                            {
3037                               Conversion conv { convert = convert, isGet = true };
3038                               // conversions.Add(conv);
3039                               conversions.Insert(after, conv);
3040                               return true;
3041                            }
3042                         }
3043                      }
3044                   }
3045                }
3046             }
3047          }
3048
3049          // MOVING THIS??
3050
3051          if(dest.kind == classType)
3052          {
3053             Class _class;
3054             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3055             {
3056                Property convert;
3057                for(convert = _class.conversions.first; convert; convert = convert.next)
3058                {
3059                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3060                   {
3061                      // Conversion after = (conversions != null) ? conversions.last : null;
3062
3063                      if(!convert.dataType)
3064                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3065                      // Just added this equality check to prevent recursion.... Make it safer?
3066                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3067                      if(convert.dataType != dest && MatchTypes(source, convert.dataType, conversions, null, null, true, false /*true*/, false, true))
3068                      {
3069                         if(!conversions && !convert.Set)
3070                            return true;
3071                         else if(conversions != null)
3072                         {
3073                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3074                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3075                               (source.kind != classType || source._class.registered != _class.base))
3076                               return true;
3077                            else
3078                            {
3079                               // *** Testing this! ***
3080                               Conversion conv { convert = convert };
3081                               conversions.Add(conv);
3082                               //conversions.Insert(after, conv);
3083                               return true;
3084                            }
3085                         }
3086                      }
3087                   }
3088                }
3089             }
3090             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3091             {
3092                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3093                   (source.kind != classType || source._class.registered.type != structClass))
3094                   return true;
3095             }*/
3096
3097             // TESTING THIS... IS THIS OK??
3098             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3099             {
3100                if(!dest._class.registered.dataType)
3101                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3102                // Only support this for classes...
3103                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3104                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3105                {
3106                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false))
3107                   {
3108                      return true;
3109                   }
3110                }
3111             }
3112          }
3113
3114          // Moved this lower
3115          if(source.kind == classType)
3116          {
3117             Class _class;
3118             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3119             {
3120                Property convert;
3121                for(convert = _class.conversions.first; convert; convert = convert.next)
3122                {
3123                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3124                   {
3125                      Conversion after = (conversions != null) ? conversions.last : null;
3126
3127                      if(!convert.dataType)
3128                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3129                      if(convert.dataType != source && MatchTypes(convert.dataType, dest, conversions, null, null, true, true, false, true))
3130                      {
3131                         if(!conversions && !convert.Get)
3132                            return true;
3133                         else if(conversions != null)
3134                         {
3135                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3136                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3137                               (dest.kind != classType || dest._class.registered != _class.base))
3138                               return true;
3139                            else
3140                            {
3141                               Conversion conv { convert = convert, isGet = true };
3142
3143                               // conversions.Add(conv);
3144                               conversions.Insert(after, conv);
3145                               return true;
3146                            }
3147                         }
3148                      }
3149                   }
3150                }
3151             }
3152
3153             // TESTING THIS... IS THIS OK??
3154             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3155             {
3156                if(!source._class.registered.dataType)
3157                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3158                if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, true, false, false))
3159                {
3160                   return true;
3161                }
3162             }
3163          }
3164       }
3165
3166       if(source.kind == classType || source.kind == subClassType)
3167          ;
3168       else if(dest.kind == source.kind &&
3169          (dest.kind != structType && dest.kind != unionType &&
3170           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3171           return true;
3172       // RECENTLY ADDED THESE
3173       else if(dest.kind == doubleType && source.kind == floatType)
3174          return true;
3175       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3176          return true;
3177       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3178          return true;
3179       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3180          return true;
3181       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3182          return true;
3183       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3184          return true;
3185       else if(source.kind == enumType &&
3186          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3187           return true;
3188       else if(dest.kind == enumType &&
3189          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3190           return true;
3191       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3192               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3193       {
3194          Type paramSource, paramDest;
3195
3196          if(dest.kind == methodType)
3197             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3198          if(source.kind == methodType)
3199             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3200
3201          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3202          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3203          if(dest.kind == methodType)
3204             dest = dest.method.dataType;
3205          if(source.kind == methodType)
3206             source = source.method.dataType;
3207
3208          paramSource = source.params.first;
3209          if(paramSource && paramSource.kind == voidType) paramSource = null;
3210          paramDest = dest.params.first;
3211          if(paramDest && paramDest.kind == voidType) paramDest = null;
3212
3213
3214          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3215             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3216          {
3217             // Source thisClass must be derived from destination thisClass
3218             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3219                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3220             {
3221                if(paramDest && paramDest.kind == classType)
3222                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3223                else
3224                   Compiler_Error($"method class should not take an object\n");
3225                return false;
3226             }
3227             paramDest = paramDest.next;
3228          }
3229          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3230          {
3231             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3232             {
3233                if(dest.thisClass)
3234                {
3235                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3236                   {
3237                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3238                      return false;
3239                   }
3240                }
3241                else
3242                {
3243                   // THIS WAS BACKWARDS:
3244                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3245                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3246                   {
3247                      if(owningClassDest)
3248                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3249                      else
3250                         Compiler_Error($"overriding class expected to be derived from method class\n");
3251                      return false;
3252                   }
3253                }
3254                paramSource = paramSource.next;
3255             }
3256             else
3257             {
3258                if(dest.thisClass)
3259                {
3260                   // Source thisClass must be derived from destination thisClass
3261                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3262                   {
3263                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3264                      return false;
3265                   }
3266                }
3267                else
3268                {
3269                   // THIS WAS BACKWARDS TOO??
3270                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3271                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3272                   {
3273                      //if(owningClass)
3274                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3275                      //else
3276                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3277                      return false;
3278                   }
3279                }
3280             }
3281          }
3282
3283
3284          // Source return type must be derived from destination return type
3285          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false))
3286          {
3287             Compiler_Warning($"incompatible return type for function\n");
3288             return false;
3289          }
3290
3291          // Check parameters
3292
3293          for(; paramDest; paramDest = paramDest.next)
3294          {
3295             if(!paramSource)
3296             {
3297                //Compiler_Warning($"not enough parameters\n");
3298                Compiler_Error($"not enough parameters\n");
3299                return false;
3300             }
3301             {
3302                Type paramDestType = paramDest;
3303                Type paramSourceType = paramSource;
3304                Type type = paramDestType;
3305
3306                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3307                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3308                   paramSource.kind != templateType)
3309                {
3310                   int id = 0;
3311                   ClassTemplateParameter curParam = null;
3312                   Class sClass;
3313                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3314                   {
3315                      id = 0;
3316                      if(sClass.templateClass) sClass = sClass.templateClass;
3317                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3318                      {
3319                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3320                         {
3321                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3322                            {
3323                               if(sClass.templateClass) sClass = sClass.templateClass;
3324                               id += sClass.templateParams.count;
3325                            }
3326                            break;
3327                         }
3328                         id++;
3329                      }
3330                      if(curParam) break;
3331                   }
3332
3333                   if(curParam)
3334                   {
3335                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3336                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3337                   }
3338                }
3339
3340                // paramDest must be derived from paramSource
3341                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false) &&
3342                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false)))
3343                {
3344                   char type[1024];
3345                   type[0] = 0;
3346                   PrintType(paramDest, type, false, true);
3347                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3348
3349                   if(paramDestType != paramDest)
3350                      FreeType(paramDestType);
3351                   return false;
3352                }
3353                if(paramDestType != paramDest)
3354                   FreeType(paramDestType);
3355             }
3356
3357             paramSource = paramSource.next;
3358          }
3359          if(paramSource)
3360          {
3361             Compiler_Error($"too many parameters\n");
3362             return false;
3363          }
3364          return true;
3365       }
3366       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3367       {
3368          return true;
3369       }
3370       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3371          (source.kind == arrayType || source.kind == pointerType))
3372       {
3373          if(MatchTypes(source.type, dest.type, null, null, null, true, true, false, false))
3374             return true;
3375       }
3376    }
3377    return false;
3378 }
3379
3380 static void FreeConvert(Conversion convert)
3381 {
3382    if(convert.resultType)
3383       FreeType(convert.resultType);
3384 }
3385
3386 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3387                               char * string, OldList conversions)
3388 {
3389    BTNamedLink link;
3390
3391    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3392    {
3393       Class _class = link.data;
3394       if(_class.type == enumClass)
3395       {
3396          OldList converts { };
3397          Type type { };
3398          type.kind = classType;
3399
3400          if(!_class.symbol)
3401             _class.symbol = FindClass(_class.fullName);
3402          type._class = _class.symbol;
3403
3404          if(MatchTypes(type, dest, &converts, null, null, true, false, false, false))
3405          {
3406             NamedLink value;
3407             Class enumClass = eSystem_FindClass(privateModule, "enum");
3408             if(enumClass)
3409             {
3410                Class baseClass;
3411                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3412                {
3413                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3414                   for(value = e.values.first; value; value = value.next)
3415                   {
3416                      if(!strcmp(value.name, string))
3417                         break;
3418                   }
3419                   if(value)
3420                   {
3421                      FreeExpContents(sourceExp);
3422                      FreeType(sourceExp.expType);
3423
3424                      sourceExp.isConstant = true;
3425                      sourceExp.expType = MkClassType(baseClass.fullName);
3426                      //if(inCompiler)
3427                      {
3428                         char constant[256];
3429                         sourceExp.type = constantExp;
3430                         if(!strcmp(baseClass.dataTypeString, "int"))
3431                            sprintf(constant, "%d",(int)value.data);
3432                         else
3433                            sprintf(constant, "0x%X",(int)value.data);
3434                         sourceExp.constant = CopyString(constant);
3435                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3436                      }
3437
3438                      while(converts.first)
3439                      {
3440                         Conversion convert = converts.first;
3441                         converts.Remove(convert);
3442                         conversions.Add(convert);
3443                      }
3444                      delete type;
3445                      return true;
3446                   }
3447                }
3448             }
3449          }
3450          if(converts.first)
3451             converts.Free(FreeConvert);
3452          delete type;
3453       }
3454    }
3455    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3456       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3457          return true;
3458    return false;
3459 }
3460
3461 public bool ModuleVisibility(Module searchIn, Module searchFor)
3462 {
3463    SubModule subModule;
3464
3465    if(searchFor == searchIn)
3466       return true;
3467
3468    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3469    {
3470       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3471       {
3472          if(ModuleVisibility(subModule.module, searchFor))
3473             return true;
3474       }
3475    }
3476    return false;
3477 }
3478
3479 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3480 {
3481    Module module;
3482
3483    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3484       return true;
3485    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3486       return true;
3487    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3488       return true;
3489
3490    for(module = mainModule.application.allModules.first; module; module = module.next)
3491    {
3492       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3493          return true;
3494    }
3495    return false;
3496 }
3497
3498 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla)
3499 {
3500    Type source = sourceExp.expType;
3501    Type realDest = dest;
3502    Type backupSourceExpType = null;
3503
3504    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3505       return true;
3506
3507    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3508    {
3509        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3510        {
3511           Class sourceBase, destBase;
3512           for(sourceBase = source._class.registered;
3513               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3514               sourceBase = sourceBase.base);
3515           for(destBase = dest._class.registered;
3516               destBase && destBase.base && destBase.base.type != systemClass;
3517               destBase = destBase.base);
3518           //if(source._class.registered == dest._class.registered)
3519           if(sourceBase == destBase)
3520              return true;
3521        }
3522    }
3523
3524    if(source)
3525    {
3526       OldList * specs;
3527       bool flag = false;
3528       int64 value = MAXINT;
3529
3530       source.refCount++;
3531       dest.refCount++;
3532
3533       if(sourceExp.type == constantExp)
3534       {
3535          if(source.isSigned)
3536             value = strtoll(sourceExp.constant, null, 0);
3537          else
3538             value = strtoull(sourceExp.constant, null, 0);
3539       }
3540       else if(sourceExp.type == opExp && sourceExp.op.op == '-' && !sourceExp.op.exp1 && sourceExp.op.exp2 && sourceExp.op.exp2.type == constantExp)
3541       {
3542          if(source.isSigned)
3543             value = -strtoll(sourceExp.op.exp2.constant, null, 0);
3544          else
3545             value = -strtoull(sourceExp.op.exp2.constant, null, 0);
3546       }
3547
3548       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3549          !strcmp(source._class.registered.fullName, "ecere::com::unichar"))
3550       {
3551          FreeType(source);
3552          source = Type { kind = intType, isSigned = false, refCount = 1 };
3553       }
3554
3555       if(dest.kind == classType)
3556       {
3557          Class _class = dest._class ? dest._class.registered : null;
3558
3559          if(_class && _class.type == unitClass)
3560          {
3561             if(source.kind != classType)
3562             {
3563                Type tempType { };
3564                Type tempDest, tempSource;
3565
3566                for(; _class.base.type != systemClass; _class = _class.base);
3567                tempSource = dest;
3568                tempDest = tempType;
3569
3570                tempType.kind = classType;
3571                if(!_class.symbol)
3572                   _class.symbol = FindClass(_class.fullName);
3573
3574                tempType._class = _class.symbol;
3575                tempType.truth = dest.truth;
3576                if(tempType._class)
3577                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false);
3578
3579                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3580                backupSourceExpType = sourceExp.expType;
3581                sourceExp.expType = dest; dest.refCount++;
3582                //sourceExp.expType = MkClassType(_class.fullName);
3583                flag = true;
3584
3585                delete tempType;
3586             }
3587          }
3588
3589
3590          // Why wasn't there something like this?
3591          if(_class && _class.type == bitClass && source.kind != classType)
3592          {
3593             if(!dest._class.registered.dataType)
3594                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3595             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false))
3596             {
3597                FreeType(source);
3598                FreeType(sourceExp.expType);
3599                source = sourceExp.expType = MkClassType(dest._class.string);
3600                source.refCount++;
3601
3602                //source.kind = classType;
3603                //source._class = dest._class;
3604             }
3605          }
3606
3607          // Adding two enumerations
3608          /*
3609          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3610          {
3611             if(!source._class.registered.dataType)
3612                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3613             if(!dest._class.registered.dataType)
3614                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3615
3616             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3617             {
3618                FreeType(source);
3619                source = sourceExp.expType = MkClassType(dest._class.string);
3620                source.refCount++;
3621
3622                //source.kind = classType;
3623                //source._class = dest._class;
3624             }
3625          }*/
3626
3627          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3628          {
3629             OldList * specs = MkList();
3630             Declarator decl;
3631             char string[1024];
3632
3633             ReadString(string, sourceExp.string);
3634             decl = SpecDeclFromString(string, specs, null);
3635
3636             FreeExpContents(sourceExp);
3637             FreeType(sourceExp.expType);
3638
3639             sourceExp.type = classExp;
3640             sourceExp._classExp.specifiers = specs;
3641             sourceExp._classExp.decl = decl;
3642             sourceExp.expType = dest;
3643             dest.refCount++;
3644
3645             FreeType(source);
3646             FreeType(dest);
3647             if(backupSourceExpType) FreeType(backupSourceExpType);
3648             return true;
3649          }
3650       }
3651       else if(source.kind == classType)
3652       {
3653          Class _class = source._class ? source._class.registered : null;
3654
3655          if(_class && (_class.type == unitClass || !strcmp(_class.fullName, "bool") || /*_class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3656          {
3657             /*
3658             if(dest.kind != classType)
3659             {
3660                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3661                if(!source._class.registered.dataType)
3662                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3663
3664                FreeType(dest);
3665                dest = MkClassType(source._class.string);
3666                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3667                //   dest = MkClassType(source._class.string);
3668             }
3669             */
3670
3671             if(dest.kind != classType)
3672             {
3673                Type tempType { };
3674                Type tempDest, tempSource;
3675
3676                if(!source._class.registered.dataType)
3677                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3678
3679                for(; _class.base.type != systemClass; _class = _class.base);
3680                tempDest = source;
3681                tempSource = tempType;
3682                tempType.kind = classType;
3683                tempType._class = FindClass(_class.fullName);
3684                tempType.truth = source.truth;
3685                tempType.classObjectType = source.classObjectType;
3686
3687                if(tempType._class)
3688                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false);
3689
3690                // PUT THIS BACK TESTING UNITS?
3691                if(conversions.last)
3692                {
3693                   ((Conversion)(conversions.last)).resultType = dest;
3694                   dest.refCount++;
3695                }
3696
3697                FreeType(sourceExp.expType);
3698                sourceExp.expType = MkClassType(_class.fullName);
3699                sourceExp.expType.truth = source.truth;
3700                sourceExp.expType.classObjectType = source.classObjectType;
3701
3702                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3703
3704                if(!sourceExp.destType)
3705                {
3706                   FreeType(sourceExp.destType);
3707                   sourceExp.destType = sourceExp.expType;
3708                   if(sourceExp.expType)
3709                      sourceExp.expType.refCount++;
3710                }
3711                //flag = true;
3712                //source = _class.dataType;
3713
3714
3715                // TOCHECK: TESTING THIS NEW CODE
3716                if(!_class.dataType)
3717                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3718                FreeType(dest);
3719                dest = MkClassType(source._class.string);
3720                dest.truth = source.truth;
3721                dest.classObjectType = source.classObjectType;
3722
3723                FreeType(source);
3724                source = _class.dataType;
3725                source.refCount++;
3726
3727                delete tempType;
3728             }
3729          }
3730       }
3731
3732       if(!flag)
3733       {
3734          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false))
3735          {
3736             FreeType(source);
3737             FreeType(dest);
3738             return true;
3739          }
3740       }
3741
3742       // Implicit Casts
3743       /*
3744       if(source.kind == classType)
3745       {
3746          Class _class = source._class.registered;
3747          if(_class.type == unitClass)
3748          {
3749             if(!_class.dataType)
3750                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3751             source = _class.dataType;
3752          }
3753       }*/
3754
3755       if(dest.kind == classType)
3756       {
3757          Class _class = dest._class ? dest._class.registered : null;
3758          if(_class && !dest.truth && (_class.type == unitClass || !strcmp(_class.fullName, "bool") ||
3759             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3760          {
3761             if(_class.type == normalClass || _class.type == noHeadClass)
3762             {
3763                Expression newExp { };
3764                *newExp = *sourceExp;
3765                if(sourceExp.destType) sourceExp.destType.refCount++;
3766                if(sourceExp.expType)  sourceExp.expType.refCount++;
3767                sourceExp.type = castExp;
3768                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3769                sourceExp.cast.exp = newExp;
3770                FreeType(sourceExp.expType);
3771                sourceExp.expType = null;
3772                ProcessExpressionType(sourceExp);
3773
3774                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3775                if(!inCompiler)
3776                {
3777                   FreeType(sourceExp.expType);
3778                   sourceExp.expType = dest;
3779                }
3780
3781                FreeType(source);
3782                if(inCompiler) FreeType(dest);
3783
3784                if(backupSourceExpType) FreeType(backupSourceExpType);
3785                return true;
3786             }
3787
3788             if(!_class.dataType)
3789                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3790             FreeType(dest);
3791             dest = _class.dataType;
3792             dest.refCount++;
3793          }
3794
3795          // Accept lower precision types for units, since we want to keep the unit type
3796          if(dest.kind == doubleType &&
3797             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3798              source.kind == charType || source.kind == _BoolType))
3799          {
3800             specs = MkListOne(MkSpecifier(DOUBLE));
3801          }
3802          else if(dest.kind == floatType &&
3803             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3804             source.kind == _BoolType || source.kind == doubleType))
3805          {
3806             specs = MkListOne(MkSpecifier(FLOAT));
3807          }
3808          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3809             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3810          {
3811             specs = MkList();
3812             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3813             ListAdd(specs, MkSpecifier(INT64));
3814          }
3815          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
3816             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3817          {
3818             specs = MkList();
3819             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3820             ListAdd(specs, MkSpecifier(INT));
3821          }
3822          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
3823             source.kind == floatType || source.kind == doubleType))
3824          {
3825             specs = MkList();
3826             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3827             ListAdd(specs, MkSpecifier(SHORT));
3828          }
3829          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
3830             source.kind == floatType || source.kind == doubleType))
3831          {
3832             specs = MkList();
3833             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3834             ListAdd(specs, MkSpecifier(CHAR));
3835          }
3836          else
3837          {
3838             FreeType(source);
3839             FreeType(dest);
3840             if(backupSourceExpType)
3841             {
3842                // Failed to convert: revert previous exp type
3843                if(sourceExp.expType) FreeType(sourceExp.expType);
3844                sourceExp.expType = backupSourceExpType;
3845             }
3846             return false;
3847          }
3848       }
3849       else if(dest.kind == doubleType &&
3850          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
3851           source.kind == _BoolType || source.kind == charType))
3852       {
3853          specs = MkListOne(MkSpecifier(DOUBLE));
3854       }
3855       else if(dest.kind == floatType &&
3856          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3857       {
3858          specs = MkListOne(MkSpecifier(FLOAT));
3859       }
3860       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3861          (value == 1 || value == 0))
3862       {
3863          specs = MkList();
3864          ListAdd(specs, MkSpecifier(BOOL));
3865       }
3866       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3867          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
3868       {
3869          specs = MkList();
3870          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3871          ListAdd(specs, MkSpecifier(CHAR));
3872       }
3873       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
3874          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
3875       {
3876          specs = MkList();
3877          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3878          ListAdd(specs, MkSpecifier(SHORT));
3879       }
3880       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
3881       {
3882          specs = MkList();
3883          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3884          ListAdd(specs, MkSpecifier(INT));
3885       }
3886       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
3887       {
3888          specs = MkList();
3889          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3890          ListAdd(specs, MkSpecifier(INT64));
3891       }
3892       else if(dest.kind == enumType &&
3893          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3894       {
3895          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
3896       }
3897       else
3898       {
3899          FreeType(source);
3900          FreeType(dest);
3901          if(backupSourceExpType)
3902          {
3903             // Failed to convert: revert previous exp type
3904             if(sourceExp.expType) FreeType(sourceExp.expType);
3905             sourceExp.expType = backupSourceExpType;
3906          }
3907          return false;
3908       }
3909
3910       if(!flag)
3911       {
3912          Expression newExp { };
3913          *newExp = *sourceExp;
3914          newExp.prev = null;
3915          newExp.next = null;
3916          if(sourceExp.destType) sourceExp.destType.refCount++;
3917          if(sourceExp.expType)  sourceExp.expType.refCount++;
3918
3919          sourceExp.type = castExp;
3920          if(realDest.kind == classType)
3921          {
3922             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
3923             FreeList(specs, FreeSpecifier);
3924          }
3925          else
3926             sourceExp.cast.typeName = MkTypeName(specs, null);
3927          if(newExp.type == opExp)
3928          {
3929             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
3930          }
3931          else
3932             sourceExp.cast.exp = newExp;
3933
3934          FreeType(sourceExp.expType);
3935          sourceExp.expType = null;
3936          ProcessExpressionType(sourceExp);
3937       }
3938       else
3939          FreeList(specs, FreeSpecifier);
3940
3941       FreeType(dest);
3942       FreeType(source);
3943       if(backupSourceExpType) FreeType(backupSourceExpType);
3944
3945       return true;
3946    }
3947    else
3948    {
3949       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
3950       if(sourceExp.type == identifierExp)
3951       {
3952          Identifier id = sourceExp.identifier;
3953          if(dest.kind == classType)
3954          {
3955             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3956             {
3957                Class _class = dest._class.registered;
3958                Class enumClass = eSystem_FindClass(privateModule, "enum");
3959                if(enumClass)
3960                {
3961                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
3962                   {
3963                      NamedLink value;
3964                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
3965                      for(value = e.values.first; value; value = value.next)
3966                      {
3967                         if(!strcmp(value.name, id.string))
3968                            break;
3969                      }
3970                      if(value)
3971                      {
3972                         FreeExpContents(sourceExp);
3973                         FreeType(sourceExp.expType);
3974
3975                         sourceExp.isConstant = true;
3976                         sourceExp.expType = MkClassType(_class.fullName);
3977                         //if(inCompiler)
3978                         {
3979                            char constant[256];
3980                            sourceExp.type = constantExp;
3981                            if(/*_class && */_class.dataTypeString && !strcmp(_class.dataTypeString, "int")) // _class cannot be null here!
3982                               sprintf(constant, "%d", (int) value.data);
3983                            else
3984                               sprintf(constant, "0x%X", (int) value.data);
3985                            sourceExp.constant = CopyString(constant);
3986                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
3987                         }
3988                         return true;
3989                      }
3990                   }
3991                }
3992             }
3993          }
3994
3995          // Loop through all enum classes
3996          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
3997             return true;
3998       }
3999    }
4000    return false;
4001 }
4002
4003 #define TERTIARY(o, name, m, t, p) \
4004    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4005    {                                                              \
4006       exp.type = constantExp;                                    \
4007       exp.string = p(op1.m ? op2.m : op3.m);                     \
4008       if(!exp.expType) \
4009          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4010       return true;                                                \
4011    }
4012
4013 #define BINARY(o, name, m, t, p) \
4014    static bool name(Expression exp, Operand op1, Operand op2)   \
4015    {                                                              \
4016       t value2 = op2.m;                                           \
4017       exp.type = constantExp;                                    \
4018       exp.string = p(op1.m o value2);                     \
4019       if(!exp.expType) \
4020          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4021       return true;                                                \
4022    }
4023
4024 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4025    static bool name(Expression exp, Operand op1, Operand op2)   \
4026    {                                                              \
4027       t value2 = op2.m;                                           \
4028       exp.type = constantExp;                                    \
4029       exp.string = p(value2 ? (op1.m o value2) : 0);             \
4030       if(!exp.expType) \
4031          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4032       return true;                                                \
4033    }
4034
4035 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4036    static bool name(Expression exp, Operand op1, Operand op2)   \
4037    {                                                              \
4038       t value2 = op2.m;                                           \
4039       exp.type = constantExp;                                    \
4040       exp.string = p(op1.m o value2);             \
4041       if(!exp.expType) \
4042          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4043       return true;                                                \
4044    }
4045
4046 #define UNARY(o, name, m, t, p) \
4047    static bool name(Expression exp, Operand op1)                \
4048    {                                                              \
4049       exp.type = constantExp;                                    \
4050       exp.string = p((t)(o op1.m));                                   \
4051       if(!exp.expType) \
4052          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4053       return true;                                                \
4054    }
4055
4056 #define OPERATOR_ALL(macro, o, name) \
4057    macro(o, Int##name, i, int, PrintInt) \
4058    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4059    macro(o, Int64##name, i64, int64, PrintInt64) \
4060    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4061    macro(o, Short##name, s, short, PrintShort) \
4062    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4063    macro(o, Char##name, c, char, PrintChar) \
4064    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4065    macro(o, Float##name, f, float, PrintFloat) \
4066    macro(o, Double##name, d, double, PrintDouble)
4067
4068 #define OPERATOR_INTTYPES(macro, o, name) \
4069    macro(o, Int##name, i, int, PrintInt) \
4070    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4071    macro(o, Int64##name, i64, int64, PrintInt64) \
4072    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4073    macro(o, Short##name, s, short, PrintShort) \
4074    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4075    macro(o, Char##name, c, char, PrintChar) \
4076    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4077
4078 #define OPERATOR_REALTYPES(macro, o, name) \
4079    macro(o, Float##name, f, float, PrintFloat) \
4080    macro(o, Double##name, d, double, PrintDouble)
4081
4082 // binary arithmetic
4083 OPERATOR_ALL(BINARY, +, Add)
4084 OPERATOR_ALL(BINARY, -, Sub)
4085 OPERATOR_ALL(BINARY, *, Mul)
4086 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4087 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4088 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4089
4090 // unary arithmetic
4091 OPERATOR_ALL(UNARY, -, Neg)
4092
4093 // unary arithmetic increment and decrement
4094 OPERATOR_ALL(UNARY, ++, Inc)
4095 OPERATOR_ALL(UNARY, --, Dec)
4096
4097 // binary arithmetic assignment
4098 OPERATOR_ALL(BINARY, =, Asign)
4099 OPERATOR_ALL(BINARY, +=, AddAsign)
4100 OPERATOR_ALL(BINARY, -=, SubAsign)
4101 OPERATOR_ALL(BINARY, *=, MulAsign)
4102 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4103 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4104 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4105
4106 // binary bitwise
4107 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4108 OPERATOR_INTTYPES(BINARY, |, BitOr)
4109 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4110 OPERATOR_INTTYPES(BINARY, <<, LShift)
4111 OPERATOR_INTTYPES(BINARY, >>, RShift)
4112
4113 // unary bitwise
4114 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4115
4116 // binary bitwise assignment
4117 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4118 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4119 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4120 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4121 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4122
4123 // unary logical negation
4124 OPERATOR_INTTYPES(UNARY, !, Not)
4125
4126 // binary logical equality
4127 OPERATOR_ALL(BINARY, ==, Equ)
4128 OPERATOR_ALL(BINARY, !=, Nqu)
4129
4130 // binary logical
4131 OPERATOR_ALL(BINARY, &&, And)
4132 OPERATOR_ALL(BINARY, ||, Or)
4133
4134 // binary logical relational
4135 OPERATOR_ALL(BINARY, >, Grt)
4136 OPERATOR_ALL(BINARY, <, Sma)
4137 OPERATOR_ALL(BINARY, >=, GrtEqu)
4138 OPERATOR_ALL(BINARY, <=, SmaEqu)
4139
4140 // tertiary condition operator
4141 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4142
4143 //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
4144 #define OPERATOR_TABLE_ALL(name, type) \
4145     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4146                           type##Neg, \
4147                           type##Inc, type##Dec, \
4148                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4149                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4150                           type##BitNot, \
4151                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4152                           type##Not, \
4153                           type##Equ, type##Nqu, \
4154                           type##And, type##Or, \
4155                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4156                         }; \
4157
4158 #define OPERATOR_TABLE_INTTYPES(name, type) \
4159     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4160                           type##Neg, \
4161                           type##Inc, type##Dec, \
4162                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4163                           null, null, null, null, null, \
4164                           null, \
4165                           null, null, null, null, null, \
4166                           null, \
4167                           type##Equ, type##Nqu, \
4168                           type##And, type##Or, \
4169                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4170                         }; \
4171
4172 OPERATOR_TABLE_ALL(int, Int)
4173 OPERATOR_TABLE_ALL(uint, UInt)
4174 OPERATOR_TABLE_ALL(int64, Int64)
4175 OPERATOR_TABLE_ALL(uint64, UInt64)
4176 OPERATOR_TABLE_ALL(short, Short)
4177 OPERATOR_TABLE_ALL(ushort, UShort)
4178 OPERATOR_TABLE_INTTYPES(float, Float)
4179 OPERATOR_TABLE_INTTYPES(double, Double)
4180 OPERATOR_TABLE_ALL(char, Char)
4181 OPERATOR_TABLE_ALL(uchar, UChar)
4182
4183 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4184 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4185 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4186 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4187 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4188 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4189 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4190 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4191
4192 public void ReadString(char * output,  char * string)
4193 {
4194    int len = strlen(string);
4195    int c,d = 0;
4196    bool quoted = false, escaped = false;
4197    for(c = 0; c<len; c++)
4198    {
4199       char ch = string[c];
4200       if(escaped)
4201       {
4202          switch(ch)
4203          {
4204             case 'n': output[d] = '\n'; break;
4205             case 't': output[d] = '\t'; break;
4206             case 'a': output[d] = '\a'; break;
4207             case 'b': output[d] = '\b'; break;
4208             case 'f': output[d] = '\f'; break;
4209             case 'r': output[d] = '\r'; break;
4210             case 'v': output[d] = '\v'; break;
4211             case '\\': output[d] = '\\'; break;
4212             case '\"': output[d] = '\"'; break;
4213             case '\'': output[d] = '\''; break;
4214             default: output[d] = ch;
4215          }
4216          d++;
4217          escaped = false;
4218       }
4219       else
4220       {
4221          if(ch == '\"')
4222             quoted ^= true;
4223          else if(quoted)
4224          {
4225             if(ch == '\\')
4226                escaped = true;
4227             else
4228                output[d++] = ch;
4229          }
4230       }
4231    }
4232    output[d] = '\0';
4233 }
4234
4235 // String Unescape Copy
4236
4237 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4238 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4239 public int UnescapeString(char * d, char * s, int len)
4240 {
4241    int j = 0, k = 0;
4242    char ch;
4243    while(j < len && (ch = s[j]))
4244    {
4245       switch(ch)
4246       {
4247          case '\\':
4248             switch((ch = s[++j]))
4249             {
4250                case 'n': d[k] = '\n'; break;
4251                case 't': d[k] = '\t'; break;
4252                case 'a': d[k] = '\a'; break;
4253                case 'b': d[k] = '\b'; break;
4254                case 'f': d[k] = '\f'; break;
4255                case 'r': d[k] = '\r'; break;
4256                case 'v': d[k] = '\v'; break;
4257                case '\\': d[k] = '\\'; break;
4258                case '\"': d[k] = '\"'; break;
4259                case '\'': d[k] = '\''; break;
4260                default: d[k] = '\\'; d[k] = ch;
4261             }
4262             break;
4263          default:
4264             d[k] = ch;
4265       }
4266       j++, k++;
4267    }
4268    d[k] = '\0';
4269    return k;
4270 }
4271
4272 public char * OffsetEscapedString(char * s, int len, int offset)
4273 {
4274    char ch;
4275    int j = 0, k = 0;
4276    while(j < len && k < offset && (ch = s[j]))
4277    {
4278       if(ch == '\\') ++j;
4279       j++, k++;
4280    }
4281    return (k == offset) ? s + j : null;
4282 }
4283
4284 public Operand GetOperand(Expression exp)
4285 {
4286    Operand op { };
4287    Type type = exp.expType;
4288    if(type)
4289    {
4290       while(type.kind == classType &&
4291          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4292       {
4293          if(!type._class.registered.dataType)
4294             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4295          type = type._class.registered.dataType;
4296
4297       }
4298       if(exp.type == stringExp && op.kind == pointerType)
4299       {
4300          op.ui64 = (uint64)exp.string;
4301          op.kind = pointerType;
4302          op.ops = uint64Ops;
4303       }
4304       else if(exp.isConstant && exp.type == constantExp)
4305       {
4306          op.kind = type.kind;
4307          op.type = exp.expType;
4308
4309          switch(op.kind)
4310          {
4311             case _BoolType:
4312             case charType:
4313             {
4314                if(exp.constant[0] == '\'')
4315                {
4316                   op.c = exp.constant[1];
4317                   op.ops = charOps;
4318                }
4319                else if(type.isSigned)
4320                {
4321                   op.c = (char)strtol(exp.constant, null, 0);
4322                   op.ops = charOps;
4323                }
4324                else
4325                {
4326                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4327                   op.ops = ucharOps;
4328                }
4329                break;
4330             }
4331             case shortType:
4332                if(type.isSigned)
4333                {
4334                   op.s = (short)strtol(exp.constant, null, 0);
4335                   op.ops = shortOps;
4336                }
4337                else
4338                {
4339                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4340                   op.ops = ushortOps;
4341                }
4342                break;
4343             case intType:
4344             case longType:
4345                if(type.isSigned)
4346                {
4347                   op.i = (int)strtol(exp.constant, null, 0);
4348                   op.ops = intOps;
4349                }
4350                else
4351                {
4352                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4353                   op.ops = uintOps;
4354                }
4355                op.kind = intType;
4356                break;
4357             case int64Type:
4358                if(type.isSigned)
4359                {
4360                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4361                   op.ops = int64Ops;
4362                }
4363                else
4364                {
4365                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4366                   op.ops = uint64Ops;
4367                }
4368                op.kind = int64Type;
4369                break;
4370             case intPtrType:
4371                if(type.isSigned)
4372                {
4373                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4374                   op.ops = int64Ops;
4375                }
4376                else
4377                {
4378                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4379                   op.ops = uint64Ops;
4380                }
4381                op.kind = int64Type;
4382                break;
4383             case intSizeType:
4384                if(type.isSigned)
4385                {
4386                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4387                   op.ops = int64Ops;
4388                }
4389                else
4390                {
4391                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4392                   op.ops = uint64Ops;
4393                }
4394                op.kind = int64Type;
4395                break;
4396             case floatType:
4397                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4398                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4399                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4400                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4401                else
4402                   op.f = (float)strtod(exp.constant, null);
4403                op.ops = floatOps;
4404                break;
4405             case doubleType:
4406                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4407                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4408                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4409                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4410                else
4411                   op.d = (double)strtod(exp.constant, null);
4412                op.ops = doubleOps;
4413                break;
4414             //case classType:    For when we have operator overloading...
4415             // Pointer additions
4416             //case functionType:
4417             case arrayType:
4418             case pointerType:
4419             case classType:
4420                op.ui64 = _strtoui64(exp.constant, null, 0);
4421                op.kind = pointerType;
4422                op.ops = uint64Ops;
4423                // op.ptrSize =
4424                break;
4425          }
4426       }
4427    }
4428    return op;
4429 }
4430
4431 static void UnusedFunction()
4432 {
4433    int a;
4434    a.OnGetString(0,0,0);
4435 }
4436 default:
4437 extern int __ecereVMethodID_class_OnGetString;
4438 public:
4439
4440 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4441 {
4442    DataMember dataMember;
4443    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4444    {
4445       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4446          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4447       else
4448       {
4449          Expression exp { };
4450          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4451          Type type;
4452          void * ptr = inst.data + dataMember.offset + offset;
4453          char * result = null;
4454          exp.loc = member.loc = inst.loc;
4455          ((Identifier)member.identifiers->first).loc = inst.loc;
4456
4457          if(!dataMember.dataType)
4458             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4459          type = dataMember.dataType;
4460          if(type.kind == classType)
4461          {
4462             Class _class = type._class.registered;
4463             if(_class.type == enumClass)
4464             {
4465                Class enumClass = eSystem_FindClass(privateModule, "enum");
4466                if(enumClass)
4467                {
4468                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4469                   NamedLink item;
4470                   for(item = e.values.first; item; item = item.next)
4471                   {
4472                      if((int)item.data == *(int *)ptr)
4473                      {
4474                         result = item.name;
4475                         break;
4476                      }
4477                   }
4478                   if(result)
4479                   {
4480                      exp.identifier = MkIdentifier(result);
4481                      exp.type = identifierExp;
4482                      exp.destType = MkClassType(_class.fullName);
4483                      ProcessExpressionType(exp);
4484                   }
4485                }
4486             }
4487             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4488             {
4489                if(!_class.dataType)
4490                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4491                type = _class.dataType;
4492             }
4493          }
4494          if(!result)
4495          {
4496             switch(type.kind)
4497             {
4498                case floatType:
4499                {
4500                   FreeExpContents(exp);
4501
4502                   exp.constant = PrintFloat(*(float*)ptr);
4503                   exp.type = constantExp;
4504                   break;
4505                }
4506                case doubleType:
4507                {
4508                   FreeExpContents(exp);
4509
4510                   exp.constant = PrintDouble(*(double*)ptr);
4511                   exp.type = constantExp;
4512                   break;
4513                }
4514                case intType:
4515                {
4516                   FreeExpContents(exp);
4517
4518                   exp.constant = PrintInt(*(int*)ptr);
4519                   exp.type = constantExp;
4520                   break;
4521                }
4522                case int64Type:
4523                {
4524                   FreeExpContents(exp);
4525
4526                   exp.constant = PrintInt64(*(int64*)ptr);
4527                   exp.type = constantExp;
4528                   break;
4529                }
4530                case intPtrType:
4531                {
4532                   FreeExpContents(exp);
4533                   // TODO: This should probably use proper type
4534                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4535                   exp.type = constantExp;
4536                   break;
4537                }
4538                case intSizeType:
4539                {
4540                   FreeExpContents(exp);
4541                   // TODO: This should probably use proper type
4542                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4543                   exp.type = constantExp;
4544                   break;
4545                }
4546                default:
4547                   Compiler_Error($"Unhandled type populating instance\n");
4548             }
4549          }
4550          ListAdd(memberList, member);
4551       }
4552
4553       if(parentDataMember.type == unionMember)
4554          break;
4555    }
4556 }
4557
4558 void PopulateInstance(Instantiation inst)
4559 {
4560    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4561    Class _class = classSym.registered;
4562    DataMember dataMember;
4563    OldList * memberList = MkList();
4564    // Added this check and ->Add to prevent memory leaks on bad code
4565    if(!inst.members)
4566       inst.members = MkListOne(MkMembersInitList(memberList));
4567    else
4568       inst.members->Add(MkMembersInitList(memberList));
4569    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4570    {
4571       if(!dataMember.isProperty)
4572       {
4573          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4574             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4575          else
4576          {
4577             Expression exp { };
4578             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4579             Type type;
4580             void * ptr = inst.data + dataMember.offset;
4581             char * result = null;
4582
4583             exp.loc = member.loc = inst.loc;
4584             ((Identifier)member.identifiers->first).loc = inst.loc;
4585
4586             if(!dataMember.dataType)
4587                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4588             type = dataMember.dataType;
4589             if(type.kind == classType)
4590             {
4591                Class _class = type._class.registered;
4592                if(_class.type == enumClass)
4593                {
4594                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4595                   if(enumClass)
4596                   {
4597                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4598                      NamedLink item;
4599                      for(item = e.values.first; item; item = item.next)
4600                      {
4601                         if((int)item.data == *(int *)ptr)
4602                         {
4603                            result = item.name;
4604                            break;
4605                         }
4606                      }
4607                   }
4608                   if(result)
4609                   {
4610                      exp.identifier = MkIdentifier(result);
4611                      exp.type = identifierExp;
4612                      exp.destType = MkClassType(_class.fullName);
4613                      ProcessExpressionType(exp);
4614                   }
4615                }
4616                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4617                {
4618                   if(!_class.dataType)
4619                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4620                   type = _class.dataType;
4621                }
4622             }
4623             if(!result)
4624             {
4625                switch(type.kind)
4626                {
4627                   case floatType:
4628                   {
4629                      exp.constant = PrintFloat(*(float*)ptr);
4630                      exp.type = constantExp;
4631                      break;
4632                   }
4633                   case doubleType:
4634                   {
4635                      exp.constant = PrintDouble(*(double*)ptr);
4636                      exp.type = constantExp;
4637                      break;
4638                   }
4639                   case intType:
4640                   {
4641                      exp.constant = PrintInt(*(int*)ptr);
4642                      exp.type = constantExp;
4643                      break;
4644                   }
4645                   case int64Type:
4646                   {
4647                      exp.constant = PrintInt64(*(int64*)ptr);
4648                      exp.type = constantExp;
4649                      break;
4650                   }
4651                   case intPtrType:
4652                   {
4653                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4654                      exp.type = constantExp;
4655                      break;
4656                   }
4657                   default:
4658                      Compiler_Error($"Unhandled type populating instance\n");
4659                }
4660             }
4661             ListAdd(memberList, member);
4662          }
4663       }
4664    }
4665 }
4666
4667 void ComputeInstantiation(Expression exp)
4668 {
4669    Instantiation inst = exp.instance;
4670    MembersInit members;
4671    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4672    Class _class = classSym ? classSym.registered : null;
4673    DataMember curMember = null;
4674    Class curClass = null;
4675    DataMember subMemberStack[256];
4676    int subMemberStackPos = 0;
4677    uint64 bits = 0;
4678
4679    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4680    {
4681       // Don't recompute the instantiation...
4682       // Non Simple classes will have become constants by now
4683       if(inst.data)
4684          return;
4685
4686       if(_class.type == normalClass || _class.type == noHeadClass)
4687       {
4688          inst.data = (byte *)eInstance_New(_class);
4689          if(_class.type == normalClass)
4690             ((Instance)inst.data)._refCount++;
4691       }
4692       else
4693          inst.data = new0 byte[_class.structSize];
4694    }
4695
4696    if(inst.members)
4697    {
4698       for(members = inst.members->first; members; members = members.next)
4699       {
4700          switch(members.type)
4701          {
4702             case dataMembersInit:
4703             {
4704                if(members.dataMembers)
4705                {
4706                   MemberInit member;
4707                   for(member = members.dataMembers->first; member; member = member.next)
4708                   {
4709                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4710                      bool found = false;
4711
4712                      Property prop = null;
4713                      DataMember dataMember = null;
4714                      Method method = null;
4715                      uint dataMemberOffset;
4716
4717                      if(!ident)
4718                      {
4719                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4720                         if(curMember)
4721                         {
4722                            if(curMember.isProperty)
4723                               prop = (Property)curMember;
4724                            else
4725                            {
4726                               dataMember = curMember;
4727
4728                               // CHANGED THIS HERE
4729                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4730
4731                               // 2013/17/29 -- It seems that this was missing here!
4732                               if(_class.type == normalClass)
4733                                  dataMemberOffset += _class.base.structSize;
4734                               // dataMemberOffset = dataMember.offset;
4735                            }
4736                            found = true;
4737                         }
4738                      }
4739                      else
4740                      {
4741                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4742                         if(prop)
4743                         {
4744                            found = true;
4745                            if(prop.memberAccess == publicAccess)
4746                            {
4747                               curMember = (DataMember)prop;
4748                               curClass = prop._class;
4749                            }
4750                         }
4751                         else
4752                         {
4753                            DataMember _subMemberStack[256];
4754                            int _subMemberStackPos = 0;
4755
4756                            // FILL MEMBER STACK
4757                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4758
4759                            if(dataMember)
4760                            {
4761                               found = true;
4762                               if(dataMember.memberAccess == publicAccess)
4763                               {
4764                                  curMember = dataMember;
4765                                  curClass = dataMember._class;
4766                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
4767                                  subMemberStackPos = _subMemberStackPos;
4768                               }
4769                            }
4770                         }
4771                      }
4772
4773                      if(found && member.initializer && member.initializer.type == expInitializer)
4774                      {
4775                         Expression value = member.initializer.exp;
4776                         Type type = null;
4777                         bool deepMember = false;
4778                         if(prop)
4779                         {
4780                            type = prop.dataType;
4781                         }
4782                         else if(dataMember)
4783                         {
4784                            if(!dataMember.dataType)
4785                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4786
4787                            type = dataMember.dataType;
4788                         }
4789
4790                         if(ident && ident.next)
4791                         {
4792                            deepMember = true;
4793
4794                            // for(; ident && type; ident = ident.next)
4795                            for(ident = ident.next; ident && type; ident = ident.next)
4796                            {
4797                               if(type.kind == classType)
4798                               {
4799                                  prop = eClass_FindProperty(type._class.registered,
4800                                     ident.string, privateModule);
4801                                  if(prop)
4802                                     type = prop.dataType;
4803                                  else
4804                                  {
4805                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
4806                                        ident.string, &dataMemberOffset, privateModule, null, null);
4807                                     if(dataMember)
4808                                        type = dataMember.dataType;
4809                                  }
4810                               }
4811                               else if(type.kind == structType || type.kind == unionType)
4812                               {
4813                                  Type memberType;
4814                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
4815                                  {
4816                                     if(!strcmp(memberType.name, ident.string))
4817                                     {
4818                                        type = memberType;
4819                                        break;
4820                                     }
4821                                  }
4822                               }
4823                            }
4824                         }
4825                         if(value)
4826                         {
4827                            FreeType(value.destType);
4828                            value.destType = type;
4829                            if(type) type.refCount++;
4830                            ComputeExpression(value);
4831                         }
4832                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
4833                         {
4834                            if(type.kind == classType)
4835                            {
4836                               Class _class = type._class.registered;
4837                               if(_class.type == bitClass || _class.type == unitClass ||
4838                                  _class.type == enumClass)
4839                               {
4840                                  if(!_class.dataType)
4841                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4842                                  type = _class.dataType;
4843                               }
4844                            }
4845
4846                            if(dataMember)
4847                            {
4848                               void * ptr = inst.data + dataMemberOffset;
4849
4850                               if(value.type == constantExp)
4851                               {
4852                                  switch(type.kind)
4853                                  {
4854                                     case intType:
4855                                     {
4856                                        GetInt(value, (int*)ptr);
4857                                        break;
4858                                     }
4859                                     case int64Type:
4860                                     {
4861                                        GetInt64(value, (int64*)ptr);
4862                                        break;
4863                                     }
4864                                     case intPtrType:
4865                                     {
4866                                        GetIntPtr(value, (intptr*)ptr);
4867                                        break;
4868                                     }
4869                                     case intSizeType:
4870                                     {
4871                                        GetIntSize(value, (intsize*)ptr);
4872                                        break;
4873                                     }
4874                                     case floatType:
4875                                     {
4876                                        GetFloat(value, (float*)ptr);
4877                                        break;
4878                                     }
4879                                     case doubleType:
4880                                     {
4881                                        GetDouble(value, (double *)ptr);
4882                                        break;
4883                                     }
4884                                  }
4885                               }
4886                               else if(value.type == instanceExp)
4887                               {
4888                                  if(type.kind == classType)
4889                                  {
4890                                     Class _class = type._class.registered;
4891                                     if(_class.type == structClass)
4892                                     {
4893                                        ComputeTypeSize(type);
4894                                        if(value.instance.data)
4895                                           memcpy(ptr, value.instance.data, type.size);
4896                                     }
4897                                  }
4898                               }
4899                            }
4900                            else if(prop)
4901                            {
4902                               if(value.type == instanceExp && value.instance.data)
4903                               {
4904                                  if(type.kind == classType)
4905                                  {
4906                                     Class _class = type._class.registered;
4907                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
4908                                     {
4909                                        void (*Set)(void *, void *) = (void *)prop.Set;
4910                                        Set(inst.data, value.instance.data);
4911                                        PopulateInstance(inst);
4912                                     }
4913                                  }
4914                               }
4915                               else if(value.type == constantExp)
4916                               {
4917                                  switch(type.kind)
4918                                  {
4919                                     case doubleType:
4920                                     {
4921                                        void (*Set)(void *, double) = (void *)prop.Set;
4922                                        Set(inst.data, strtod(value.constant, null) );
4923                                        break;
4924                                     }
4925                                     case floatType:
4926                                     {
4927                                        void (*Set)(void *, float) = (void *)prop.Set;
4928                                        Set(inst.data, (float)(strtod(value.constant, null)));
4929                                        break;
4930                                     }
4931                                     case intType:
4932                                     {
4933                                        void (*Set)(void *, int) = (void *)prop.Set;
4934                                        Set(inst.data, (int)strtol(value.constant, null, 0));
4935                                        break;
4936                                     }
4937                                     case int64Type:
4938                                     {
4939                                        void (*Set)(void *, int64) = (void *)prop.Set;
4940                                        Set(inst.data, _strtoi64(value.constant, null, 0));
4941                                        break;
4942                                     }
4943                                     case intPtrType:
4944                                     {
4945                                        void (*Set)(void *, intptr) = (void *)prop.Set;
4946                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
4947                                        break;
4948                                     }
4949                                     case intSizeType:
4950                                     {
4951                                        void (*Set)(void *, intsize) = (void *)prop.Set;
4952                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
4953                                        break;
4954                                     }
4955                                  }
4956                               }
4957                               else if(value.type == stringExp)
4958                               {
4959                                  char temp[1024];
4960                                  ReadString(temp, value.string);
4961                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
4962                               }
4963                            }
4964                         }
4965                         else if(!deepMember && type && _class.type == unitClass)
4966                         {
4967                            if(prop)
4968                            {
4969                               // Only support converting units to units for now...
4970                               if(value.type == constantExp)
4971                               {
4972                                  if(type.kind == classType)
4973                                  {
4974                                     Class _class = type._class.registered;
4975                                     if(_class.type == unitClass)
4976                                     {
4977                                        if(!_class.dataType)
4978                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4979                                        type = _class.dataType;
4980                                     }
4981                                  }
4982                                  // TODO: Assuming same base type for units...
4983                                  switch(type.kind)
4984                                  {
4985                                     case floatType:
4986                                     {
4987                                        float fValue;
4988                                        float (*Set)(float) = (void *)prop.Set;
4989                                        GetFloat(member.initializer.exp, &fValue);
4990                                        exp.constant = PrintFloat(Set(fValue));
4991                                        exp.type = constantExp;
4992                                        break;
4993                                     }
4994                                     case doubleType:
4995                                     {
4996                                        double dValue;
4997                                        double (*Set)(double) = (void *)prop.Set;
4998                                        GetDouble(member.initializer.exp, &dValue);
4999                                        exp.constant = PrintDouble(Set(dValue));
5000                                        exp.type = constantExp;
5001                                        break;
5002                                     }
5003                                  }
5004                               }
5005                            }
5006                         }
5007                         else if(!deepMember && type && _class.type == bitClass)
5008                         {
5009                            if(prop)
5010                            {
5011                               if(value.type == instanceExp && value.instance.data)
5012                               {
5013                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5014                                  bits = Set(value.instance.data);
5015                               }
5016                               else if(value.type == constantExp)
5017                               {
5018                               }
5019                            }
5020                            else if(dataMember)
5021                            {
5022                               BitMember bitMember = (BitMember) dataMember;
5023                               Type type;
5024                               uint64 part;
5025                               bits = (bits & ~bitMember.mask);
5026                               if(!bitMember.dataType)
5027                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5028                               type = bitMember.dataType;
5029                               if(type.kind == classType && type._class && type._class.registered)
5030                               {
5031                                  if(!type._class.registered.dataType)
5032                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5033                                  type = type._class.registered.dataType;
5034                               }
5035                               switch(type.kind)
5036                               {
5037                                  case _BoolType:
5038                                  case charType:       { byte v; type.isSigned ? GetChar(value, &v) : GetUChar(value, &v); part = (uint64)v; break; }
5039                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, &v) : GetUShort(value, &v); part = (uint64)v; break; }
5040                                  case intType:
5041                                  case longType:       { uint v; type.isSigned ? GetInt(value, &v) : GetUInt(value, &v); part = (uint64)v; break; }
5042                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, &v) : GetUInt64(value, &v); part = (uint64)v; break; }
5043                                  case intPtrType:     { intptr v; type.isSigned ? GetIntPtr(value, &v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5044                                  case intSizeType:    { intsize v; type.isSigned ? GetIntSize(value, &v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5045                               }
5046                               bits += part << bitMember.pos;
5047                            }
5048                         }
5049                      }
5050                      else
5051                      {
5052                         if(_class && _class.type == unitClass)
5053                         {
5054                            ComputeExpression(member.initializer.exp);
5055                            exp.constant = member.initializer.exp.constant;
5056                            exp.type = constantExp;
5057
5058                            member.initializer.exp.constant = null;
5059                         }
5060                      }
5061                   }
5062                }
5063                break;
5064             }
5065          }
5066       }
5067    }
5068    if(_class && _class.type == bitClass)
5069    {
5070       exp.constant = PrintHexUInt(bits);
5071       exp.type = constantExp;
5072    }
5073    if(exp.type != instanceExp)
5074    {
5075       FreeInstance(inst);
5076    }
5077 }
5078
5079 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5080 {
5081    bool result = false;
5082    switch(kind)
5083    {
5084       case shortType:
5085          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5086             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5087          break;
5088       case intType:
5089       case longType:
5090          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5091             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5092          break;
5093       case int64Type:
5094          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5095             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5096             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5097          break;
5098       case floatType:
5099          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5100             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5101             result = GetOpFloat(op, &op.f);
5102          break;
5103       case doubleType:
5104          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5105             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5106             result = GetOpDouble(op, &op.d);
5107          break;
5108       case pointerType:
5109          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5110             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5111             result = GetOpUIntPtr(op, &op.ui64);
5112          break;
5113       case enumType:
5114          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5115             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5116             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5117          break;
5118       case intPtrType:
5119          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5120             result = isSigned ? GetOpIntPtr(op, &op.i64) : GetOpUIntPtr(op, &op.i64);
5121          break;
5122       case intSizeType:
5123          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5124             result = isSigned ? GetOpIntSize(op, &op.ui64) : GetOpUIntSize(op, &op.ui64);
5125          break;
5126    }
5127    return result;
5128 }
5129
5130 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5131 {
5132    if(exp.op.op == SIZEOF)
5133    {
5134       FreeExpContents(exp);
5135       exp.type = constantExp;
5136       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5137    }
5138    else
5139    {
5140       if(!exp.op.exp1)
5141       {
5142          switch(exp.op.op)
5143          {
5144             // unary arithmetic
5145             case '+':
5146             {
5147                // Provide default unary +
5148                Expression exp2 = exp.op.exp2;
5149                exp.op.exp2 = null;
5150                FreeExpContents(exp);
5151                FreeType(exp.expType);
5152                FreeType(exp.destType);
5153                *exp = *exp2;
5154                delete exp2;
5155                break;
5156             }
5157             case '-':
5158                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5159                break;
5160             // unary arithmetic increment and decrement
5161                   //OPERATOR_ALL(UNARY, ++, Inc)
5162                   //OPERATOR_ALL(UNARY, --, Dec)
5163             // unary bitwise
5164             case '~':
5165                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5166                break;
5167             // unary logical negation
5168             case '!':
5169                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5170                break;
5171          }
5172       }
5173       else
5174       {
5175          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5176          {
5177             if(Promote(op2, op1.kind, op1.type.isSigned))
5178                op2.kind = op1.kind, op2.ops = op1.ops;
5179             else if(Promote(op1, op2.kind, op2.type.isSigned))
5180                op1.kind = op2.kind, op1.ops = op2.ops;
5181          }
5182          switch(exp.op.op)
5183          {
5184             // binary arithmetic
5185             case '+':
5186                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5187                break;
5188             case '-':
5189                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5190                break;
5191             case '*':
5192                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5193                break;
5194             case '/':
5195                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5196                break;
5197             case '%':
5198                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5199                break;
5200             // binary arithmetic assignment
5201                   //OPERATOR_ALL(BINARY, =, Asign)
5202                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5203                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5204                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5205                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5206                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5207             // binary bitwise
5208             case '&':
5209                if(exp.op.exp2)
5210                {
5211                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5212                }
5213                break;
5214             case '|':
5215                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5216                break;
5217             case '^':
5218                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5219                break;
5220             case LEFT_OP:
5221                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5222                break;
5223             case RIGHT_OP:
5224                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5225                break;
5226             // binary bitwise assignment
5227                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5228                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5229                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5230                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5231                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5232             // binary logical equality
5233             case EQ_OP:
5234                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5235                break;
5236             case NE_OP:
5237                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5238                break;
5239             // binary logical
5240             case AND_OP:
5241                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5242                break;
5243             case OR_OP:
5244                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5245                break;
5246             // binary logical relational
5247             case '>':
5248                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5249                break;
5250             case '<':
5251                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5252                break;
5253             case GE_OP:
5254                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5255                break;
5256             case LE_OP:
5257                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5258                break;
5259          }
5260       }
5261    }
5262 }
5263
5264 void ComputeExpression(Expression exp)
5265 {
5266    char expString[10240];
5267    expString[0] = '\0';
5268 #ifdef _DEBUG
5269    PrintExpression(exp, expString);
5270 #endif
5271
5272    switch(exp.type)
5273    {
5274       case instanceExp:
5275       {
5276          ComputeInstantiation(exp);
5277          break;
5278       }
5279       /*
5280       case constantExp:
5281          break;
5282       */
5283       case opExp:
5284       {
5285          Expression exp1, exp2 = null;
5286          Operand op1 { };
5287          Operand op2 { };
5288
5289          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5290          if(exp.op.exp2)
5291          {
5292             Expression e = exp.op.exp2;
5293
5294             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5295             {
5296                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5297                {
5298                   if(e.type == extensionCompoundExp)
5299                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5300                   else
5301                      e = e.list->last;
5302                }
5303             }
5304             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5305             {
5306                if(e.type == stringExp && e.string)
5307                {
5308                   char * string = e.string;
5309                   int len = strlen(string);
5310                   char * tmp = new char[len-2+1];
5311                   len = UnescapeString(tmp, string + 1, len - 2);
5312                   delete tmp;
5313                   FreeExpContents(exp);
5314                   exp.type = constantExp;
5315                   exp.constant = PrintUInt(len + 1);
5316                }
5317                else
5318                {
5319                   Type type = e.expType;
5320                   type.refCount++;
5321                   FreeExpContents(exp);
5322                   exp.type = constantExp;
5323                   exp.constant = PrintUInt(ComputeTypeSize(type));
5324                   FreeType(type);
5325                }
5326                break;
5327             }
5328             else
5329                ComputeExpression(exp.op.exp2);
5330          }
5331          if(exp.op.exp1)
5332          {
5333             ComputeExpression(exp.op.exp1);
5334             exp1 = exp.op.exp1;
5335             exp2 = exp.op.exp2;
5336             op1 = GetOperand(exp1);
5337             if(op1.type) op1.type.refCount++;
5338             if(exp2)
5339             {
5340                op2 = GetOperand(exp2);
5341                if(op2.type) op2.type.refCount++;
5342             }
5343          }
5344          else
5345          {
5346             exp1 = exp.op.exp2;
5347             op1 = GetOperand(exp1);
5348             if(op1.type) op1.type.refCount++;
5349          }
5350
5351          CallOperator(exp, exp1, exp2, op1, op2);
5352          /*
5353          switch(exp.op.op)
5354          {
5355             // Unary operators
5356             case '&':
5357                // Also binary
5358                if(exp.op.exp1 && exp.op.exp2)
5359                {
5360                   // Binary And
5361                   if(op1.ops.BitAnd)
5362                   {
5363                      FreeExpContents(exp);
5364                      op1.ops.BitAnd(exp, op1, op2);
5365                   }
5366                }
5367                break;
5368             case '*':
5369                if(exp.op.exp1)
5370                {
5371                   if(op1.ops.Mul)
5372                   {
5373                      FreeExpContents(exp);
5374                      op1.ops.Mul(exp, op1, op2);
5375                   }
5376                }
5377                break;
5378             case '+':
5379                if(exp.op.exp1)
5380                {
5381                   if(op1.ops.Add)
5382                   {
5383                      FreeExpContents(exp);
5384                      op1.ops.Add(exp, op1, op2);
5385                   }
5386                }
5387                else
5388                {
5389                   // Provide default unary +
5390                   Expression exp2 = exp.op.exp2;
5391                   exp.op.exp2 = null;
5392                   FreeExpContents(exp);
5393                   FreeType(exp.expType);
5394                   FreeType(exp.destType);
5395
5396                   *exp = *exp2;
5397                   delete exp2;
5398                }
5399                break;
5400             case '-':
5401                if(exp.op.exp1)
5402                {
5403                   if(op1.ops.Sub)
5404                   {
5405                      FreeExpContents(exp);
5406                      op1.ops.Sub(exp, op1, op2);
5407                   }
5408                }
5409                else
5410                {
5411                   if(op1.ops.Neg)
5412                   {
5413                      FreeExpContents(exp);
5414                      op1.ops.Neg(exp, op1);
5415                   }
5416                }
5417                break;
5418             case '~':
5419                if(op1.ops.BitNot)
5420                {
5421                   FreeExpContents(exp);
5422                   op1.ops.BitNot(exp, op1);
5423                }
5424                break;
5425             case '!':
5426                if(op1.ops.Not)
5427                {
5428                   FreeExpContents(exp);
5429                   op1.ops.Not(exp, op1);
5430                }
5431                break;
5432             // Binary only operators
5433             case '/':
5434                if(op1.ops.Div)
5435                {
5436                   FreeExpContents(exp);
5437                   op1.ops.Div(exp, op1, op2);
5438                }
5439                break;
5440             case '%':
5441                if(op1.ops.Mod)
5442                {
5443                   FreeExpContents(exp);
5444                   op1.ops.Mod(exp, op1, op2);
5445                }
5446                break;
5447             case LEFT_OP:
5448                break;
5449             case RIGHT_OP:
5450                break;
5451             case '<':
5452                if(exp.op.exp1)
5453                {
5454                   if(op1.ops.Sma)
5455                   {
5456                      FreeExpContents(exp);
5457                      op1.ops.Sma(exp, op1, op2);
5458                   }
5459                }
5460                break;
5461             case '>':
5462                if(exp.op.exp1)
5463                {
5464                   if(op1.ops.Grt)
5465                   {
5466                      FreeExpContents(exp);
5467                      op1.ops.Grt(exp, op1, op2);
5468                   }
5469                }
5470                break;
5471             case LE_OP:
5472                if(exp.op.exp1)
5473                {
5474                   if(op1.ops.SmaEqu)
5475                   {
5476                      FreeExpContents(exp);
5477                      op1.ops.SmaEqu(exp, op1, op2);
5478                   }
5479                }
5480                break;
5481             case GE_OP:
5482                if(exp.op.exp1)
5483                {
5484                   if(op1.ops.GrtEqu)
5485                   {
5486                      FreeExpContents(exp);
5487                      op1.ops.GrtEqu(exp, op1, op2);
5488                   }
5489                }
5490                break;
5491             case EQ_OP:
5492                if(exp.op.exp1)
5493                {
5494                   if(op1.ops.Equ)
5495                   {
5496                      FreeExpContents(exp);
5497                      op1.ops.Equ(exp, op1, op2);
5498                   }
5499                }
5500                break;
5501             case NE_OP:
5502                if(exp.op.exp1)
5503                {
5504                   if(op1.ops.Nqu)
5505                   {
5506                      FreeExpContents(exp);
5507                      op1.ops.Nqu(exp, op1, op2);
5508                   }
5509                }
5510                break;
5511             case '|':
5512                if(op1.ops.BitOr)
5513                {
5514                   FreeExpContents(exp);
5515                   op1.ops.BitOr(exp, op1, op2);
5516                }
5517                break;
5518             case '^':
5519                if(op1.ops.BitXor)
5520                {
5521                   FreeExpContents(exp);
5522                   op1.ops.BitXor(exp, op1, op2);
5523                }
5524                break;
5525             case AND_OP:
5526                break;
5527             case OR_OP:
5528                break;
5529             case SIZEOF:
5530                FreeExpContents(exp);
5531                exp.type = constantExp;
5532                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5533                break;
5534          }
5535          */
5536          if(op1.type) FreeType(op1.type);
5537          if(op2.type) FreeType(op2.type);
5538          break;
5539       }
5540       case bracketsExp:
5541       case extensionExpressionExp:
5542       {
5543          Expression e, n;
5544          for(e = exp.list->first; e; e = n)
5545          {
5546             n = e.next;
5547             if(!n)
5548             {
5549                OldList * list = exp.list;
5550                ComputeExpression(e);
5551                //FreeExpContents(exp);
5552                FreeType(exp.expType);
5553                FreeType(exp.destType);
5554                *exp = *e;
5555                delete e;
5556                delete list;
5557             }
5558             else
5559             {
5560                FreeExpression(e);
5561             }
5562          }
5563          break;
5564       }
5565       /*
5566
5567       case ExpIndex:
5568       {
5569          Expression e;
5570          exp.isConstant = true;
5571
5572          ComputeExpression(exp.index.exp);
5573          if(!exp.index.exp.isConstant)
5574             exp.isConstant = false;
5575
5576          for(e = exp.index.index->first; e; e = e.next)
5577          {
5578             ComputeExpression(e);
5579             if(!e.next)
5580             {
5581                // Check if this type is int
5582             }
5583             if(!e.isConstant)
5584                exp.isConstant = false;
5585          }
5586          exp.expType = Dereference(exp.index.exp.expType);
5587          break;
5588       }
5589       */
5590       case memberExp:
5591       {
5592          Expression memberExp = exp.member.exp;
5593          Identifier memberID = exp.member.member;
5594
5595          Type type;
5596          ComputeExpression(exp.member.exp);
5597          type = exp.member.exp.expType;
5598          if(type)
5599          {
5600             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);
5601             Property prop = null;
5602             DataMember member = null;
5603             Class convertTo = null;
5604             if(type.kind == subClassType && exp.member.exp.type == classExp)
5605                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5606
5607             if(!_class)
5608             {
5609                char string[256];
5610                Symbol classSym;
5611                string[0] = '\0';
5612                PrintTypeNoConst(type, string, false, true);
5613                classSym = FindClass(string);
5614                _class = classSym ? classSym.registered : null;
5615             }
5616
5617             if(exp.member.member)
5618             {
5619                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5620                if(!prop)
5621                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5622             }
5623             if(!prop && !member && _class && exp.member.member)
5624             {
5625                Symbol classSym = FindClass(exp.member.member.string);
5626                convertTo = _class;
5627                _class = classSym ? classSym.registered : null;
5628                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5629             }
5630
5631             if(prop)
5632             {
5633                if(prop.compiled)
5634                {
5635                   Type type = prop.dataType;
5636                   // TODO: Assuming same base type for units...
5637                   if(_class.type == unitClass)
5638                   {
5639                      if(type.kind == classType)
5640                      {
5641                         Class _class = type._class.registered;
5642                         if(_class.type == unitClass)
5643                         {
5644                            if(!_class.dataType)
5645                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5646                            type = _class.dataType;
5647                         }
5648                      }
5649                      switch(type.kind)
5650                      {
5651                         case floatType:
5652                         {
5653                            float value;
5654                            float (*Get)(float) = (void *)prop.Get;
5655                            GetFloat(exp.member.exp, &value);
5656                            exp.constant = PrintFloat(Get ? Get(value) : value);
5657                            exp.type = constantExp;
5658                            break;
5659                         }
5660                         case doubleType:
5661                         {
5662                            double value;
5663                            double (*Get)(double);
5664                            GetDouble(exp.member.exp, &value);
5665
5666                            if(convertTo)
5667                               Get = (void *)prop.Set;
5668                            else
5669                               Get = (void *)prop.Get;
5670                            exp.constant = PrintDouble(Get ? Get(value) : value);
5671                            exp.type = constantExp;
5672                            break;
5673                         }
5674                      }
5675                   }
5676                   else
5677                   {
5678                      if(convertTo)
5679                      {
5680                         Expression value = exp.member.exp;
5681                         Type type;
5682                         if(!prop.dataType)
5683                            ProcessPropertyType(prop);
5684
5685                         type = prop.dataType;
5686                         if(!type)
5687                         {
5688                             // printf("Investigate this\n");
5689                         }
5690                         else if(_class.type == structClass)
5691                         {
5692                            switch(type.kind)
5693                            {
5694                               case classType:
5695                               {
5696                                  Class propertyClass = type._class.registered;
5697                                  if(propertyClass.type == structClass && value.type == instanceExp)
5698                                  {
5699                                     void (*Set)(void *, void *) = (void *)prop.Set;
5700                                     exp.instance = Instantiation { };
5701                                     exp.instance.data = new0 byte[_class.structSize];
5702                                     exp.instance._class = MkSpecifierName(_class.fullName);
5703                                     exp.instance.loc = exp.loc;
5704                                     exp.type = instanceExp;
5705                                     Set(exp.instance.data, value.instance.data);
5706                                     PopulateInstance(exp.instance);
5707                                  }
5708                                  break;
5709                               }
5710                               case intType:
5711                               {
5712                                  int intValue;
5713                                  void (*Set)(void *, int) = (void *)prop.Set;
5714
5715                                  exp.instance = Instantiation { };
5716                                  exp.instance.data = new0 byte[_class.structSize];
5717                                  exp.instance._class = MkSpecifierName(_class.fullName);
5718                                  exp.instance.loc = exp.loc;
5719                                  exp.type = instanceExp;
5720
5721                                  GetInt(value, &intValue);
5722
5723                                  Set(exp.instance.data, intValue);
5724                                  PopulateInstance(exp.instance);
5725                                  break;
5726                               }
5727                               case int64Type:
5728                               {
5729                                  int64 intValue;
5730                                  void (*Set)(void *, int64) = (void *)prop.Set;
5731
5732                                  exp.instance = Instantiation { };
5733                                  exp.instance.data = new0 byte[_class.structSize];
5734                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5735                                  exp.instance.loc = exp.loc;
5736                                  exp.type = instanceExp;
5737
5738                                  GetInt64(value, &intValue);
5739
5740                                  Set(exp.instance.data, intValue);
5741                                  PopulateInstance(exp.instance);
5742                                  break;
5743                               }
5744                               case intPtrType:
5745                               {
5746                                  // TOFIX:
5747                                  intptr intValue;
5748                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5749
5750                                  exp.instance = Instantiation { };
5751                                  exp.instance.data = new0 byte[_class.structSize];
5752                                  exp.instance._class = MkSpecifierName(_class.fullName);
5753                                  exp.instance.loc = exp.loc;
5754                                  exp.type = instanceExp;
5755
5756                                  GetIntPtr(value, &intValue);
5757
5758                                  Set(exp.instance.data, intValue);
5759                                  PopulateInstance(exp.instance);
5760                                  break;
5761                               }
5762                               case intSizeType:
5763                               {
5764                                  // TOFIX:
5765                                  intsize intValue;
5766                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5767
5768                                  exp.instance = Instantiation { };
5769                                  exp.instance.data = new0 byte[_class.structSize];
5770                                  exp.instance._class = MkSpecifierName(_class.fullName);
5771                                  exp.instance.loc = exp.loc;
5772                                  exp.type = instanceExp;
5773
5774                                  GetIntSize(value, &intValue);
5775
5776                                  Set(exp.instance.data, intValue);
5777                                  PopulateInstance(exp.instance);
5778                                  break;
5779                               }
5780                               case floatType:
5781                               {
5782                                  float floatValue;
5783                                  void (*Set)(void *, float) = (void *)prop.Set;
5784
5785                                  exp.instance = Instantiation { };
5786                                  exp.instance.data = new0 byte[_class.structSize];
5787                                  exp.instance._class = MkSpecifierName(_class.fullName);
5788                                  exp.instance.loc = exp.loc;
5789                                  exp.type = instanceExp;
5790
5791                                  GetFloat(value, &floatValue);
5792
5793                                  Set(exp.instance.data, floatValue);
5794                                  PopulateInstance(exp.instance);
5795                                  break;
5796                               }
5797                               case doubleType:
5798                               {
5799                                  double doubleValue;
5800                                  void (*Set)(void *, double) = (void *)prop.Set;
5801
5802                                  exp.instance = Instantiation { };
5803                                  exp.instance.data = new0 byte[_class.structSize];
5804                                  exp.instance._class = MkSpecifierName(_class.fullName);
5805                                  exp.instance.loc = exp.loc;
5806                                  exp.type = instanceExp;
5807
5808                                  GetDouble(value, &doubleValue);
5809
5810                                  Set(exp.instance.data, doubleValue);
5811                                  PopulateInstance(exp.instance);
5812                                  break;
5813                               }
5814                            }
5815                         }
5816                         else if(_class.type == bitClass)
5817                         {
5818                            switch(type.kind)
5819                            {
5820                               case classType:
5821                               {
5822                                  Class propertyClass = type._class.registered;
5823                                  if(propertyClass.type == structClass && value.instance.data)
5824                                  {
5825                                     unsigned int (*Set)(void *) = (void *)prop.Set;
5826                                     unsigned int bits = Set(value.instance.data);
5827                                     exp.constant = PrintHexUInt(bits);
5828                                     exp.type = constantExp;
5829                                     break;
5830                                  }
5831                                  else if(_class.type == bitClass)
5832                                  {
5833                                     unsigned int value;
5834                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
5835                                     unsigned int bits;
5836
5837                                     GetUInt(exp.member.exp, &value);
5838                                     bits = Set(value);
5839                                     exp.constant = PrintHexUInt(bits);
5840                                     exp.type = constantExp;
5841                                  }
5842                               }
5843                            }
5844                         }
5845                      }
5846                      else
5847                      {
5848                         if(_class.type == bitClass)
5849                         {
5850                            unsigned int value;
5851                            GetUInt(exp.member.exp, &value);
5852
5853                            switch(type.kind)
5854                            {
5855                               case classType:
5856                               {
5857                                  Class _class = type._class.registered;
5858                                  if(_class.type == structClass)
5859                                  {
5860                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
5861
5862                                     exp.instance = Instantiation { };
5863                                     exp.instance.data = new0 byte[_class.structSize];
5864                                     exp.instance._class = MkSpecifierName(_class.fullName);
5865                                     exp.instance.loc = exp.loc;
5866                                     //exp.instance.fullSet = true;
5867                                     exp.type = instanceExp;
5868                                     Get(value, exp.instance.data);
5869                                     PopulateInstance(exp.instance);
5870                                  }
5871                                  else if(_class.type == bitClass)
5872                                  {
5873                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
5874                                     uint64 bits = Get(value);
5875                                     exp.constant = PrintHexUInt64(bits);
5876                                     exp.type = constantExp;
5877                                  }
5878                                  break;
5879                               }
5880                            }
5881                         }
5882                         else if(_class.type == structClass)
5883                         {
5884                            char * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
5885                            switch(type.kind)
5886                            {
5887                               case classType:
5888                               {
5889                                  Class _class = type._class.registered;
5890                                  if(_class.type == structClass && value)
5891                                  {
5892                                     void (*Get)(void *, void *) = (void *)prop.Get;
5893
5894                                     exp.instance = Instantiation { };
5895                                     exp.instance.data = new0 byte[_class.structSize];
5896                                     exp.instance._class = MkSpecifierName(_class.fullName);
5897                                     exp.instance.loc = exp.loc;
5898                                     //exp.instance.fullSet = true;
5899                                     exp.type = instanceExp;
5900                                     Get(value, exp.instance.data);
5901                                     PopulateInstance(exp.instance);
5902                                  }
5903                                  break;
5904                               }
5905                            }
5906                         }
5907                         /*else
5908                         {
5909                            char * value = exp.member.exp.instance.data;
5910                            switch(type.kind)
5911                            {
5912                               case classType:
5913                               {
5914                                  Class _class = type._class.registered;
5915                                  if(_class.type == normalClass)
5916                                  {
5917                                     void *(*Get)(void *) = (void *)prop.Get;
5918
5919                                     exp.instance = Instantiation { };
5920                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
5921                                     exp.type = instanceExp;
5922                                     exp.instance.data = Get(value, exp.instance.data);
5923                                  }
5924                                  break;
5925                               }
5926                            }
5927                         }
5928                         */
5929                      }
5930                   }
5931                }
5932                else
5933                {
5934                   exp.isConstant = false;
5935                }
5936             }
5937             else if(member)
5938             {
5939             }
5940          }
5941
5942          if(exp.type != ExpressionType::memberExp)
5943          {
5944             FreeExpression(memberExp);
5945             FreeIdentifier(memberID);
5946          }
5947          break;
5948       }
5949       case typeSizeExp:
5950       {
5951          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
5952          FreeExpContents(exp);
5953          exp.constant = PrintUInt(ComputeTypeSize(type));
5954          exp.type = constantExp;
5955          FreeType(type);
5956          break;
5957       }
5958       case classSizeExp:
5959       {
5960          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
5961          if(classSym && classSym.registered)
5962          {
5963             if(classSym.registered.fixed)
5964             {
5965                FreeSpecifier(exp._class);
5966                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
5967                exp.type = constantExp;
5968             }
5969             else
5970             {
5971                char className[1024];
5972                strcpy(className, "__ecereClass_");
5973                FullClassNameCat(className, classSym.string, true);
5974                MangleClassName(className);
5975
5976                DeclareClass(classSym, className);
5977
5978                FreeExpContents(exp);
5979                exp.type = pointerExp;
5980                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
5981                exp.member.member = MkIdentifier("structSize");
5982             }
5983          }
5984          break;
5985       }
5986       case castExp:
5987       //case constantExp:
5988       {
5989          Type type;
5990          Expression e = exp;
5991          if(exp.type == castExp)
5992          {
5993             if(exp.cast.exp)
5994                ComputeExpression(exp.cast.exp);
5995             e = exp.cast.exp;
5996          }
5997          if(e && exp.expType)
5998          {
5999             /*if(exp.destType)
6000                type = exp.destType;
6001             else*/
6002                type = exp.expType;
6003             if(type.kind == classType)
6004             {
6005                Class _class = type._class.registered;
6006                if(_class && (_class.type == unitClass || _class.type == bitClass))
6007                {
6008                   if(!_class.dataType)
6009                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6010                   type = _class.dataType;
6011                }
6012             }
6013
6014             switch(type.kind)
6015             {
6016                case _BoolType:
6017                case charType:
6018                   if(type.isSigned)
6019                   {
6020                      char value = 0;
6021                      if(GetChar(e, &value))
6022                      {
6023                         FreeExpContents(exp);
6024                         exp.constant = PrintChar(value);
6025                         exp.type = constantExp;
6026                      }
6027                   }
6028                   else
6029                   {
6030                      unsigned char value = 0;
6031                      if(GetUChar(e, &value))
6032                      {
6033                         FreeExpContents(exp);
6034                         exp.constant = PrintUChar(value);
6035                         exp.type = constantExp;
6036                      }
6037                   }
6038                   break;
6039                case shortType:
6040                   if(type.isSigned)
6041                   {
6042                      short value = 0;
6043                      if(GetShort(e, &value))
6044                      {
6045                         FreeExpContents(exp);
6046                         exp.constant = PrintShort(value);
6047                         exp.type = constantExp;
6048                      }
6049                   }
6050                   else
6051                   {
6052                      unsigned short value = 0;
6053                      if(GetUShort(e, &value))
6054                      {
6055                         FreeExpContents(exp);
6056                         exp.constant = PrintUShort(value);
6057                         exp.type = constantExp;
6058                      }
6059                   }
6060                   break;
6061                case intType:
6062                   if(type.isSigned)
6063                   {
6064                      int value = 0;
6065                      if(GetInt(e, &value))
6066                      {
6067                         FreeExpContents(exp);
6068                         exp.constant = PrintInt(value);
6069                         exp.type = constantExp;
6070                      }
6071                   }
6072                   else
6073                   {
6074                      unsigned int value = 0;
6075                      if(GetUInt(e, &value))
6076                      {
6077                         FreeExpContents(exp);
6078                         exp.constant = PrintUInt(value);
6079                         exp.type = constantExp;
6080                      }
6081                   }
6082                   break;
6083                case int64Type:
6084                   if(type.isSigned)
6085                   {
6086                      int64 value = 0;
6087                      if(GetInt64(e, &value))
6088                      {
6089                         FreeExpContents(exp);
6090                         exp.constant = PrintInt64(value);
6091                         exp.type = constantExp;
6092                      }
6093                   }
6094                   else
6095                   {
6096                      uint64 value = 0;
6097                      if(GetUInt64(e, &value))
6098                      {
6099                         FreeExpContents(exp);
6100                         exp.constant = PrintUInt64(value);
6101                         exp.type = constantExp;
6102                      }
6103                   }
6104                   break;
6105                case intPtrType:
6106                   if(type.isSigned)
6107                   {
6108                      intptr value = 0;
6109                      if(GetIntPtr(e, &value))
6110                      {
6111                         FreeExpContents(exp);
6112                         exp.constant = PrintInt64((int64)value);
6113                         exp.type = constantExp;
6114                      }
6115                   }
6116                   else
6117                   {
6118                      uintptr value = 0;
6119                      if(GetUIntPtr(e, &value))
6120                      {
6121                         FreeExpContents(exp);
6122                         exp.constant = PrintUInt64((uint64)value);
6123                         exp.type = constantExp;
6124                      }
6125                   }
6126                   break;
6127                case intSizeType:
6128                   if(type.isSigned)
6129                   {
6130                      intsize value = 0;
6131                      if(GetIntSize(e, &value))
6132                      {
6133                         FreeExpContents(exp);
6134                         exp.constant = PrintInt64((int64)value);
6135                         exp.type = constantExp;
6136                      }
6137                   }
6138                   else
6139                   {
6140                      uintsize value = 0;
6141                      if(GetUIntSize(e, &value))
6142                      {
6143                         FreeExpContents(exp);
6144                         exp.constant = PrintUInt64((uint64)value);
6145                         exp.type = constantExp;
6146                      }
6147                   }
6148                   break;
6149                case floatType:
6150                {
6151                   float value = 0;
6152                   if(GetFloat(e, &value))
6153                   {
6154                      FreeExpContents(exp);
6155                      exp.constant = PrintFloat(value);
6156                      exp.type = constantExp;
6157                   }
6158                   break;
6159                }
6160                case doubleType:
6161                {
6162                   double value = 0;
6163                   if(GetDouble(e, &value))
6164                   {
6165                      FreeExpContents(exp);
6166                      exp.constant = PrintDouble(value);
6167                      exp.type = constantExp;
6168                   }
6169                   break;
6170                }
6171             }
6172          }
6173          break;
6174       }
6175       case conditionExp:
6176       {
6177          Operand op1 { };
6178          Operand op2 { };
6179          Operand op3 { };
6180
6181          if(exp.cond.exp)
6182             // Caring only about last expression for now...
6183             ComputeExpression(exp.cond.exp->last);
6184          if(exp.cond.elseExp)
6185             ComputeExpression(exp.cond.elseExp);
6186          if(exp.cond.cond)
6187             ComputeExpression(exp.cond.cond);
6188
6189          op1 = GetOperand(exp.cond.cond);
6190          if(op1.type) op1.type.refCount++;
6191          op2 = GetOperand(exp.cond.exp->last);
6192          if(op2.type) op2.type.refCount++;
6193          op3 = GetOperand(exp.cond.elseExp);
6194          if(op3.type) op3.type.refCount++;
6195
6196          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6197          if(op1.type) FreeType(op1.type);
6198          if(op2.type) FreeType(op2.type);
6199          if(op3.type) FreeType(op3.type);
6200          break;
6201       }
6202    }
6203 }
6204
6205 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla)
6206 {
6207    bool result = true;
6208    if(destType)
6209    {
6210       OldList converts { };
6211       Conversion convert;
6212
6213       if(destType.kind == voidType)
6214          return false;
6215
6216       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla))
6217          result = false;
6218       if(converts.count)
6219       {
6220          // for(convert = converts.last; convert; convert = convert.prev)
6221          for(convert = converts.first; convert; convert = convert.next)
6222          {
6223             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6224             if(!empty)
6225             {
6226                Expression newExp { };
6227                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6228
6229                // TODO: Check this...
6230                *newExp = *exp;
6231                newExp.destType = null;
6232
6233                if(convert.isGet)
6234                {
6235                   // [exp].ColorRGB
6236                   exp.type = memberExp;
6237                   exp.addedThis = true;
6238                   exp.member.exp = newExp;
6239                   FreeType(exp.member.exp.expType);
6240
6241                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6242                   exp.member.exp.expType.classObjectType = objectType;
6243                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6244                   exp.member.memberType = propertyMember;
6245                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6246                   // TESTING THIS... for (int)degrees
6247                   exp.needCast = true;
6248                   if(exp.expType) exp.expType.refCount++;
6249                   ApplyAnyObjectLogic(exp.member.exp);
6250                }
6251                else
6252                {
6253
6254                   /*if(exp.isConstant)
6255                   {
6256                      // Color { ColorRGB = [exp] };
6257                      exp.type = instanceExp;
6258                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6259                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6260                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6261                   }
6262                   else*/
6263                   {
6264                      // If not constant, don't turn it yet into an instantiation
6265                      // (Go through the deep members system first)
6266                      exp.type = memberExp;
6267                      exp.addedThis = true;
6268                      exp.member.exp = newExp;
6269
6270                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6271                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6272                         newExp.expType._class.registered.type == noHeadClass)
6273                      {
6274                         newExp.byReference = true;
6275                      }
6276
6277                      FreeType(exp.member.exp.expType);
6278                      /*exp.member.exp.expType = convert.convert.dataType;
6279                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6280                      exp.member.exp.expType = null;
6281                      if(convert.convert.dataType)
6282                      {
6283                         exp.member.exp.expType = { };
6284                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6285                         exp.member.exp.expType.refCount = 1;
6286                         exp.member.exp.expType.classObjectType = objectType;
6287                         ApplyAnyObjectLogic(exp.member.exp);
6288                      }
6289
6290                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6291                      exp.member.memberType = reverseConversionMember;
6292                      exp.expType = convert.resultType ? convert.resultType :
6293                         MkClassType(convert.convert._class.fullName);
6294                      exp.needCast = true;
6295                      if(convert.resultType) convert.resultType.refCount++;
6296                   }
6297                }
6298             }
6299             else
6300             {
6301                FreeType(exp.expType);
6302                if(convert.isGet)
6303                {
6304                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6305                   exp.needCast = true;
6306                   if(exp.expType) exp.expType.refCount++;
6307                }
6308                else
6309                {
6310                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6311                   exp.needCast = true;
6312                   if(convert.resultType)
6313                      convert.resultType.refCount++;
6314                }
6315             }
6316          }
6317          if(exp.isConstant && inCompiler)
6318             ComputeExpression(exp);
6319
6320          converts.Free(FreeConvert);
6321       }
6322
6323       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6324       {
6325          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false);
6326       }
6327       if(!result && exp.expType && exp.destType)
6328       {
6329          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6330              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6331             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6332             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6333             result = true;
6334       }
6335    }
6336    // if(result) CheckTemplateTypes(exp);
6337    return result;
6338 }
6339
6340 void CheckTemplateTypes(Expression exp)
6341 {
6342    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate)
6343    {
6344       Expression newExp { };
6345       Statement compound;
6346       Context context;
6347       *newExp = *exp;
6348       if(exp.destType) exp.destType.refCount++;
6349       if(exp.expType)  exp.expType.refCount++;
6350       newExp.prev = null;
6351       newExp.next = null;
6352
6353       switch(exp.expType.kind)
6354       {
6355          case doubleType:
6356             if(exp.destType.classObjectType)
6357             {
6358                // We need to pass the address, just pass it along (Undo what was done above)
6359                if(exp.destType) exp.destType.refCount--;
6360                if(exp.expType)  exp.expType.refCount--;
6361                delete newExp;
6362             }
6363             else
6364             {
6365                // If we're looking for value:
6366                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6367                OldList * specs;
6368                OldList * unionDefs = MkList();
6369                OldList * statements = MkList();
6370                context = PushContext();
6371                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6372                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6373                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6374                exp.type = extensionCompoundExp;
6375                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6376                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6377                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6378                exp.compound.compound.context = context;
6379                PopContext(context);
6380             }
6381             break;
6382          default:
6383             exp.type = castExp;
6384             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6385             exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6386             break;
6387       }
6388    }
6389    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6390    {
6391       Expression newExp { };
6392       Statement compound;
6393       Context context;
6394       *newExp = *exp;
6395       if(exp.destType) exp.destType.refCount++;
6396       if(exp.expType)  exp.expType.refCount++;
6397       newExp.prev = null;
6398       newExp.next = null;
6399
6400       switch(exp.expType.kind)
6401       {
6402          case doubleType:
6403             if(exp.destType.classObjectType)
6404             {
6405                // We need to pass the address, just pass it along (Undo what was done above)
6406                if(exp.destType) exp.destType.refCount--;
6407                if(exp.expType)  exp.expType.refCount--;
6408                delete newExp;
6409             }
6410             else
6411             {
6412                // If we're looking for value:
6413                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6414                OldList * specs;
6415                OldList * unionDefs = MkList();
6416                OldList * statements = MkList();
6417                context = PushContext();
6418                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6419                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6420                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6421                exp.type = extensionCompoundExp;
6422                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6423                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6424                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6425                exp.compound.compound.context = context;
6426                PopContext(context);
6427             }
6428             break;
6429          case classType:
6430          {
6431             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6432             {
6433                exp.type = bracketsExp;
6434                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6435                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6436                ProcessExpressionType(exp.list->first);
6437                break;
6438             }
6439             else
6440             {
6441                exp.type = bracketsExp;
6442                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6443                newExp.needCast = true;
6444                ProcessExpressionType(exp.list->first);
6445                break;
6446             }
6447          }
6448          default:
6449          {
6450             if(exp.expType.kind == templateType)
6451             {
6452                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6453                if(type)
6454                {
6455                   FreeType(exp.destType);
6456                   FreeType(exp.expType);
6457                   delete newExp;
6458                   break;
6459                }
6460             }
6461             if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6462             {
6463                exp.type = opExp;
6464                exp.op.op = '*';
6465                exp.op.exp1 = null;
6466                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6467                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6468             }
6469             else
6470             {
6471                char typeString[1024];
6472                Declarator decl;
6473                OldList * specs = MkList();
6474                typeString[0] = '\0';
6475                PrintType(exp.expType, typeString, false, false);
6476                decl = SpecDeclFromString(typeString, specs, null);
6477
6478                exp.type = castExp;
6479                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6480                exp.cast.typeName = MkTypeName(specs, decl);
6481                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6482                exp.cast.exp.needCast = true;
6483             }
6484             break;
6485          }
6486       }
6487    }
6488 }
6489 // TODO: The Symbol tree should be reorganized by namespaces
6490 // Name Space:
6491 //    - Tree of all symbols within (stored without namespace)
6492 //    - Tree of sub-namespaces
6493
6494 static Symbol ScanWithNameSpace(BinaryTree tree, char * nameSpace, char * name)
6495 {
6496    int nsLen = strlen(nameSpace);
6497    Symbol symbol;
6498    // Start at the name space prefix
6499    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6500    {
6501       char * s = symbol.string;
6502       if(!strncmp(s, nameSpace, nsLen))
6503       {
6504          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6505          int c;
6506          char * namePart;
6507          for(c = strlen(s)-1; c >= 0; c--)
6508             if(s[c] == ':')
6509                break;
6510
6511          namePart = s+c+1;
6512          if(!strcmp(namePart, name))
6513          {
6514             // TODO: Error on ambiguity
6515             return symbol;
6516          }
6517       }
6518       else
6519          break;
6520    }
6521    return null;
6522 }
6523
6524 static Symbol FindWithNameSpace(BinaryTree tree, char * name)
6525 {
6526    int c;
6527    char nameSpace[1024];
6528    char * namePart;
6529    bool gotColon = false;
6530
6531    nameSpace[0] = '\0';
6532    for(c = strlen(name)-1; c >= 0; c--)
6533       if(name[c] == ':')
6534       {
6535          gotColon = true;
6536          break;
6537       }
6538
6539    namePart = name+c+1;
6540    while(c >= 0 && name[c] == ':') c--;
6541    if(c >= 0)
6542    {
6543       // Try an exact match first
6544       Symbol symbol = (Symbol)tree.FindString(name);
6545       if(symbol)
6546          return symbol;
6547
6548       // Namespace specified
6549       memcpy(nameSpace, name, c + 1);
6550       nameSpace[c+1] = 0;
6551
6552       return ScanWithNameSpace(tree, nameSpace, namePart);
6553    }
6554    else if(gotColon)
6555    {
6556       // Looking for a global symbol, e.g. ::Sleep()
6557       Symbol symbol = (Symbol)tree.FindString(namePart);
6558       return symbol;
6559    }
6560    else
6561    {
6562       // Name only (no namespace specified)
6563       Symbol symbol = (Symbol)tree.FindString(namePart);
6564       if(symbol)
6565          return symbol;
6566       return ScanWithNameSpace(tree, "", namePart);
6567    }
6568    return null;
6569 }
6570
6571 static void ProcessDeclaration(Declaration decl);
6572
6573 /*static */Symbol FindSymbol(char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6574 {
6575 #ifdef _DEBUG
6576    //Time startTime = GetTime();
6577 #endif
6578    // Optimize this later? Do this before/less?
6579    Context ctx;
6580    Symbol symbol = null;
6581    // First, check if the identifier is declared inside the function
6582    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6583
6584    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6585    {
6586       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6587       {
6588          symbol = null;
6589          if(thisNameSpace)
6590          {
6591             char curName[1024];
6592             strcpy(curName, thisNameSpace);
6593             strcat(curName, "::");
6594             strcat(curName, name);
6595             // Try to resolve in current namespace first
6596             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6597          }
6598          if(!symbol)
6599             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6600       }
6601       else
6602          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6603
6604       if(symbol || ctx == endContext) break;
6605    }
6606    if(inCompiler && curExternal && symbol && ctx == globalContext && curExternal.symbol && symbol.id > curExternal.symbol.idCode && symbol.pointerExternal)
6607    {
6608       if(symbol.pointerExternal.type == functionExternal)
6609       {
6610          FunctionDefinition function = symbol.pointerExternal.function;
6611
6612          // Modified this recently...
6613          Context tmpContext = curContext;
6614          curContext = null;
6615          symbol.pointerExternal = MkExternalDeclaration(MkDeclaration(CopyList(function.specifiers, CopySpecifier), MkListOne(MkInitDeclarator(CopyDeclarator(function.declarator), null))));
6616          curContext = tmpContext;
6617
6618          symbol.pointerExternal.symbol = symbol;
6619
6620          // TESTING THIS:
6621          DeclareType(symbol.type, true, true);
6622
6623          ast->Insert(curExternal.prev, symbol.pointerExternal);
6624
6625          symbol.id = curExternal.symbol.idCode;
6626
6627       }
6628       else if(symbol.pointerExternal.type == declarationExternal && curExternal.symbol.idCode < symbol.pointerExternal.symbol.id) // Added id comparison because Global Function prototypes were broken
6629       {
6630          ast->Move(symbol.pointerExternal, curExternal.prev);
6631          symbol.id = curExternal.symbol.idCode;
6632       }
6633    }
6634 #ifdef _DEBUG
6635    //findSymbolTotalTime += GetTime() - startTime;
6636 #endif
6637    return symbol;
6638 }
6639
6640 static void GetTypeSpecs(Type type, OldList * specs)
6641 {
6642    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6643    switch(type.kind)
6644    {
6645       case classType:
6646       {
6647          if(type._class.registered)
6648          {
6649             if(!type._class.registered.dataType)
6650                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6651             GetTypeSpecs(type._class.registered.dataType, specs);
6652          }
6653          break;
6654       }
6655       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6656       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6657       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6658       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6659       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6660       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6661       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6662       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6663       case intType:
6664       default:
6665          ListAdd(specs, MkSpecifier(INT)); break;
6666    }
6667 }
6668
6669 static void PrintArraySize(Type arrayType, char * string)
6670 {
6671    char size[256];
6672    size[0] = '\0';
6673    strcat(size, "[");
6674    if(arrayType.enumClass)
6675       strcat(size, arrayType.enumClass.string);
6676    else if(arrayType.arraySizeExp)
6677       PrintExpression(arrayType.arraySizeExp, size);
6678    strcat(size, "]");
6679    strcat(string, size);
6680 }
6681
6682 // WARNING : This function expects a null terminated string since it recursively concatenate...
6683 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6684 {
6685    if(type)
6686    {
6687       if(printConst && type.constant)
6688          strcat(string, "const ");
6689       switch(type.kind)
6690       {
6691          case classType:
6692          {
6693             Symbol c = type._class;
6694             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6695             //       look into merging with thisclass ?
6696             if(type.classObjectType == typedObject)
6697                strcat(string, "typed_object");
6698             else if(type.classObjectType == anyObject)
6699                strcat(string, "any_object");
6700             else
6701             {
6702                if(c && c.string)
6703                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6704             }
6705             if(type.byReference)
6706                strcat(string, " &");
6707             break;
6708          }
6709          case voidType: strcat(string, "void"); break;
6710          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6711          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6712          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6713          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6714          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6715          case _BoolType: strcat(string, "_Bool"); break;
6716          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6717          case floatType: strcat(string, "float"); break;
6718          case doubleType: strcat(string, "double"); break;
6719          case structType:
6720             if(type.enumName)
6721             {
6722                strcat(string, "struct ");
6723                strcat(string, type.enumName);
6724             }
6725             else if(type.typeName)
6726                strcat(string, type.typeName);
6727             else
6728             {
6729                Type member;
6730                strcat(string, "struct { ");
6731                for(member = type.members.first; member; member = member.next)
6732                {
6733                   PrintType(member, string, true, fullName);
6734                   strcat(string,"; ");
6735                }
6736                strcat(string,"}");
6737             }
6738             break;
6739          case unionType:
6740             if(type.enumName)
6741             {
6742                strcat(string, "union ");
6743                strcat(string, type.enumName);
6744             }
6745             else if(type.typeName)
6746                strcat(string, type.typeName);
6747             else
6748             {
6749                strcat(string, "union ");
6750                strcat(string,"(unnamed)");
6751             }
6752             break;
6753          case enumType:
6754             if(type.enumName)
6755             {
6756                strcat(string, "enum ");
6757                strcat(string, type.enumName);
6758             }
6759             else if(type.typeName)
6760                strcat(string, type.typeName);
6761             else
6762                strcat(string, "int"); // "enum");
6763             break;
6764          case ellipsisType:
6765             strcat(string, "...");
6766             break;
6767          case subClassType:
6768             strcat(string, "subclass(");
6769             strcat(string, type._class ? type._class.string : "int");
6770             strcat(string, ")");
6771             break;
6772          case templateType:
6773             strcat(string, type.templateParameter.identifier.string);
6774             break;
6775          case thisClassType:
6776             strcat(string, "thisclass");
6777             break;
6778          case vaListType:
6779             strcat(string, "__builtin_va_list");
6780             break;
6781       }
6782    }
6783 }
6784
6785 static void PrintName(Type type, char * string, bool fullName)
6786 {
6787    if(type.name && type.name[0])
6788    {
6789       if(fullName)
6790          strcat(string, type.name);
6791       else
6792       {
6793          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
6794          if(name) name += 2; else name = type.name;
6795          strcat(string, name);
6796       }
6797    }
6798 }
6799
6800 static void PrintAttribs(Type type, char * string)
6801 {
6802    if(type)
6803    {
6804       if(type.dllExport)   strcat(string, "dllexport ");
6805       if(type.attrStdcall) strcat(string, "stdcall ");
6806    }
6807 }
6808
6809 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
6810 {
6811    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
6812    {
6813       Type attrType = null;
6814       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
6815          PrintAttribs(type, string);
6816       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
6817          strcat(string, " const");
6818       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
6819       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
6820          strcat(string, " (");
6821       if(type.kind == pointerType)
6822       {
6823          if(type.type.kind == functionType || type.type.kind == methodType)
6824             PrintAttribs(type.type, string);
6825       }
6826       if(type.kind == pointerType)
6827       {
6828          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
6829             strcat(string, "*");
6830          else
6831             strcat(string, " *");
6832       }
6833       if(printConst && type.constant && type.kind == pointerType)
6834          strcat(string, " const");
6835    }
6836    else
6837       PrintTypeSpecs(type, string, fullName, printConst);
6838 }
6839
6840 static void PostPrintType(Type type, char * string, bool fullName)
6841 {
6842    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
6843       strcat(string, ")");
6844    if(type.kind == arrayType)
6845       PrintArraySize(type, string);
6846    else if(type.kind == functionType)
6847    {
6848       Type param;
6849       strcat(string, "(");
6850       for(param = type.params.first; param; param = param.next)
6851       {
6852          PrintType(param, string, true, fullName);
6853          if(param.next) strcat(string, ", ");
6854       }
6855       strcat(string, ")");
6856    }
6857    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
6858       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
6859 }
6860
6861 // *****
6862 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
6863 // *****
6864 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
6865 {
6866    PrePrintType(type, string, fullName, null, printConst);
6867
6868    if(type.thisClass || (printName && type.name && type.name[0]))
6869       strcat(string, " ");
6870    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
6871    {
6872       Symbol _class = type.thisClass;
6873       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
6874       {
6875          if(type.classObjectType == classPointer)
6876             strcat(string, "class");
6877          else
6878             strcat(string, type.byReference ? "typed_object&" : "typed_object");
6879       }
6880       else if(_class && _class.string)
6881       {
6882          String s = _class.string;
6883          if(fullName)
6884             strcat(string, s);
6885          else
6886          {
6887             char * name = RSearchString(s, "::", strlen(s), true, false);
6888             if(name) name += 2; else name = s;
6889             strcat(string, name);
6890          }
6891       }
6892       strcat(string, "::");
6893    }
6894
6895    if(printName && type.name)
6896       PrintName(type, string, fullName);
6897    PostPrintType(type, string, fullName);
6898    if(type.bitFieldCount)
6899    {
6900       char count[100];
6901       sprintf(count, ":%d", type.bitFieldCount);
6902       strcat(string, count);
6903    }
6904 }
6905
6906 void PrintType(Type type, char * string, bool printName, bool fullName)
6907 {
6908    _PrintType(type, string, printName, fullName, true);
6909 }
6910
6911 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
6912 {
6913    _PrintType(type, string, printName, fullName, false);
6914 }
6915
6916 static Type FindMember(Type type, char * string)
6917 {
6918    Type memberType;
6919    for(memberType = type.members.first; memberType; memberType = memberType.next)
6920    {
6921       if(!memberType.name)
6922       {
6923          Type subType = FindMember(memberType, string);
6924          if(subType)
6925             return subType;
6926       }
6927       else if(!strcmp(memberType.name, string))
6928          return memberType;
6929    }
6930    return null;
6931 }
6932
6933 Type FindMemberAndOffset(Type type, char * string, uint * offset)
6934 {
6935    Type memberType;
6936    for(memberType = type.members.first; memberType; memberType = memberType.next)
6937    {
6938       if(!memberType.name)
6939       {
6940          Type subType = FindMember(memberType, string);
6941          if(subType)
6942          {
6943             *offset += memberType.offset;
6944             return subType;
6945          }
6946       }
6947       else if(!strcmp(memberType.name, string))
6948       {
6949          *offset += memberType.offset;
6950          return memberType;
6951       }
6952    }
6953    return null;
6954 }
6955
6956 public bool GetParseError() { return parseError; }
6957
6958 Expression ParseExpressionString(char * expression)
6959 {
6960    parseError = false;
6961
6962    fileInput = TempFile { };
6963    fileInput.Write(expression, 1, strlen(expression));
6964    fileInput.Seek(0, start);
6965
6966    echoOn = false;
6967    parsedExpression = null;
6968    resetScanner();
6969    expression_yyparse();
6970    delete fileInput;
6971
6972    return parsedExpression;
6973 }
6974
6975 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
6976 {
6977    Identifier id = exp.identifier;
6978    Method method = null;
6979    Property prop = null;
6980    DataMember member = null;
6981    ClassProperty classProp = null;
6982
6983    if(_class && _class.type == enumClass)
6984    {
6985       NamedLink value = null;
6986       Class enumClass = eSystem_FindClass(privateModule, "enum");
6987       if(enumClass)
6988       {
6989          Class baseClass;
6990          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
6991          {
6992             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
6993             for(value = e.values.first; value; value = value.next)
6994             {
6995                if(!strcmp(value.name, id.string))
6996                   break;
6997             }
6998             if(value)
6999             {
7000                char constant[256];
7001
7002                FreeExpContents(exp);
7003
7004                exp.type = constantExp;
7005                exp.isConstant = true;
7006                if(!strcmp(baseClass.dataTypeString, "int"))
7007                   sprintf(constant, "%d",(int)value.data);
7008                else
7009                   sprintf(constant, "0x%X",(int)value.data);
7010                exp.constant = CopyString(constant);
7011                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7012                exp.expType = MkClassType(baseClass.fullName);
7013                break;
7014             }
7015          }
7016       }
7017       if(value)
7018          return true;
7019    }
7020    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7021    {
7022       ProcessMethodType(method);
7023       exp.expType = Type
7024       {
7025          refCount = 1;
7026          kind = methodType;
7027          method = method;
7028          // Crash here?
7029          // TOCHECK: Put it back to what it was...
7030          // methodClass = _class;
7031          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7032       };
7033       //id._class = null;
7034       return true;
7035    }
7036    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7037    {
7038       if(!prop.dataType)
7039          ProcessPropertyType(prop);
7040       exp.expType = prop.dataType;
7041       if(prop.dataType) prop.dataType.refCount++;
7042       return true;
7043    }
7044    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7045    {
7046       if(!member.dataType)
7047          member.dataType = ProcessTypeString(member.dataTypeString, false);
7048       exp.expType = member.dataType;
7049       if(member.dataType) member.dataType.refCount++;
7050       return true;
7051    }
7052    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7053    {
7054       if(!classProp.dataType)
7055          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7056
7057       if(classProp.constant)
7058       {
7059          FreeExpContents(exp);
7060
7061          exp.isConstant = true;
7062          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7063          {
7064             //char constant[256];
7065             exp.type = stringExp;
7066             exp.constant = QMkString((char *)classProp.Get(_class));
7067          }
7068          else
7069          {
7070             char constant[256];
7071             exp.type = constantExp;
7072             sprintf(constant, "%d", (int)classProp.Get(_class));
7073             exp.constant = CopyString(constant);
7074          }
7075       }
7076       else
7077       {
7078          // TO IMPLEMENT...
7079       }
7080
7081       exp.expType = classProp.dataType;
7082       if(classProp.dataType) classProp.dataType.refCount++;
7083       return true;
7084    }
7085    return false;
7086 }
7087
7088 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7089 {
7090    BinaryTree * tree = &nameSpace.functions;
7091    GlobalData data = (GlobalData)tree->FindString(name);
7092    NameSpace * child;
7093    if(!data)
7094    {
7095       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7096       {
7097          data = ScanGlobalData(child, name);
7098          if(data)
7099             break;
7100       }
7101    }
7102    return data;
7103 }
7104
7105 static GlobalData FindGlobalData(char * name)
7106 {
7107    int start = 0, c;
7108    NameSpace * nameSpace;
7109    nameSpace = globalData;
7110    for(c = 0; name[c]; c++)
7111    {
7112       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7113       {
7114          NameSpace * newSpace;
7115          char * spaceName = new char[c - start + 1];
7116          strncpy(spaceName, name + start, c - start);
7117          spaceName[c-start] = '\0';
7118          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7119          delete spaceName;
7120          if(!newSpace)
7121             return null;
7122          nameSpace = newSpace;
7123          if(name[c] == ':') c++;
7124          start = c+1;
7125       }
7126    }
7127    if(c - start)
7128    {
7129       return ScanGlobalData(nameSpace, name + start);
7130    }
7131    return null;
7132 }
7133
7134 static int definedExpStackPos;
7135 static void * definedExpStack[512];
7136
7137 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7138 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7139 {
7140    Expression prev = checkedExp.prev, next = checkedExp.next;
7141
7142    FreeExpContents(checkedExp);
7143    FreeType(checkedExp.expType);
7144    FreeType(checkedExp.destType);
7145
7146    *checkedExp = *newExp;
7147
7148    delete newExp;
7149
7150    checkedExp.prev = prev;
7151    checkedExp.next = next;
7152 }
7153
7154 void ApplyAnyObjectLogic(Expression e)
7155 {
7156    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7157 #ifdef _DEBUG
7158    char debugExpString[4096];
7159    debugExpString[0] = '\0';
7160    PrintExpression(e, debugExpString);
7161 #endif
7162
7163    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7164    {
7165       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7166       //ellipsisDestType = destType;
7167       if(e && e.expType)
7168       {
7169          Type type = e.expType;
7170          Class _class = null;
7171          //Type destType = e.destType;
7172
7173          if(type.kind == classType && type._class && type._class.registered)
7174          {
7175             _class = type._class.registered;
7176          }
7177          else if(type.kind == subClassType)
7178          {
7179             _class = FindClass("ecere::com::Class").registered;
7180          }
7181          else
7182          {
7183             char string[1024] = "";
7184             Symbol classSym;
7185
7186             PrintTypeNoConst(type, string, false, true);
7187             classSym = FindClass(string);
7188             if(classSym) _class = classSym.registered;
7189          }
7190
7191          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...
7192             (!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))) ||
7193             destType.byReference)))
7194          {
7195             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7196             {
7197                Expression checkedExp = e, newExp;
7198
7199                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7200                {
7201                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7202                   {
7203                      if(checkedExp.type == extensionCompoundExp)
7204                      {
7205                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7206                      }
7207                      else
7208                         checkedExp = checkedExp.list->last;
7209                   }
7210                   else if(checkedExp.type == castExp)
7211                      checkedExp = checkedExp.cast.exp;
7212                }
7213
7214                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7215                {
7216                   newExp = checkedExp.op.exp2;
7217                   checkedExp.op.exp2 = null;
7218                   FreeExpContents(checkedExp);
7219
7220                   if(e.expType && e.expType.passAsTemplate)
7221                   {
7222                      char size[100];
7223                      ComputeTypeSize(e.expType);
7224                      sprintf(size, "%d", e.expType.size);
7225                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7226                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7227                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7228                   }
7229
7230                   ReplaceExpContents(checkedExp, newExp);
7231                   e.byReference = true;
7232                }
7233                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7234                {
7235                   Expression checkedExp, newExp;
7236
7237                   {
7238                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7239                      bool hasAddress =
7240                         e.type == identifierExp ||
7241                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7242                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7243                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7244                         e.type == indexExp;
7245
7246                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7247                      {
7248                         Context context = PushContext();
7249                         Declarator decl;
7250                         OldList * specs = MkList();
7251                         char typeString[1024];
7252                         Expression newExp { };
7253
7254                         typeString[0] = '\0';
7255                         *newExp = *e;
7256
7257                         //if(e.destType) e.destType.refCount++;
7258                         // if(exp.expType) exp.expType.refCount++;
7259                         newExp.prev = null;
7260                         newExp.next = null;
7261                         newExp.expType = null;
7262
7263                         PrintTypeNoConst(e.expType, typeString, false, true);
7264                         decl = SpecDeclFromString(typeString, specs, null);
7265                         newExp.destType = ProcessType(specs, decl);
7266
7267                         curContext = context;
7268
7269                         // We need a current compound for this
7270                         if(curCompound)
7271                         {
7272                            char name[100];
7273                            OldList * stmts = MkList();
7274                            e.type = extensionCompoundExp;
7275                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7276                            if(!curCompound.compound.declarations)
7277                               curCompound.compound.declarations = MkList();
7278                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7279                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7280                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7281                            e.compound = MkCompoundStmt(null, stmts);
7282                         }
7283                         else
7284                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7285
7286                         /*
7287                         e.compound = MkCompoundStmt(
7288                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7289                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7290
7291                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7292                         */
7293
7294                         {
7295                            Type type = e.destType;
7296                            e.destType = { };
7297                            CopyTypeInto(e.destType, type);
7298                            e.destType.refCount = 1;
7299                            e.destType.classObjectType = none;
7300                            FreeType(type);
7301                         }
7302
7303                         e.compound.compound.context = context;
7304                         PopContext(context);
7305                         curContext = context.parent;
7306                      }
7307                   }
7308
7309                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7310                   checkedExp = e;
7311                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7312                   {
7313                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7314                      {
7315                         if(checkedExp.type == extensionCompoundExp)
7316                         {
7317                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7318                         }
7319                         else
7320                            checkedExp = checkedExp.list->last;
7321                      }
7322                      else if(checkedExp.type == castExp)
7323                         checkedExp = checkedExp.cast.exp;
7324                   }
7325                   {
7326                      Expression operand { };
7327                      operand = *checkedExp;
7328                      checkedExp.destType = null;
7329                      checkedExp.expType = null;
7330                      checkedExp.Clear();
7331                      checkedExp.type = opExp;
7332                      checkedExp.op.op = '&';
7333                      checkedExp.op.exp1 = null;
7334                      checkedExp.op.exp2 = operand;
7335
7336                      //newExp = MkExpOp(null, '&', checkedExp);
7337                   }
7338                   //ReplaceExpContents(checkedExp, newExp);
7339                }
7340             }
7341          }
7342       }
7343    }
7344    {
7345       // If expression type is a simple class, make it an address
7346       // FixReference(e, true);
7347    }
7348 //#if 0
7349    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7350       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7351          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7352    {
7353       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"))
7354       {
7355          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7356       }
7357       else
7358       {
7359          Expression thisExp { };
7360
7361          *thisExp = *e;
7362          thisExp.prev = null;
7363          thisExp.next = null;
7364          e.Clear();
7365
7366          e.type = bracketsExp;
7367          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7368          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7369             ((Expression)e.list->first).byReference = true;
7370
7371          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7372          {
7373             e.expType = thisExp.expType;
7374             e.expType.refCount++;
7375          }
7376          else*/
7377          {
7378             e.expType = { };
7379             CopyTypeInto(e.expType, thisExp.expType);
7380             e.expType.byReference = false;
7381             e.expType.refCount = 1;
7382
7383             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7384                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7385             {
7386                e.expType.classObjectType = none;
7387             }
7388          }
7389       }
7390    }
7391 // TOFIX: Try this for a nice IDE crash!
7392 //#endif
7393    // The other way around
7394    else
7395 //#endif
7396    if(destType && e.expType &&
7397          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7398          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7399          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7400    {
7401       if(destType.kind == ellipsisType)
7402       {
7403          Compiler_Error($"Unspecified type\n");
7404       }
7405       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7406       {
7407          bool byReference = e.expType.byReference;
7408          Expression thisExp { };
7409          Declarator decl;
7410          OldList * specs = MkList();
7411          char typeString[1024]; // Watch buffer overruns
7412          Type type;
7413          ClassObjectType backupClassObjectType;
7414          bool backupByReference;
7415
7416          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7417             type = e.expType;
7418          else
7419             type = destType;
7420
7421          backupClassObjectType = type.classObjectType;
7422          backupByReference = type.byReference;
7423
7424          type.classObjectType = none;
7425          type.byReference = false;
7426
7427          typeString[0] = '\0';
7428          PrintType(type, typeString, false, true);
7429          decl = SpecDeclFromString(typeString, specs, null);
7430
7431          type.classObjectType = backupClassObjectType;
7432          type.byReference = backupByReference;
7433
7434          *thisExp = *e;
7435          thisExp.prev = null;
7436          thisExp.next = null;
7437          e.Clear();
7438
7439          if( ( type.kind == classType && type._class && type._class.registered &&
7440                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7441                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7442              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7443              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7444          {
7445             e.type = opExp;
7446             e.op.op = '*';
7447             e.op.exp1 = null;
7448             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7449
7450             e.expType = { };
7451             CopyTypeInto(e.expType, type);
7452             e.expType.byReference = false;
7453             e.expType.refCount = 1;
7454          }
7455          else
7456          {
7457             e.type = castExp;
7458             e.cast.typeName = MkTypeName(specs, decl);
7459             e.cast.exp = thisExp;
7460             e.byReference = true;
7461             e.expType = type;
7462             type.refCount++;
7463          }
7464          e.destType = destType;
7465          destType.refCount++;
7466       }
7467    }
7468 }
7469
7470 void ProcessExpressionType(Expression exp)
7471 {
7472    bool unresolved = false;
7473    Location oldyylloc = yylloc;
7474    bool notByReference = false;
7475 #ifdef _DEBUG
7476    char debugExpString[4096];
7477    debugExpString[0] = '\0';
7478    PrintExpression(exp, debugExpString);
7479 #endif
7480    if(!exp || exp.expType)
7481       return;
7482
7483    //eSystem_Logf("%s\n", expString);
7484
7485    // Testing this here
7486    yylloc = exp.loc;
7487    switch(exp.type)
7488    {
7489       case identifierExp:
7490       {
7491          Identifier id = exp.identifier;
7492          if(!id || !topContext) return;
7493
7494          // DOING THIS LATER NOW...
7495          if(id._class && id._class.name)
7496          {
7497             id.classSym = id._class.symbol; // FindClass(id._class.name);
7498             /* TODO: Name Space Fix ups
7499             if(!id.classSym)
7500                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7501             */
7502          }
7503
7504          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7505          {
7506             exp.expType = ProcessTypeString("Module", true);
7507             break;
7508          }
7509          else */if(strstr(id.string, "__ecereClass") == id.string)
7510          {
7511             exp.expType = ProcessTypeString("ecere::com::Class", true);
7512             break;
7513          }
7514          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7515          {
7516             // Added this here as well
7517             ReplaceClassMembers(exp, thisClass);
7518             if(exp.type != identifierExp)
7519             {
7520                ProcessExpressionType(exp);
7521                break;
7522             }
7523
7524             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7525                break;
7526          }
7527          else
7528          {
7529             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7530             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7531             if(!symbol/* && exp.destType*/)
7532             {
7533                if(exp.destType && CheckExpressionType(exp, exp.destType, false))
7534                   break;
7535                else
7536                {
7537                   if(thisClass)
7538                   {
7539                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7540                      if(exp.type != identifierExp)
7541                      {
7542                         ProcessExpressionType(exp);
7543                         break;
7544                      }
7545                   }
7546                   // Static methods called from inside the _class
7547                   else if(currentClass && !id._class)
7548                   {
7549                      if(ResolveIdWithClass(exp, currentClass, true))
7550                         break;
7551                   }
7552                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7553                }
7554             }
7555
7556             // If we manage to resolve this symbol
7557             if(symbol)
7558             {
7559                Type type = symbol.type;
7560                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7561
7562                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7563                {
7564                   Context context = SetupTemplatesContext(_class);
7565                   type = ReplaceThisClassType(_class);
7566                   FinishTemplatesContext(context);
7567                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7568                }
7569
7570                FreeSpecifier(id._class);
7571                id._class = null;
7572                delete id.string;
7573                id.string = CopyString(symbol.string);
7574
7575                id.classSym = null;
7576                exp.expType = type;
7577                if(type)
7578                   type.refCount++;
7579                if(type && (type.kind == enumType || (_class && _class.type == enumClass)))
7580                   // Add missing cases here... enum Classes...
7581                   exp.isConstant = true;
7582
7583                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7584                if(symbol.isParam || !strcmp(id.string, "this"))
7585                {
7586                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7587                      exp.byReference = true;
7588
7589                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7590                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7591                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7592                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7593                   {
7594                      Identifier id = exp.identifier;
7595                      exp.type = bracketsExp;
7596                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7597                   }*/
7598                }
7599
7600                if(symbol.isIterator)
7601                {
7602                   if(symbol.isIterator == 3)
7603                   {
7604                      exp.type = bracketsExp;
7605                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7606                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7607                      exp.expType = null;
7608                      ProcessExpressionType(exp);
7609                   }
7610                   else if(symbol.isIterator != 4)
7611                   {
7612                      exp.type = memberExp;
7613                      exp.member.exp = MkExpIdentifier(exp.identifier);
7614                      exp.member.exp.expType = exp.expType;
7615                      /*if(symbol.isIterator == 6)
7616                         exp.member.member = MkIdentifier("key");
7617                      else*/
7618                         exp.member.member = MkIdentifier("data");
7619                      exp.expType = null;
7620                      ProcessExpressionType(exp);
7621                   }
7622                }
7623                break;
7624             }
7625             else
7626             {
7627                DefinedExpression definedExp = null;
7628                if(thisNameSpace && !(id._class && !id._class.name))
7629                {
7630                   char name[1024];
7631                   strcpy(name, thisNameSpace);
7632                   strcat(name, "::");
7633                   strcat(name, id.string);
7634                   definedExp = eSystem_FindDefine(privateModule, name);
7635                }
7636                if(!definedExp)
7637                   definedExp = eSystem_FindDefine(privateModule, id.string);
7638                if(definedExp)
7639                {
7640                   int c;
7641                   for(c = 0; c<definedExpStackPos; c++)
7642                      if(definedExpStack[c] == definedExp)
7643                         break;
7644                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7645                   {
7646                      Location backupYylloc = yylloc;
7647                      File backInput = fileInput;
7648                      definedExpStack[definedExpStackPos++] = definedExp;
7649
7650                      fileInput = TempFile { };
7651                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7652                      fileInput.Seek(0, start);
7653
7654                      echoOn = false;
7655                      parsedExpression = null;
7656                      resetScanner();
7657                      expression_yyparse();
7658                      delete fileInput;
7659                      if(backInput)
7660                         fileInput = backInput;
7661
7662                      yylloc = backupYylloc;
7663
7664                      if(parsedExpression)
7665                      {
7666                         FreeIdentifier(id);
7667                         exp.type = bracketsExp;
7668                         exp.list = MkListOne(parsedExpression);
7669                         parsedExpression.loc = yylloc;
7670                         ProcessExpressionType(exp);
7671                         definedExpStackPos--;
7672                         return;
7673                      }
7674                      definedExpStackPos--;
7675                   }
7676                   else
7677                   {
7678                      if(inCompiler)
7679                      {
7680                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7681                      }
7682                   }
7683                }
7684                else
7685                {
7686                   GlobalData data = null;
7687                   if(thisNameSpace && !(id._class && !id._class.name))
7688                   {
7689                      char name[1024];
7690                      strcpy(name, thisNameSpace);
7691                      strcat(name, "::");
7692                      strcat(name, id.string);
7693                      data = FindGlobalData(name);
7694                   }
7695                   if(!data)
7696                      data = FindGlobalData(id.string);
7697                   if(data)
7698                   {
7699                      DeclareGlobalData(data);
7700                      exp.expType = data.dataType;
7701                      if(data.dataType) data.dataType.refCount++;
7702
7703                      delete id.string;
7704                      id.string = CopyString(data.fullName);
7705                      FreeSpecifier(id._class);
7706                      id._class = null;
7707
7708                      break;
7709                   }
7710                   else
7711                   {
7712                      GlobalFunction function = null;
7713                      if(thisNameSpace && !(id._class && !id._class.name))
7714                      {
7715                         char name[1024];
7716                         strcpy(name, thisNameSpace);
7717                         strcat(name, "::");
7718                         strcat(name, id.string);
7719                         function = eSystem_FindFunction(privateModule, name);
7720                      }
7721                      if(!function)
7722                         function = eSystem_FindFunction(privateModule, id.string);
7723                      if(function)
7724                      {
7725                         char name[1024];
7726                         delete id.string;
7727                         id.string = CopyString(function.name);
7728                         name[0] = 0;
7729
7730                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
7731                            strcpy(name, "__ecereFunction_");
7732                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
7733                         if(DeclareFunction(function, name))
7734                         {
7735                            delete id.string;
7736                            id.string = CopyString(name);
7737                         }
7738                         exp.expType = function.dataType;
7739                         if(function.dataType) function.dataType.refCount++;
7740
7741                         FreeSpecifier(id._class);
7742                         id._class = null;
7743
7744                         break;
7745                      }
7746                   }
7747                }
7748             }
7749          }
7750          unresolved = true;
7751          break;
7752       }
7753       case instanceExp:
7754       {
7755          Class _class;
7756          // Symbol classSym;
7757
7758          if(!exp.instance._class)
7759          {
7760             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
7761             {
7762                exp.instance._class = MkSpecifierName(exp.destType._class.string);
7763             }
7764          }
7765
7766          //classSym = FindClass(exp.instance._class.fullName);
7767          //_class = classSym ? classSym.registered : null;
7768
7769          ProcessInstantiationType(exp.instance);
7770          exp.isConstant = exp.instance.isConstant;
7771
7772          /*
7773          if(_class.type == unitClass && _class.base.type != systemClass)
7774          {
7775             {
7776                Type destType = exp.destType;
7777
7778                exp.destType = MkClassType(_class.base.fullName);
7779                exp.expType = MkClassType(_class.fullName);
7780                CheckExpressionType(exp, exp.destType, true);
7781
7782                exp.destType = destType;
7783             }
7784             exp.expType = MkClassType(_class.fullName);
7785          }
7786          else*/
7787          if(exp.instance._class)
7788          {
7789             exp.expType = MkClassType(exp.instance._class.name);
7790             /*if(exp.expType._class && exp.expType._class.registered &&
7791                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
7792                exp.expType.byReference = true;*/
7793          }
7794          break;
7795       }
7796       case constantExp:
7797       {
7798          if(!exp.expType)
7799          {
7800             char * constant = exp.constant;
7801             Type type
7802             {
7803                refCount = 1;
7804                constant = true;
7805             };
7806             exp.expType = type;
7807
7808             if(constant[0] == '\'')
7809             {
7810                if((int)((byte *)constant)[1] > 127)
7811                {
7812                   int nb;
7813                   unichar ch = UTF8GetChar(constant + 1, &nb);
7814                   if(nb < 2) ch = constant[1];
7815                   delete constant;
7816                   exp.constant = PrintUInt(ch);
7817                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
7818                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
7819                   type._class = FindClass("unichar");
7820
7821                   type.isSigned = false;
7822                }
7823                else
7824                {
7825                   type.kind = charType;
7826                   type.isSigned = true;
7827                }
7828             }
7829             else
7830             {
7831                char * dot = strchr(constant, '.');
7832                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
7833                char * exponent;
7834                if(isHex)
7835                {
7836                   exponent = strchr(constant, 'p');
7837                   if(!exponent) exponent = strchr(constant, 'P');
7838                }
7839                else
7840                {
7841                   exponent = strchr(constant, 'e');
7842                   if(!exponent) exponent = strchr(constant, 'E');
7843                }
7844
7845                if(dot || exponent)
7846                {
7847                   if(strchr(constant, 'f') || strchr(constant, 'F'))
7848                      type.kind = floatType;
7849                   else
7850                      type.kind = doubleType;
7851                   type.isSigned = true;
7852                }
7853                else
7854                {
7855                   bool isSigned = constant[0] == '-';
7856                   char * endP = null;
7857                   int64 i64 = strtoll(constant, &endP, 0);
7858                   uint64 ui64 = strtoull(constant, &endP, 0);
7859                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll"));
7860                   if(isSigned)
7861                   {
7862                      if(i64 < MININT)
7863                         is64Bit = true;
7864                   }
7865                   else
7866                   {
7867                      if(ui64 > MAXINT)
7868                      {
7869                         if(ui64 > MAXDWORD)
7870                         {
7871                            is64Bit = true;
7872                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
7873                               isSigned = true;
7874                         }
7875                      }
7876                      else if(constant[0] != '0' || !constant[1])
7877                         isSigned = true;
7878                   }
7879                   type.kind = is64Bit ? int64Type : intType;
7880                   type.isSigned = isSigned;
7881                }
7882             }
7883             exp.isConstant = true;
7884             if(exp.destType && exp.destType.kind == doubleType)
7885                type.kind = doubleType;
7886             else if(exp.destType && exp.destType.kind == floatType)
7887                type.kind = floatType;
7888             else if(exp.destType && exp.destType.kind == int64Type)
7889                type.kind = int64Type;
7890          }
7891          break;
7892       }
7893       case stringExp:
7894       {
7895          exp.isConstant = true;      // Why wasn't this constant?
7896          exp.expType = Type
7897          {
7898             refCount = 1;
7899             kind = pointerType;
7900             type = Type
7901             {
7902                refCount = 1;
7903                kind = charType;
7904                constant = true;
7905                isSigned = true;
7906             }
7907          };
7908          break;
7909       }
7910       case newExp:
7911       case new0Exp:
7912          ProcessExpressionType(exp._new.size);
7913          exp.expType = Type
7914          {
7915             refCount = 1;
7916             kind = pointerType;
7917             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
7918          };
7919          DeclareType(exp.expType.type, false, false);
7920          break;
7921       case renewExp:
7922       case renew0Exp:
7923          ProcessExpressionType(exp._renew.size);
7924          ProcessExpressionType(exp._renew.exp);
7925          exp.expType = Type
7926          {
7927             refCount = 1;
7928             kind = pointerType;
7929             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
7930          };
7931          DeclareType(exp.expType.type, false, false);
7932          break;
7933       case opExp:
7934       {
7935          bool assign = false, boolResult = false, boolOps = false;
7936          Type type1 = null, type2 = null;
7937          bool useDestType = false, useSideType = false;
7938          Location oldyylloc = yylloc;
7939          bool useSideUnit = false;
7940
7941          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
7942          Type dummy
7943          {
7944             count = 1;
7945             refCount = 1;
7946          };
7947
7948          switch(exp.op.op)
7949          {
7950             // Assignment Operators
7951             case '=':
7952             case MUL_ASSIGN:
7953             case DIV_ASSIGN:
7954             case MOD_ASSIGN:
7955             case ADD_ASSIGN:
7956             case SUB_ASSIGN:
7957             case LEFT_ASSIGN:
7958             case RIGHT_ASSIGN:
7959             case AND_ASSIGN:
7960             case XOR_ASSIGN:
7961             case OR_ASSIGN:
7962                assign = true;
7963                break;
7964             // boolean Operators
7965             case '!':
7966                // Expect boolean operators
7967                //boolOps = true;
7968                //boolResult = true;
7969                break;
7970             case AND_OP:
7971             case OR_OP:
7972                // Expect boolean operands
7973                boolOps = true;
7974                boolResult = true;
7975                break;
7976             // Comparisons
7977             case EQ_OP:
7978             case '<':
7979             case '>':
7980             case LE_OP:
7981             case GE_OP:
7982             case NE_OP:
7983                // Gives boolean result
7984                boolResult = true;
7985                useSideType = true;
7986                break;
7987             case '+':
7988             case '-':
7989                useSideUnit = true;
7990
7991                // Just added these... testing
7992             case '|':
7993             case '&':
7994             case '^':
7995
7996             // DANGER: Verify units
7997             case '/':
7998             case '%':
7999             case '*':
8000
8001                if(exp.op.op != '*' || exp.op.exp1)
8002                {
8003                   useSideType = true;
8004                   useDestType = true;
8005                }
8006                break;
8007
8008             /*// Implement speed etc.
8009             case '*':
8010             case '/':
8011                break;
8012             */
8013          }
8014          if(exp.op.op == '&')
8015          {
8016             // Added this here earlier for Iterator address as key
8017             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8018             {
8019                Identifier id = exp.op.exp2.identifier;
8020                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8021                if(symbol && symbol.isIterator == 2)
8022                {
8023                   exp.type = memberExp;
8024                   exp.member.exp = exp.op.exp2;
8025                   exp.member.member = MkIdentifier("key");
8026                   exp.expType = null;
8027                   exp.op.exp2.expType = symbol.type;
8028                   symbol.type.refCount++;
8029                   ProcessExpressionType(exp);
8030                   FreeType(dummy);
8031                   break;
8032                }
8033                // exp.op.exp2.usage.usageRef = true;
8034             }
8035          }
8036
8037          //dummy.kind = TypeDummy;
8038
8039          if(exp.op.exp1)
8040          {
8041             if(exp.destType && exp.destType.kind == classType &&
8042                exp.destType._class && exp.destType._class.registered && useDestType &&
8043
8044               ((exp.destType._class.registered.type == unitClass && useSideUnit) ||
8045                exp.destType._class.registered.type == enumClass ||
8046                exp.destType._class.registered.type == bitClass
8047                ))
8048
8049               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8050             {
8051                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8052                exp.op.exp1.destType = exp.destType;
8053                if(exp.destType)
8054                   exp.destType.refCount++;
8055             }
8056             else if(!assign)
8057             {
8058                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8059                exp.op.exp1.destType = dummy;
8060                dummy.refCount++;
8061             }
8062
8063             // TESTING THIS HERE...
8064             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8065             ProcessExpressionType(exp.op.exp1);
8066             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8067
8068             if(exp.op.exp1.destType == dummy)
8069             {
8070                FreeType(dummy);
8071                exp.op.exp1.destType = null;
8072             }
8073             type1 = exp.op.exp1.expType;
8074          }
8075
8076          if(exp.op.exp2)
8077          {
8078             char expString[10240];
8079             expString[0] = '\0';
8080             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8081             {
8082                if(exp.op.exp1)
8083                {
8084                   exp.op.exp2.destType = exp.op.exp1.expType;
8085                   if(exp.op.exp1.expType)
8086                      exp.op.exp1.expType.refCount++;
8087                }
8088                else
8089                {
8090                   exp.op.exp2.destType = exp.destType;
8091                   if(exp.destType)
8092                      exp.destType.refCount++;
8093                }
8094
8095                if(type1) type1.refCount++;
8096                exp.expType = type1;
8097             }
8098             else if(assign)
8099             {
8100                if(inCompiler)
8101                   PrintExpression(exp.op.exp2, expString);
8102
8103                if(type1 && type1.kind == pointerType)
8104                {
8105                   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 ||
8106                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8107                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8108                   else if(exp.op.op == '=')
8109                   {
8110                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8111                      exp.op.exp2.destType = type1;
8112                      if(type1)
8113                         type1.refCount++;
8114                   }
8115                }
8116                else
8117                {
8118                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8119                   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/* ||
8120                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8121                   else
8122                   {
8123                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8124                      exp.op.exp2.destType = type1;
8125                      if(type1)
8126                         type1.refCount++;
8127                   }
8128                }
8129                if(type1) type1.refCount++;
8130                exp.expType = type1;
8131             }
8132             else if(exp.destType && exp.destType.kind == classType &&
8133                exp.destType._class && exp.destType._class.registered &&
8134
8135                   ((exp.destType._class.registered.type == unitClass && useDestType && useSideUnit) ||
8136                   (exp.destType._class.registered.type == enumClass && useDestType))
8137                   )
8138             {
8139                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8140                exp.op.exp2.destType = exp.destType;
8141                if(exp.destType)
8142                   exp.destType.refCount++;
8143             }
8144             else
8145             {
8146                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8147                exp.op.exp2.destType = dummy;
8148                dummy.refCount++;
8149             }
8150
8151             // TESTING THIS HERE... (DANGEROUS)
8152             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8153                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8154             {
8155                FreeType(exp.op.exp2.destType);
8156                exp.op.exp2.destType = type1;
8157                type1.refCount++;
8158             }
8159             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8160             // Cannot lose the cast on a sizeof
8161             if(exp.op.op == SIZEOF)
8162             {
8163                Expression e = exp.op.exp2;
8164                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8165                {
8166                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8167                   {
8168                      if(e.type == extensionCompoundExp)
8169                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8170                      else
8171                         e = e.list->last;
8172                   }
8173                }
8174                if(e.type == castExp && e.cast.exp)
8175                   e.cast.exp.needCast = true;
8176             }
8177             ProcessExpressionType(exp.op.exp2);
8178             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8179
8180             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8181             {
8182                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)
8183                {
8184                   if(exp.op.op != '=' && type1.type.kind == voidType)
8185                      Compiler_Error($"void *: unknown size\n");
8186                }
8187                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||
8188                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8189                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8190                               exp.op.exp2.expType._class.registered.type == structClass ||
8191                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8192                {
8193                   if(exp.op.op == ADD_ASSIGN)
8194                      Compiler_Error($"cannot add two pointers\n");
8195                }
8196                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8197                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8198                {
8199                   if(exp.op.op == ADD_ASSIGN)
8200                      Compiler_Error($"cannot add two pointers\n");
8201                }
8202                else if(inCompiler)
8203                {
8204                   char type1String[1024];
8205                   char type2String[1024];
8206                   type1String[0] = '\0';
8207                   type2String[0] = '\0';
8208
8209                   PrintType(exp.op.exp2.expType, type1String, false, true);
8210                   PrintType(type1, type2String, false, true);
8211                   ChangeCh(expString, '\n', ' ');
8212                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8213                }
8214             }
8215
8216             if(exp.op.exp2.destType == dummy)
8217             {
8218                FreeType(dummy);
8219                exp.op.exp2.destType = null;
8220             }
8221
8222             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8223             {
8224                type2 = { };
8225                type2.refCount = 1;
8226                CopyTypeInto(type2, exp.op.exp2.expType);
8227                type2.isSigned = true;
8228             }
8229             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8230             {
8231                type2 = { kind = intType };
8232                type2.refCount = 1;
8233                type2.isSigned = true;
8234             }
8235             else
8236             {
8237                type2 = exp.op.exp2.expType;
8238                if(type2) type2.refCount++;
8239             }
8240          }
8241
8242          dummy.kind = voidType;
8243
8244          if(exp.op.op == SIZEOF)
8245          {
8246             exp.expType = Type
8247             {
8248                refCount = 1;
8249                kind = intType;
8250             };
8251             exp.isConstant = true;
8252          }
8253          // Get type of dereferenced pointer
8254          else if(exp.op.op == '*' && !exp.op.exp1)
8255          {
8256             exp.expType = Dereference(type2);
8257             if(type2 && type2.kind == classType)
8258                notByReference = true;
8259          }
8260          else if(exp.op.op == '&' && !exp.op.exp1)
8261             exp.expType = Reference(type2);
8262          else if(!assign)
8263          {
8264             if(boolOps)
8265             {
8266                if(exp.op.exp1)
8267                {
8268                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8269                   exp.op.exp1.destType = MkClassType("bool");
8270                   exp.op.exp1.destType.truth = true;
8271                   if(!exp.op.exp1.expType)
8272                      ProcessExpressionType(exp.op.exp1);
8273                   else
8274                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8275                   FreeType(exp.op.exp1.expType);
8276                   exp.op.exp1.expType = MkClassType("bool");
8277                   exp.op.exp1.expType.truth = true;
8278                }
8279                if(exp.op.exp2)
8280                {
8281                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8282                   exp.op.exp2.destType = MkClassType("bool");
8283                   exp.op.exp2.destType.truth = true;
8284                   if(!exp.op.exp2.expType)
8285                      ProcessExpressionType(exp.op.exp2);
8286                   else
8287                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8288                   FreeType(exp.op.exp2.expType);
8289                   exp.op.exp2.expType = MkClassType("bool");
8290                   exp.op.exp2.expType.truth = true;
8291                }
8292             }
8293             else if(exp.op.exp1 && exp.op.exp2 &&
8294                ((useSideType /*&&
8295                      (useSideUnit ||
8296                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8297                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8298                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8299                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8300             {
8301                if(type1 && type2 &&
8302                   // If either both are class or both are not class
8303                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8304                {
8305                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8306                   exp.op.exp2.destType = type1;
8307                   type1.refCount++;
8308                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8309                   exp.op.exp1.destType = type2;
8310                   type2.refCount++;
8311                   // Warning here for adding Radians + Degrees with no destination type
8312                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8313                      type1._class.registered && type1._class.registered.type == unitClass &&
8314                      type2._class.registered && type2._class.registered.type == unitClass &&
8315                      type1._class.registered != type2._class.registered)
8316                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8317                         type1._class.string, type2._class.string, type1._class.string);
8318
8319                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8320                   {
8321                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8322                      if(argExp)
8323                      {
8324                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8325
8326                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8327                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8328                            exp.op.exp1)));
8329
8330                         ProcessExpressionType(exp.op.exp1);
8331
8332                         if(type2.kind != pointerType)
8333                         {
8334                            ProcessExpressionType(classExp);
8335
8336                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*',
8337                               // ((_class.type == noHeadClass || _class.type == normalClass) ? sizeof(void *) : type.size)
8338                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(MkExpOp(
8339                                  // noHeadClass
8340                                  MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpConstant("5")),
8341                                     OR_OP,
8342                                  // normalClass
8343                                  MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpConstant("0"))))),
8344                                     MkListOne(MkExpTypeSize(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(
8345                                        MkPointer(null, null), null)))),
8346                                        MkExpMember(classExp, MkIdentifier("typeSize"))))))));
8347
8348                            if(!exp.op.exp2.expType)
8349                            {
8350                               if(type2)
8351                                  FreeType(type2);
8352                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8353                               type2.refCount++;
8354                            }
8355
8356                            ProcessExpressionType(exp.op.exp2);
8357                         }
8358                      }
8359                   }
8360
8361                   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)))
8362                   {
8363                      if(type1.kind != classType && type1.type.kind == voidType)
8364                         Compiler_Error($"void *: unknown size\n");
8365                      exp.expType = type1;
8366                      if(type1) type1.refCount++;
8367                   }
8368                   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)))
8369                   {
8370                      if(type2.kind != classType && type2.type.kind == voidType)
8371                         Compiler_Error($"void *: unknown size\n");
8372                      exp.expType = type2;
8373                      if(type2) type2.refCount++;
8374                   }
8375                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8376                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8377                   {
8378                      Compiler_Warning($"different levels of indirection\n");
8379                   }
8380                   else
8381                   {
8382                      bool success = false;
8383                      if(type1.kind == pointerType && type2.kind == pointerType)
8384                      {
8385                         if(exp.op.op == '+')
8386                            Compiler_Error($"cannot add two pointers\n");
8387                         else if(exp.op.op == '-')
8388                         {
8389                            // Pointer Subtraction gives integer
8390                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false))
8391                            {
8392                               exp.expType = Type
8393                               {
8394                                  kind = intType;
8395                                  refCount = 1;
8396                               };
8397                               success = true;
8398
8399                               if(type1.type.kind == templateType)
8400                               {
8401                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8402                                  if(argExp)
8403                                  {
8404                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8405
8406                                     ProcessExpressionType(classExp);
8407
8408                                     exp.type = bracketsExp;
8409                                     exp.list = MkListOne(MkExpOp(
8410                                        MkExpBrackets(MkListOne(MkExpOp(
8411                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8412                                              , exp.op.op,
8413                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8414
8415                                              //MkExpMember(classExp, MkIdentifier("typeSize"))
8416
8417                                              // ((_class.type == noHeadClass || _class.type == normalClass) ? sizeof(void *) : type.size)
8418                                              MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(MkExpOp(
8419                                                 // noHeadClass
8420                                                 MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpIdentifier(MkIdentifier("noHeadClass"))),
8421                                                    OR_OP,
8422                                                 // normalClass
8423                                                 MkExpOp(MkExpMember(CopyExpression(classExp), MkIdentifier("type")), EQ_OP, MkExpIdentifier(MkIdentifier("normalClass")))))),
8424                                                    MkListOne(MkExpTypeSize(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(
8425                                                       MkPointer(null, null), null)))),
8426                                                       MkExpMember(classExp, MkIdentifier("typeSize")))))
8427
8428
8429                                              ));
8430
8431                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8432                                     FreeType(dummy);
8433                                     return;
8434                                  }
8435                               }
8436                            }
8437                         }
8438                      }
8439
8440                      if(!success && exp.op.exp1.type == constantExp)
8441                      {
8442                         // If first expression is constant, try to match that first
8443                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8444                         {
8445                            if(exp.expType) FreeType(exp.expType);
8446                            exp.expType = exp.op.exp1.destType;
8447                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8448                            success = true;
8449                         }
8450                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8451                         {
8452                            if(exp.expType) FreeType(exp.expType);
8453                            exp.expType = exp.op.exp2.destType;
8454                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8455                            success = true;
8456                         }
8457                      }
8458                      else if(!success)
8459                      {
8460                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8461                         {
8462                            if(exp.expType) FreeType(exp.expType);
8463                            exp.expType = exp.op.exp2.destType;
8464                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8465                            success = true;
8466                         }
8467                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8468                         {
8469                            if(exp.expType) FreeType(exp.expType);
8470                            exp.expType = exp.op.exp1.destType;
8471                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8472                            success = true;
8473                         }
8474                      }
8475                      if(!success)
8476                      {
8477                         char expString1[10240];
8478                         char expString2[10240];
8479                         char type1[1024];
8480                         char type2[1024];
8481                         expString1[0] = '\0';
8482                         expString2[0] = '\0';
8483                         type1[0] = '\0';
8484                         type2[0] = '\0';
8485                         if(inCompiler)
8486                         {
8487                            PrintExpression(exp.op.exp1, expString1);
8488                            ChangeCh(expString1, '\n', ' ');
8489                            PrintExpression(exp.op.exp2, expString2);
8490                            ChangeCh(expString2, '\n', ' ');
8491                            PrintType(exp.op.exp1.expType, type1, false, true);
8492                            PrintType(exp.op.exp2.expType, type2, false, true);
8493                         }
8494
8495                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8496                      }
8497                   }
8498                }
8499                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8500                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8501                {
8502                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8503                   // Convert e.g. / 4 into / 4.0
8504                   exp.op.exp1.destType = type2._class.registered.dataType;
8505                   if(type2._class.registered.dataType)
8506                      type2._class.registered.dataType.refCount++;
8507                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8508                   exp.expType = type2;
8509                   if(type2) type2.refCount++;
8510                }
8511                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8512                {
8513                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8514                   // Convert e.g. / 4 into / 4.0
8515                   exp.op.exp2.destType = type1._class.registered.dataType;
8516                   if(type1._class.registered.dataType)
8517                      type1._class.registered.dataType.refCount++;
8518                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8519                   exp.expType = type1;
8520                   if(type1) type1.refCount++;
8521                }
8522                else if(type1)
8523                {
8524                   bool valid = false;
8525
8526                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8527                   {
8528                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8529
8530                      if(!type1._class.registered.dataType)
8531                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8532                      exp.op.exp2.destType = type1._class.registered.dataType;
8533                      exp.op.exp2.destType.refCount++;
8534
8535                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8536                      if(type2)
8537                         FreeType(type2);
8538                      type2 = exp.op.exp2.destType;
8539                      if(type2) type2.refCount++;
8540
8541                      exp.expType = type2;
8542                      type2.refCount++;
8543                   }
8544
8545                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8546                   {
8547                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8548
8549                      if(!type2._class.registered.dataType)
8550                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8551                      exp.op.exp1.destType = type2._class.registered.dataType;
8552                      exp.op.exp1.destType.refCount++;
8553
8554                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8555                      type1 = exp.op.exp1.destType;
8556                      exp.expType = type1;
8557                      type1.refCount++;
8558                   }
8559
8560                   // TESTING THIS NEW CODE
8561                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<')
8562                   {
8563                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass && exp.op.exp2.expType)
8564                      {
8565                         if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false))
8566                         {
8567                            if(exp.expType) FreeType(exp.expType);
8568                            exp.expType = exp.op.exp1.expType;
8569                            if(exp.op.exp2.expType) exp.op.exp1.expType.refCount++;
8570                            valid = true;
8571                         }
8572                      }
8573
8574                      else if(type2 && (type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass && exp.op.exp1.expType))
8575                      {
8576                         if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false))
8577                         {
8578                            if(exp.expType) FreeType(exp.expType);
8579                            exp.expType = exp.op.exp2.expType;
8580                            if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8581                            valid = true;
8582                         }
8583                      }
8584                   }
8585
8586                   if(!valid)
8587                   {
8588                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8589                      exp.op.exp2.destType = type1;
8590                      type1.refCount++;
8591
8592                      /*
8593                      // Maybe this was meant to be an enum...
8594                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8595                      {
8596                         Type oldType = exp.op.exp2.expType;
8597                         exp.op.exp2.expType = null;
8598                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8599                            FreeType(oldType);
8600                         else
8601                            exp.op.exp2.expType = oldType;
8602                      }
8603                      */
8604
8605                      /*
8606                      // TESTING THIS HERE... LATEST ADDITION
8607                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8608                      {
8609                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8610                         exp.op.exp2.destType = type2._class.registered.dataType;
8611                         if(type2._class.registered.dataType)
8612                            type2._class.registered.dataType.refCount++;
8613                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8614
8615                         //exp.expType = type2._class.registered.dataType; //type2;
8616                         //if(type2) type2.refCount++;
8617                      }
8618
8619                      // TESTING THIS HERE... LATEST ADDITION
8620                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8621                      {
8622                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8623                         exp.op.exp1.destType = type1._class.registered.dataType;
8624                         if(type1._class.registered.dataType)
8625                            type1._class.registered.dataType.refCount++;
8626                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8627                         exp.expType = type1._class.registered.dataType; //type1;
8628                         if(type1) type1.refCount++;
8629                      }
8630                      */
8631
8632                      if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8633                      {
8634                         if(exp.expType) FreeType(exp.expType);
8635                         exp.expType = exp.op.exp2.destType;
8636                         if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8637                      }
8638                      else if(type1 && type2)
8639                      {
8640                         char expString1[10240];
8641                         char expString2[10240];
8642                         char type1String[1024];
8643                         char type2String[1024];
8644                         expString1[0] = '\0';
8645                         expString2[0] = '\0';
8646                         type1String[0] = '\0';
8647                         type2String[0] = '\0';
8648                         if(inCompiler)
8649                         {
8650                            PrintExpression(exp.op.exp1, expString1);
8651                            ChangeCh(expString1, '\n', ' ');
8652                            PrintExpression(exp.op.exp2, expString2);
8653                            ChangeCh(expString2, '\n', ' ');
8654                            PrintType(exp.op.exp1.expType, type1String, false, true);
8655                            PrintType(exp.op.exp2.expType, type2String, false, true);
8656                         }
8657
8658                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
8659
8660                         if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8661                         {
8662                            exp.expType = exp.op.exp1.expType;
8663                            if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8664                         }
8665                         else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
8666                         {
8667                            exp.expType = exp.op.exp2.expType;
8668                            if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8669                         }
8670                      }
8671                   }
8672                }
8673                else if(type2)
8674                {
8675                   // Maybe this was meant to be an enum...
8676                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
8677                   {
8678                      Type oldType = exp.op.exp1.expType;
8679                      exp.op.exp1.expType = null;
8680                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8681                         FreeType(oldType);
8682                      else
8683                         exp.op.exp1.expType = oldType;
8684                   }
8685
8686                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8687                   exp.op.exp1.destType = type2;
8688                   type2.refCount++;
8689                   /*
8690                   // TESTING THIS HERE... LATEST ADDITION
8691                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8692                   {
8693                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8694                      exp.op.exp1.destType = type1._class.registered.dataType;
8695                      if(type1._class.registered.dataType)
8696                         type1._class.registered.dataType.refCount++;
8697                   }
8698
8699                   // TESTING THIS HERE... LATEST ADDITION
8700                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8701                   {
8702                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8703                      exp.op.exp2.destType = type2._class.registered.dataType;
8704                      if(type2._class.registered.dataType)
8705                         type2._class.registered.dataType.refCount++;
8706                   }
8707                   */
8708
8709                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false))
8710                   {
8711                      if(exp.expType) FreeType(exp.expType);
8712                      exp.expType = exp.op.exp1.destType;
8713                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8714                   }
8715                }
8716             }
8717             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
8718             {
8719                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8720                {
8721                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8722                   // Convert e.g. / 4 into / 4.0
8723                   exp.op.exp1.destType = type2._class.registered.dataType;
8724                   if(type2._class.registered.dataType)
8725                      type2._class.registered.dataType.refCount++;
8726                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
8727                }
8728                if(exp.op.op == '!')
8729                {
8730                   exp.expType = MkClassType("bool");
8731                   exp.expType.truth = true;
8732                }
8733                else
8734                {
8735                   exp.expType = type2;
8736                   if(type2) type2.refCount++;
8737                }
8738             }
8739             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
8740             {
8741                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8742                {
8743                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8744                   // Convert e.g. / 4 into / 4.0
8745                   exp.op.exp2.destType = type1._class.registered.dataType;
8746                   if(type1._class.registered.dataType)
8747                      type1._class.registered.dataType.refCount++;
8748                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8749                }
8750                exp.expType = type1;
8751                if(type1) type1.refCount++;
8752             }
8753          }
8754
8755          yylloc = exp.loc;
8756          if(exp.op.exp1 && !exp.op.exp1.expType)
8757          {
8758             char expString[10000];
8759             expString[0] = '\0';
8760             if(inCompiler)
8761             {
8762                PrintExpression(exp.op.exp1, expString);
8763                ChangeCh(expString, '\n', ' ');
8764             }
8765             if(expString[0])
8766                Compiler_Error($"couldn't determine type of %s\n", expString);
8767          }
8768          if(exp.op.exp2 && !exp.op.exp2.expType)
8769          {
8770             char expString[10240];
8771             expString[0] = '\0';
8772             if(inCompiler)
8773             {
8774                PrintExpression(exp.op.exp2, expString);
8775                ChangeCh(expString, '\n', ' ');
8776             }
8777             if(expString[0])
8778                Compiler_Error($"couldn't determine type of %s\n", expString);
8779          }
8780
8781          if(boolResult)
8782          {
8783             FreeType(exp.expType);
8784             exp.expType = MkClassType("bool");
8785             exp.expType.truth = true;
8786          }
8787
8788          if(exp.op.op != SIZEOF)
8789             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
8790                (!exp.op.exp2 || exp.op.exp2.isConstant);
8791
8792          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
8793          {
8794             DeclareType(exp.op.exp2.expType, false, false);
8795          }
8796
8797          yylloc = oldyylloc;
8798
8799          FreeType(dummy);
8800          if(type2)
8801             FreeType(type2);
8802          break;
8803       }
8804       case bracketsExp:
8805       case extensionExpressionExp:
8806       {
8807          Expression e;
8808          exp.isConstant = true;
8809          for(e = exp.list->first; e; e = e.next)
8810          {
8811             bool inced = false;
8812             if(!e.next)
8813             {
8814                FreeType(e.destType);
8815                e.destType = exp.destType;
8816                if(e.destType) { exp.destType.refCount++; e.destType.count++; inced = true; }
8817             }
8818             ProcessExpressionType(e);
8819             if(inced)
8820                exp.destType.count--;
8821             if(!exp.expType && !e.next)
8822             {
8823                exp.expType = e.expType;
8824                if(e.expType) e.expType.refCount++;
8825             }
8826             if(!e.isConstant)
8827                exp.isConstant = false;
8828          }
8829
8830          // In case a cast became a member...
8831          e = exp.list->first;
8832          if(!e.next && e.type == memberExp)
8833          {
8834             // Preserve prev, next
8835             Expression next = exp.next, prev = exp.prev;
8836
8837
8838             FreeType(exp.expType);
8839             FreeType(exp.destType);
8840             delete exp.list;
8841
8842             *exp = *e;
8843
8844             exp.prev = prev;
8845             exp.next = next;
8846
8847             delete e;
8848
8849             ProcessExpressionType(exp);
8850          }
8851          break;
8852       }
8853       case indexExp:
8854       {
8855          Expression e;
8856          exp.isConstant = true;
8857
8858          ProcessExpressionType(exp.index.exp);
8859          if(!exp.index.exp.isConstant)
8860             exp.isConstant = false;
8861
8862          if(exp.index.exp.expType)
8863          {
8864             Type source = exp.index.exp.expType;
8865             if(source.kind == classType && source._class && source._class.registered)
8866             {
8867                Class _class = source._class.registered;
8868                Class c = _class.templateClass ? _class.templateClass : _class;
8869                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
8870                {
8871                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
8872
8873                   if(exp.index.index && exp.index.index->last)
8874                   {
8875                      ((Expression)exp.index.index->last).destType = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
8876                   }
8877                }
8878             }
8879          }
8880
8881          for(e = exp.index.index->first; e; e = e.next)
8882          {
8883             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
8884             {
8885                if(e.destType) FreeType(e.destType);
8886                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
8887             }
8888             ProcessExpressionType(e);
8889             if(!e.next)
8890             {
8891                // Check if this type is int
8892             }
8893             if(!e.isConstant)
8894                exp.isConstant = false;
8895          }
8896
8897          if(!exp.expType)
8898             exp.expType = Dereference(exp.index.exp.expType);
8899          if(exp.expType)
8900             DeclareType(exp.expType, false, false);
8901          break;
8902       }
8903       case callExp:
8904       {
8905          Expression e;
8906          Type functionType;
8907          Type methodType = null;
8908          char name[1024];
8909          name[0] = '\0';
8910
8911          if(inCompiler)
8912          {
8913             PrintExpression(exp.call.exp,  name);
8914             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
8915             {
8916                //exp.call.exp.expType = null;
8917                PrintExpression(exp.call.exp,  name);
8918             }
8919          }
8920          if(exp.call.exp.type == identifierExp)
8921          {
8922             Expression idExp = exp.call.exp;
8923             Identifier id = idExp.identifier;
8924             if(!strcmp(id.string, "__builtin_frame_address"))
8925             {
8926                exp.expType = ProcessTypeString("void *", true);
8927                if(exp.call.arguments && exp.call.arguments->first)
8928                   ProcessExpressionType(exp.call.arguments->first);
8929                break;
8930             }
8931             else if(!strcmp(id.string, "__ENDIAN_PAD"))
8932             {
8933                exp.expType = ProcessTypeString("int", true);
8934                if(exp.call.arguments && exp.call.arguments->first)
8935                   ProcessExpressionType(exp.call.arguments->first);
8936                break;
8937             }
8938             else if(!strcmp(id.string, "Max") ||
8939                !strcmp(id.string, "Min") ||
8940                !strcmp(id.string, "Sgn") ||
8941                !strcmp(id.string, "Abs"))
8942             {
8943                Expression a = null;
8944                Expression b = null;
8945                Expression tempExp1 = null, tempExp2 = null;
8946                if((!strcmp(id.string, "Max") ||
8947                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
8948                {
8949                   a = exp.call.arguments->first;
8950                   b = exp.call.arguments->last;
8951                   tempExp1 = a;
8952                   tempExp2 = b;
8953                }
8954                else if(exp.call.arguments->count == 1)
8955                {
8956                   a = exp.call.arguments->first;
8957                   tempExp1 = a;
8958                }
8959
8960                if(a)
8961                {
8962                   exp.call.arguments->Clear();
8963                   idExp.identifier = null;
8964
8965                   FreeExpContents(exp);
8966
8967                   ProcessExpressionType(a);
8968                   if(b)
8969                      ProcessExpressionType(b);
8970
8971                   exp.type = bracketsExp;
8972                   exp.list = MkList();
8973
8974                   if(a.expType && (!b || b.expType))
8975                   {
8976                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
8977                      {
8978                         // Use the simpleStruct name/ids for now...
8979                         if(inCompiler)
8980                         {
8981                            OldList * specs = MkList();
8982                            OldList * decls = MkList();
8983                            Declaration decl;
8984                            char temp1[1024], temp2[1024];
8985
8986                            GetTypeSpecs(a.expType, specs);
8987
8988                            if(a && !a.isConstant && a.type != identifierExp)
8989                            {
8990                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
8991                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
8992                               tempExp1 = QMkExpId(temp1);
8993                               tempExp1.expType = a.expType;
8994                               if(a.expType)
8995                                  a.expType.refCount++;
8996                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
8997                            }
8998                            if(b && !b.isConstant && b.type != identifierExp)
8999                            {
9000                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9001                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9002                               tempExp2 = QMkExpId(temp2);
9003                               tempExp2.expType = b.expType;
9004                               if(b.expType)
9005                                  b.expType.refCount++;
9006                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9007                            }
9008
9009                            decl = MkDeclaration(specs, decls);
9010                            if(!curCompound.compound.declarations)
9011                               curCompound.compound.declarations = MkList();
9012                            curCompound.compound.declarations->Insert(null, decl);
9013                         }
9014                      }
9015                   }
9016
9017                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9018                   {
9019                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9020                      ListAdd(exp.list,
9021                         MkExpCondition(MkExpBrackets(MkListOne(
9022                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9023                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9024                      exp.expType = a.expType;
9025                      if(a.expType)
9026                         a.expType.refCount++;
9027                   }
9028                   else if(!strcmp(id.string, "Abs"))
9029                   {
9030                      ListAdd(exp.list,
9031                         MkExpCondition(MkExpBrackets(MkListOne(
9032                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9033                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9034                      exp.expType = a.expType;
9035                      if(a.expType)
9036                         a.expType.refCount++;
9037                   }
9038                   else if(!strcmp(id.string, "Sgn"))
9039                   {
9040                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9041                      ListAdd(exp.list,
9042                         MkExpCondition(MkExpBrackets(MkListOne(
9043                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9044                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9045                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9046                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9047                      exp.expType = ProcessTypeString("int", false);
9048                   }
9049
9050                   FreeExpression(tempExp1);
9051                   if(tempExp2) FreeExpression(tempExp2);
9052
9053                   FreeIdentifier(id);
9054                   break;
9055                }
9056             }
9057          }
9058
9059          {
9060             Type dummy
9061             {
9062                count = 1;
9063                refCount = 1;
9064             };
9065             if(!exp.call.exp.destType)
9066             {
9067                exp.call.exp.destType = dummy;
9068                dummy.refCount++;
9069             }
9070             ProcessExpressionType(exp.call.exp);
9071             if(exp.call.exp.destType == dummy)
9072             {
9073                FreeType(dummy);
9074                exp.call.exp.destType = null;
9075             }
9076             FreeType(dummy);
9077          }
9078
9079          // Check argument types against parameter types
9080          functionType = exp.call.exp.expType;
9081
9082          if(functionType && functionType.kind == TypeKind::methodType)
9083          {
9084             methodType = functionType;
9085             functionType = methodType.method.dataType;
9086
9087             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9088             // TOCHECK: Instead of doing this here could this be done per param?
9089             if(exp.call.exp.expType.usedClass)
9090             {
9091                char typeString[1024];
9092                typeString[0] = '\0';
9093                {
9094                   Symbol back = functionType.thisClass;
9095                   // Do not output class specifier here (thisclass was added to this)
9096                   functionType.thisClass = null;
9097                   PrintType(functionType, typeString, true, true);
9098                   functionType.thisClass = back;
9099                }
9100                if(strstr(typeString, "thisclass"))
9101                {
9102                   OldList * specs = MkList();
9103                   Declarator decl;
9104                   {
9105                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9106
9107                      decl = SpecDeclFromString(typeString, specs, null);
9108
9109                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9110                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9111                         exp.call.exp.expType.usedClass))
9112                         thisClassParams = false;
9113
9114                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9115                      {
9116                         Class backupThisClass = thisClass;
9117                         thisClass = exp.call.exp.expType.usedClass;
9118                         ProcessDeclarator(decl);
9119                         thisClass = backupThisClass;
9120                      }
9121
9122                      thisClassParams = true;
9123
9124                      functionType = ProcessType(specs, decl);
9125                      functionType.refCount = 0;
9126                      FinishTemplatesContext(context);
9127                   }
9128
9129                   FreeList(specs, FreeSpecifier);
9130                   FreeDeclarator(decl);
9131                 }
9132             }
9133          }
9134          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9135          {
9136             Type type = functionType.type;
9137             if(!functionType.refCount)
9138             {
9139                functionType.type = null;
9140                FreeType(functionType);
9141             }
9142             //methodType = functionType;
9143             functionType = type;
9144          }
9145          if(functionType && functionType.kind != TypeKind::functionType)
9146          {
9147             Compiler_Error($"called object %s is not a function\n", name);
9148          }
9149          else if(functionType)
9150          {
9151             bool emptyParams = false, noParams = false;
9152             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9153             Type type = functionType.params.first;
9154             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9155             int extra = 0;
9156             Location oldyylloc = yylloc;
9157
9158             if(!type) emptyParams = true;
9159
9160             // WORKING ON THIS:
9161             if(functionType.extraParam && e && functionType.thisClass)
9162             {
9163                e.destType = MkClassType(functionType.thisClass.string);
9164                e = e.next;
9165             }
9166
9167             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9168             // Fixed #141 by adding '&& !functionType.extraParam'
9169             if(!functionType.staticMethod && !functionType.extraParam)
9170             {
9171                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9172                   memberExp.member.exp.expType._class)
9173                {
9174                   type = MkClassType(memberExp.member.exp.expType._class.string);
9175                   if(e)
9176                   {
9177                      e.destType = type;
9178                      e = e.next;
9179                      type = functionType.params.first;
9180                   }
9181                   else
9182                      type.refCount = 0;
9183                }
9184                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9185                {
9186                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9187                   type.byReference = functionType.byReference;
9188                   type.typedByReference = functionType.typedByReference;
9189                   if(e)
9190                   {
9191                      // Allow manually passing a class for typed object
9192                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9193                         e = e.next;
9194                      e.destType = type;
9195                      e = e.next;
9196                      type = functionType.params.first;
9197                   }
9198                   else
9199                      type.refCount = 0;
9200                   //extra = 1;
9201                }
9202             }
9203
9204             if(type && type.kind == voidType)
9205             {
9206                noParams = true;
9207                if(!type.refCount) FreeType(type);
9208                type = null;
9209             }
9210
9211             for( ; e; e = e.next)
9212             {
9213                if(!type && !emptyParams)
9214                {
9215                   yylloc = e.loc;
9216                   if(methodType && methodType.methodClass)
9217                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9218                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9219                         noParams ? 0 : functionType.params.count);
9220                   else
9221                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9222                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9223                         noParams ? 0 : functionType.params.count);
9224                   break;
9225                }
9226
9227                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9228                {
9229                   Type templatedType = null;
9230                   Class _class = methodType.usedClass;
9231                   ClassTemplateParameter curParam = null;
9232                   int id = 0;
9233                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9234                   {
9235                      Class sClass;
9236                      for(sClass = _class; sClass; sClass = sClass.base)
9237                      {
9238                         if(sClass.templateClass) sClass = sClass.templateClass;
9239                         id = 0;
9240                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9241                         {
9242                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9243                            {
9244                               Class nextClass;
9245                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9246                               {
9247                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9248                                  id += nextClass.templateParams.count;
9249                               }
9250                               break;
9251                            }
9252                            id++;
9253                         }
9254                         if(curParam) break;
9255                      }
9256                   }
9257                   if(curParam && _class.templateArgs[id].dataTypeString)
9258                   {
9259                      ClassTemplateArgument arg = _class.templateArgs[id];
9260                      {
9261                         Context context = SetupTemplatesContext(_class);
9262
9263                         /*if(!arg.dataType)
9264                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9265                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9266                         FinishTemplatesContext(context);
9267                      }
9268                      e.destType = templatedType;
9269                      if(templatedType)
9270                      {
9271                         templatedType.passAsTemplate = true;
9272                         // templatedType.refCount++;
9273                      }
9274                   }
9275                   else
9276                   {
9277                      e.destType = type;
9278                      if(type) type.refCount++;
9279                   }
9280                }
9281                else
9282                {
9283                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9284                   {
9285                      e.destType = type.prev;
9286                      e.destType.refCount++;
9287                   }
9288                   else
9289                   {
9290                      e.destType = type;
9291                      if(type) type.refCount++;
9292                   }
9293                }
9294                // Don't reach the end for the ellipsis
9295                if(type && type.kind != ellipsisType)
9296                {
9297                   Type next = type.next;
9298                   if(!type.refCount) FreeType(type);
9299                   type = next;
9300                }
9301             }
9302
9303             if(type && type.kind != ellipsisType)
9304             {
9305                if(methodType && methodType.methodClass)
9306                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9307                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9308                      functionType.params.count + extra);
9309                else
9310                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9311                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9312                      functionType.params.count + extra);
9313             }
9314             yylloc = oldyylloc;
9315             if(type && !type.refCount) FreeType(type);
9316          }
9317          else
9318          {
9319             functionType = Type
9320             {
9321                refCount = 0;
9322                kind = TypeKind::functionType;
9323             };
9324
9325             if(exp.call.exp.type == identifierExp)
9326             {
9327                char * string = exp.call.exp.identifier.string;
9328                if(inCompiler)
9329                {
9330                   Symbol symbol;
9331                   Location oldyylloc = yylloc;
9332
9333                   yylloc = exp.call.exp.identifier.loc;
9334                   if(strstr(string, "__builtin_") == string)
9335                   {
9336                      if(exp.destType)
9337                      {
9338                         functionType.returnType = exp.destType;
9339                         exp.destType.refCount++;
9340                      }
9341                   }
9342                   else
9343                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9344                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9345                   globalContext.symbols.Add((BTNode)symbol);
9346                   if(strstr(symbol.string, "::"))
9347                      globalContext.hasNameSpace = true;
9348
9349                   yylloc = oldyylloc;
9350                }
9351             }
9352             else if(exp.call.exp.type == memberExp)
9353             {
9354                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9355                   exp.call.exp.member.member.string);*/
9356             }
9357             else
9358                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9359
9360             if(!functionType.returnType)
9361             {
9362                functionType.returnType = Type
9363                {
9364                   refCount = 1;
9365                   kind = intType;
9366                };
9367             }
9368          }
9369          if(functionType && functionType.kind == TypeKind::functionType)
9370          {
9371             exp.expType = functionType.returnType;
9372
9373             if(functionType.returnType)
9374                functionType.returnType.refCount++;
9375
9376             if(!functionType.refCount)
9377                FreeType(functionType);
9378          }
9379
9380          if(exp.call.arguments)
9381          {
9382             for(e = exp.call.arguments->first; e; e = e.next)
9383             {
9384                Type destType = e.destType;
9385                ProcessExpressionType(e);
9386             }
9387          }
9388          break;
9389       }
9390       case memberExp:
9391       {
9392          Type type;
9393          Location oldyylloc = yylloc;
9394          bool thisPtr;
9395          Expression checkExp = exp.member.exp;
9396          while(checkExp)
9397          {
9398             if(checkExp.type == castExp)
9399                checkExp = checkExp.cast.exp;
9400             else if(checkExp.type == bracketsExp)
9401                checkExp = checkExp.list ? checkExp.list->first : null;
9402             else
9403                break;
9404          }
9405
9406          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9407          exp.thisPtr = thisPtr;
9408
9409          // DOING THIS LATER NOW...
9410          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9411          {
9412             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9413             /* TODO: Name Space Fix ups
9414             if(!exp.member.member.classSym)
9415                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9416             */
9417          }
9418
9419          ProcessExpressionType(exp.member.exp);
9420          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9421             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9422          {
9423             exp.isConstant = false;
9424          }
9425          else
9426             exp.isConstant = exp.member.exp.isConstant;
9427          type = exp.member.exp.expType;
9428
9429          yylloc = exp.loc;
9430
9431          if(type && (type.kind == templateType))
9432          {
9433             Class _class = thisClass ? thisClass : currentClass;
9434             ClassTemplateParameter param = null;
9435             if(_class)
9436             {
9437                for(param = _class.templateParams.first; param; param = param.next)
9438                {
9439                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9440                      break;
9441                }
9442             }
9443             if(param && param.defaultArg.member)
9444             {
9445                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9446                if(argExp)
9447                {
9448                   Expression expMember = exp.member.exp;
9449                   Declarator decl;
9450                   OldList * specs = MkList();
9451                   char thisClassTypeString[1024];
9452
9453                   FreeIdentifier(exp.member.member);
9454
9455                   ProcessExpressionType(argExp);
9456
9457                   {
9458                      char * colon = strstr(param.defaultArg.memberString, "::");
9459                      if(colon)
9460                      {
9461                         char className[1024];
9462                         Class sClass;
9463
9464                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9465                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9466                      }
9467                      else
9468                         strcpy(thisClassTypeString, _class.fullName);
9469                   }
9470
9471                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9472
9473                   exp.expType = ProcessType(specs, decl);
9474                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9475                   {
9476                      Class expClass = exp.expType._class.registered;
9477                      Class cClass = null;
9478                      int c;
9479                      int paramCount = 0;
9480                      int lastParam = -1;
9481
9482                      char templateString[1024];
9483                      ClassTemplateParameter param;
9484                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9485                      for(cClass = expClass; cClass; cClass = cClass.base)
9486                      {
9487                         int p = 0;
9488                         for(param = cClass.templateParams.first; param; param = param.next)
9489                         {
9490                            int id = p;
9491                            Class sClass;
9492                            ClassTemplateArgument arg;
9493                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9494                            arg = expClass.templateArgs[id];
9495
9496                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9497                            {
9498                               ClassTemplateParameter cParam;
9499                               //int p = numParams - sClass.templateParams.count;
9500                               int p = 0;
9501                               Class nextClass;
9502                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9503
9504                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9505                               {
9506                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9507                                  {
9508                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9509                                     {
9510                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9511                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9512                                        break;
9513                                     }
9514                                  }
9515                               }
9516                            }
9517
9518                            {
9519                               char argument[256];
9520                               argument[0] = '\0';
9521                               /*if(arg.name)
9522                               {
9523                                  strcat(argument, arg.name.string);
9524                                  strcat(argument, " = ");
9525                               }*/
9526                               switch(param.type)
9527                               {
9528                                  case expression:
9529                                  {
9530                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9531                                     char expString[1024];
9532                                     OldList * specs = MkList();
9533                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9534                                     Expression exp;
9535                                     char * string = PrintHexUInt64(arg.expression.ui64);
9536                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9537                                     delete string;
9538
9539                                     ProcessExpressionType(exp);
9540                                     ComputeExpression(exp);
9541                                     expString[0] = '\0';
9542                                     PrintExpression(exp, expString);
9543                                     strcat(argument, expString);
9544                                     // delete exp;
9545                                     FreeExpression(exp);
9546                                     break;
9547                                  }
9548                                  case identifier:
9549                                  {
9550                                     strcat(argument, arg.member.name);
9551                                     break;
9552                                  }
9553                                  case TemplateParameterType::type:
9554                                  {
9555                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9556                                     {
9557                                        if(!strcmp(arg.dataTypeString, "thisclass"))
9558                                           strcat(argument, thisClassTypeString);
9559                                        else
9560                                           strcat(argument, arg.dataTypeString);
9561                                     }
9562                                     break;
9563                                  }
9564                               }
9565                               if(argument[0])
9566                               {
9567                                  if(paramCount) strcat(templateString, ", ");
9568                                  if(lastParam != p - 1)
9569                                  {
9570                                     strcat(templateString, param.name);
9571                                     strcat(templateString, " = ");
9572                                  }
9573                                  strcat(templateString, argument);
9574                                  paramCount++;
9575                                  lastParam = p;
9576                               }
9577                               p++;
9578                            }
9579                         }
9580                      }
9581                      {
9582                         int len = strlen(templateString);
9583                         if(templateString[len-1] == '>') templateString[len++] = ' ';
9584                         templateString[len++] = '>';
9585                         templateString[len++] = '\0';
9586                      }
9587                      {
9588                         Context context = SetupTemplatesContext(_class);
9589                         FreeType(exp.expType);
9590                         exp.expType = ProcessTypeString(templateString, false);
9591                         FinishTemplatesContext(context);
9592                      }
9593                   }
9594
9595                   // *([expType] *)(((byte *)[exp.member.exp]) + [argExp].member.offset)
9596                   exp.type = bracketsExp;
9597                   exp.list = MkListOne(MkExpOp(null, '*',
9598                   /*opExp;
9599                   exp.op.op = '*';
9600                   exp.op.exp1 = null;
9601                   exp.op.exp2 = */
9602                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
9603                      MkExpBrackets(MkListOne(
9604                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), expMember))),
9605                            '+',
9606                            MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
9607                            '+',
9608                            MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
9609
9610                            ));
9611                }
9612             }
9613             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
9614                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
9615             {
9616                type = ProcessTemplateParameterType(type.templateParameter);
9617             }
9618          }
9619          // TODO: *** This seems to be where we should add method support for all basic types ***
9620          if(type && (type.kind == templateType));
9621          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
9622                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
9623                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
9624                           (type.kind == pointerType && type.type.kind == charType)))
9625          {
9626             Identifier id = exp.member.member;
9627             TypeKind typeKind = type.kind;
9628             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
9629             if(typeKind == subClassType && exp.member.exp.type == classExp)
9630             {
9631                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
9632                typeKind = classType;
9633             }
9634
9635             if(id)
9636             {
9637                if(typeKind == intType || typeKind == enumType)
9638                   _class = eSystem_FindClass(privateModule, "int");
9639                else if(!_class)
9640                {
9641                   if(type.kind == classType && type._class && type._class.registered)
9642                   {
9643                      _class = type._class.registered;
9644                   }
9645                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
9646                   {
9647                      _class = FindClass("char *").registered;
9648                   }
9649                   else if(type.kind == pointerType)
9650                   {
9651                      _class = eSystem_FindClass(privateModule, "uintptr");
9652                      FreeType(exp.expType);
9653                      exp.expType = ProcessTypeString("uintptr", false);
9654                      exp.byReference = true;
9655                   }
9656                   else
9657                   {
9658                      char string[1024] = "";
9659                      Symbol classSym;
9660                      PrintTypeNoConst(type, string, false, true);
9661                      classSym = FindClass(string);
9662                      if(classSym) _class = classSym.registered;
9663                   }
9664                }
9665             }
9666
9667             if(_class && id)
9668             {
9669                /*bool thisPtr =
9670                   (exp.member.exp.type == identifierExp &&
9671                   !strcmp(exp.member.exp.identifier.string, "this"));*/
9672                Property prop = null;
9673                Method method = null;
9674                DataMember member = null;
9675                Property revConvert = null;
9676                ClassProperty classProp = null;
9677
9678                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
9679                   exp.member.memberType = propertyMember;
9680
9681                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
9682                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
9683
9684                if(typeKind != subClassType)
9685                {
9686                   // Prioritize data members over properties for "this"
9687                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
9688                   {
9689                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
9690                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
9691                      {
9692                         prop = eClass_FindProperty(_class, id.string, privateModule);
9693                         if(prop)
9694                            member = null;
9695                      }
9696                      if(!member && !prop)
9697                         prop = eClass_FindProperty(_class, id.string, privateModule);
9698                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
9699                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
9700                         exp.member.thisPtr = true;
9701                   }
9702                   // Prioritize properties over data members otherwise
9703                   else
9704                   {
9705                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
9706                      if(!id.classSym)
9707                      {
9708                         prop = eClass_FindProperty(_class, id.string, null);
9709                         if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
9710                            member = eClass_FindDataMember(_class, id.string, null, null, null);
9711                      }
9712
9713                      if(!prop && !member)
9714                      {
9715                         method = eClass_FindMethod(_class, id.string, null);
9716                         if(!method)
9717                         {
9718                            prop = eClass_FindProperty(_class, id.string, privateModule);
9719                            if(!id._class || !id._class.name || strcmp(id._class.name, "property"))
9720                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
9721                         }
9722                      }
9723
9724                      if(member && prop)
9725                      {
9726                         if(member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class))
9727                            prop = null;
9728                         else
9729                            member = null;
9730                      }
9731                   }
9732                }
9733                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
9734                   method = eClass_FindMethod(_class, id.string, privateModule);
9735                if(!prop && !member && !method)
9736                {
9737                   if(typeKind == subClassType)
9738                   {
9739                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
9740                      if(classProp)
9741                      {
9742                         exp.member.memberType = classPropertyMember;
9743                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
9744                      }
9745                      else
9746                      {
9747                         // Assume this is a class_data member
9748                         char structName[1024];
9749                         Identifier id = exp.member.member;
9750                         Expression classExp = exp.member.exp;
9751                         type.refCount++;
9752
9753                         FreeType(classExp.expType);
9754                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
9755
9756                         strcpy(structName, "__ecereClassData_");
9757                         FullClassNameCat(structName, type._class.string, false);
9758                         exp.type = pointerExp;
9759                         exp.member.member = id;
9760
9761                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
9762                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
9763                               MkExpBrackets(MkListOne(MkExpOp(
9764                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
9765                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
9766                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
9767                                  )));
9768
9769                         FreeType(type);
9770
9771                         ProcessExpressionType(exp);
9772                         return;
9773                      }
9774                   }
9775                   else
9776                   {
9777                      // Check for reverse conversion
9778                      // (Convert in an instantiation later, so that we can use
9779                      //  deep properties system)
9780                      Symbol classSym = FindClass(id.string);
9781                      if(classSym)
9782                      {
9783                         Class convertClass = classSym.registered;
9784                         if(convertClass)
9785                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
9786                      }
9787                   }
9788                }
9789
9790                if(prop)
9791                {
9792                   exp.member.memberType = propertyMember;
9793                   if(!prop.dataType)
9794                      ProcessPropertyType(prop);
9795                   exp.expType = prop.dataType;
9796                   if(prop.dataType) prop.dataType.refCount++;
9797                }
9798                else if(member)
9799                {
9800                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
9801                   {
9802                      FreeExpContents(exp);
9803                      exp.type = identifierExp;
9804                      exp.identifier = MkIdentifier("class");
9805                      ProcessExpressionType(exp);
9806                      return;
9807                   }
9808
9809                   exp.member.memberType = dataMember;
9810                   DeclareStruct(_class.fullName, false);
9811                   if(!member.dataType)
9812                   {
9813                      Context context = SetupTemplatesContext(_class);
9814                      member.dataType = ProcessTypeString(member.dataTypeString, false);
9815                      FinishTemplatesContext(context);
9816                   }
9817                   exp.expType = member.dataType;
9818                   if(member.dataType) member.dataType.refCount++;
9819                }
9820                else if(revConvert)
9821                {
9822                   exp.member.memberType = reverseConversionMember;
9823                   exp.expType = MkClassType(revConvert._class.fullName);
9824                }
9825                else if(method)
9826                {
9827                   //if(inCompiler)
9828                   {
9829                      /*if(id._class)
9830                      {
9831                         exp.type = identifierExp;
9832                         exp.identifier = exp.member.member;
9833                      }
9834                      else*/
9835                         exp.member.memberType = methodMember;
9836                   }
9837                   if(!method.dataType)
9838                      ProcessMethodType(method);
9839                   exp.expType = Type
9840                   {
9841                      refCount = 1;
9842                      kind = methodType;
9843                      method = method;
9844                   };
9845
9846                   // Tricky spot here... To use instance versus class virtual table
9847                   // Put it back to what it was... What did we break?
9848
9849                   // Had to put it back for overriding Main of Thread global instance
9850
9851                   //exp.expType.methodClass = _class;
9852                   exp.expType.methodClass = (id && id._class) ? _class : null;
9853
9854                   // Need the actual class used for templated classes
9855                   exp.expType.usedClass = _class;
9856                }
9857                else if(!classProp)
9858                {
9859                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
9860                   {
9861                      FreeExpContents(exp);
9862                      exp.type = identifierExp;
9863                      exp.identifier = MkIdentifier("class");
9864                      FreeType(exp.expType);
9865                      exp.expType = MkClassType("ecere::com::Class");
9866                      return;
9867                   }
9868                   yylloc = exp.member.member.loc;
9869                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
9870                   if(inCompiler)
9871                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
9872                }
9873
9874                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
9875                {
9876                   Class tClass;
9877
9878                   tClass = _class;
9879                   while(tClass && !tClass.templateClass) tClass = tClass.base;
9880
9881                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
9882                   {
9883                      int id = 0;
9884                      ClassTemplateParameter curParam = null;
9885                      Class sClass;
9886
9887                      for(sClass = tClass; sClass; sClass = sClass.base)
9888                      {
9889                         id = 0;
9890                         if(sClass.templateClass) sClass = sClass.templateClass;
9891                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9892                         {
9893                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
9894                            {
9895                               for(sClass = sClass.base; sClass; sClass = sClass.base)
9896                                  id += sClass.templateParams.count;
9897                               break;
9898                            }
9899                            id++;
9900                         }
9901                         if(curParam) break;
9902                      }
9903
9904                      if(curParam && tClass.templateArgs[id].dataTypeString)
9905                      {
9906                         ClassTemplateArgument arg = tClass.templateArgs[id];
9907                         Context context = SetupTemplatesContext(tClass);
9908                         /*if(!arg.dataType)
9909                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9910                         FreeType(exp.expType);
9911                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
9912                         if(exp.expType)
9913                         {
9914                            if(exp.expType.kind == thisClassType)
9915                            {
9916                               FreeType(exp.expType);
9917                               exp.expType = ReplaceThisClassType(_class);
9918                            }
9919
9920                            if(tClass.templateClass)
9921                               exp.expType.passAsTemplate = true;
9922                            //exp.expType.refCount++;
9923                            if(!exp.destType)
9924                            {
9925                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
9926                               //exp.destType.refCount++;
9927
9928                               if(exp.destType.kind == thisClassType)
9929                               {
9930                                  FreeType(exp.destType);
9931                                  exp.destType = ReplaceThisClassType(_class);
9932                               }
9933                            }
9934                         }
9935                         FinishTemplatesContext(context);
9936                      }
9937                   }
9938                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
9939                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
9940                   {
9941                      int id = 0;
9942                      ClassTemplateParameter curParam = null;
9943                      Class sClass;
9944
9945                      for(sClass = tClass; sClass; sClass = sClass.base)
9946                      {
9947                         id = 0;
9948                         if(sClass.templateClass) sClass = sClass.templateClass;
9949                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9950                         {
9951                            if(curParam.type == TemplateParameterType::type &&
9952                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
9953                            {
9954                               for(sClass = sClass.base; sClass; sClass = sClass.base)
9955                                  id += sClass.templateParams.count;
9956                               break;
9957                            }
9958                            id++;
9959                         }
9960                         if(curParam) break;
9961                      }
9962
9963                      if(curParam)
9964                      {
9965                         ClassTemplateArgument arg = tClass.templateArgs[id];
9966                         Context context = SetupTemplatesContext(tClass);
9967                         Type basicType;
9968                         /*if(!arg.dataType)
9969                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9970
9971                         basicType = ProcessTypeString(arg.dataTypeString, false);
9972                         if(basicType)
9973                         {
9974                            if(basicType.kind == thisClassType)
9975                            {
9976                               FreeType(basicType);
9977                               basicType = ReplaceThisClassType(_class);
9978                            }
9979
9980                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
9981                            if(tClass.templateClass)
9982                               basicType.passAsTemplate = true;
9983                            */
9984
9985                            FreeType(exp.expType);
9986
9987                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
9988                            //exp.expType.refCount++;
9989                            if(!exp.destType)
9990                            {
9991                               exp.destType = exp.expType;
9992                               exp.destType.refCount++;
9993                            }
9994
9995                            {
9996                               Expression newExp { };
9997                               OldList * specs = MkList();
9998                               Declarator decl;
9999                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10000                               *newExp = *exp;
10001                               if(exp.destType) exp.destType.refCount++;
10002                               if(exp.expType)  exp.expType.refCount++;
10003                               exp.type = castExp;
10004                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10005                               exp.cast.exp = newExp;
10006                               //FreeType(exp.expType);
10007                               //exp.expType = null;
10008                               //ProcessExpressionType(sourceExp);
10009                            }
10010                         }
10011                         FinishTemplatesContext(context);
10012                      }
10013                   }
10014                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10015                   {
10016                      Class expClass = exp.expType._class.registered;
10017                      if(expClass)
10018                      {
10019                         Class cClass = null;
10020                         int c;
10021                         int p = 0;
10022                         int paramCount = 0;
10023                         int lastParam = -1;
10024                         char templateString[1024];
10025                         ClassTemplateParameter param;
10026                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10027                         while(cClass != expClass)
10028                         {
10029                            Class sClass;
10030                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10031                            cClass = sClass;
10032
10033                            for(param = cClass.templateParams.first; param; param = param.next)
10034                            {
10035                               Class cClassCur = null;
10036                               int c;
10037                               int cp = 0;
10038                               ClassTemplateParameter paramCur = null;
10039                               ClassTemplateArgument arg;
10040                               while(cClassCur != tClass && !paramCur)
10041                               {
10042                                  Class sClassCur;
10043                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10044                                  cClassCur = sClassCur;
10045
10046                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10047                                  {
10048                                     if(!strcmp(paramCur.name, param.name))
10049                                     {
10050
10051                                        break;
10052                                     }
10053                                     cp++;
10054                                  }
10055                               }
10056                               if(paramCur && paramCur.type == TemplateParameterType::type)
10057                                  arg = tClass.templateArgs[cp];
10058                               else
10059                                  arg = expClass.templateArgs[p];
10060
10061                               {
10062                                  char argument[256];
10063                                  argument[0] = '\0';
10064                                  /*if(arg.name)
10065                                  {
10066                                     strcat(argument, arg.name.string);
10067                                     strcat(argument, " = ");
10068                                  }*/
10069                                  switch(param.type)
10070                                  {
10071                                     case expression:
10072                                     {
10073                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10074                                        char expString[1024];
10075                                        OldList * specs = MkList();
10076                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10077                                        Expression exp;
10078                                        char * string = PrintHexUInt64(arg.expression.ui64);
10079                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10080                                        delete string;
10081
10082                                        ProcessExpressionType(exp);
10083                                        ComputeExpression(exp);
10084                                        expString[0] = '\0';
10085                                        PrintExpression(exp, expString);
10086                                        strcat(argument, expString);
10087                                        // delete exp;
10088                                        FreeExpression(exp);
10089                                        break;
10090                                     }
10091                                     case identifier:
10092                                     {
10093                                        strcat(argument, arg.member.name);
10094                                        break;
10095                                     }
10096                                     case TemplateParameterType::type:
10097                                     {
10098                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10099                                           strcat(argument, arg.dataTypeString);
10100                                        break;
10101                                     }
10102                                  }
10103                                  if(argument[0])
10104                                  {
10105                                     if(paramCount) strcat(templateString, ", ");
10106                                     if(lastParam != p - 1)
10107                                     {
10108                                        strcat(templateString, param.name);
10109                                        strcat(templateString, " = ");
10110                                     }
10111                                     strcat(templateString, argument);
10112                                     paramCount++;
10113                                     lastParam = p;
10114                                  }
10115                               }
10116                               p++;
10117                            }
10118                         }
10119                         {
10120                            int len = strlen(templateString);
10121                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10122                            templateString[len++] = '>';
10123                            templateString[len++] = '\0';
10124                         }
10125
10126                         FreeType(exp.expType);
10127                         {
10128                            Context context = SetupTemplatesContext(tClass);
10129                            exp.expType = ProcessTypeString(templateString, false);
10130                            FinishTemplatesContext(context);
10131                         }
10132                      }
10133                   }
10134                }
10135             }
10136             else
10137                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10138          }
10139          else if(type && (type.kind == structType || type.kind == unionType))
10140          {
10141             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10142             if(memberType)
10143             {
10144                exp.expType = memberType;
10145                if(memberType)
10146                   memberType.refCount++;
10147             }
10148          }
10149          else
10150          {
10151             char expString[10240];
10152             expString[0] = '\0';
10153             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10154             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10155          }
10156
10157          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10158          {
10159             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10160             {
10161                Identifier id = exp.member.member;
10162                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10163                if(_class)
10164                {
10165                   FreeType(exp.expType);
10166                   exp.expType = ReplaceThisClassType(_class);
10167                }
10168             }
10169          }
10170          yylloc = oldyylloc;
10171          break;
10172       }
10173       // Convert x->y into (*x).y
10174       case pointerExp:
10175       {
10176          Type destType = exp.destType;
10177
10178          // DOING THIS LATER NOW...
10179          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10180          {
10181             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10182             /* TODO: Name Space Fix ups
10183             if(!exp.member.member.classSym)
10184                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10185             */
10186          }
10187
10188          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10189          exp.type = memberExp;
10190          if(destType)
10191             destType.count++;
10192          ProcessExpressionType(exp);
10193          if(destType)
10194             destType.count--;
10195          break;
10196       }
10197       case classSizeExp:
10198       {
10199          //ComputeExpression(exp);
10200
10201          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10202          if(classSym && classSym.registered)
10203          {
10204             if(classSym.registered.type == noHeadClass)
10205             {
10206                char name[1024];
10207                name[0] = '\0';
10208                DeclareStruct(classSym.string, false);
10209                FreeSpecifier(exp._class);
10210                exp.type = typeSizeExp;
10211                FullClassNameCat(name, classSym.string, false);
10212                exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10213             }
10214             else
10215             {
10216                if(classSym.registered.fixed)
10217                {
10218                   FreeSpecifier(exp._class);
10219                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10220                   exp.type = constantExp;
10221                }
10222                else
10223                {
10224                   char className[1024];
10225                   strcpy(className, "__ecereClass_");
10226                   FullClassNameCat(className, classSym.string, true);
10227                   MangleClassName(className);
10228
10229                   DeclareClass(classSym, className);
10230
10231                   FreeExpContents(exp);
10232                   exp.type = pointerExp;
10233                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10234                   exp.member.member = MkIdentifier("structSize");
10235                }
10236             }
10237          }
10238
10239          exp.expType = Type
10240          {
10241             refCount = 1;
10242             kind = intType;
10243          };
10244          // exp.isConstant = true;
10245          break;
10246       }
10247       case typeSizeExp:
10248       {
10249          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10250
10251          exp.expType = Type
10252          {
10253             refCount = 1;
10254             kind = intType;
10255          };
10256          exp.isConstant = true;
10257
10258          DeclareType(type, false, false);
10259          FreeType(type);
10260          break;
10261       }
10262       case castExp:
10263       {
10264          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10265          type.count = 1;
10266          FreeType(exp.cast.exp.destType);
10267          exp.cast.exp.destType = type;
10268          type.refCount++;
10269          ProcessExpressionType(exp.cast.exp);
10270          type.count = 0;
10271          exp.expType = type;
10272          //type.refCount++;
10273
10274          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10275          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10276          {
10277             void * prev = exp.prev, * next = exp.next;
10278             Type expType = exp.cast.exp.destType;
10279             Expression castExp = exp.cast.exp;
10280             Type destType = exp.destType;
10281
10282             if(expType) expType.refCount++;
10283
10284             //FreeType(exp.destType);
10285             FreeType(exp.expType);
10286             FreeTypeName(exp.cast.typeName);
10287
10288             *exp = *castExp;
10289             FreeType(exp.expType);
10290             FreeType(exp.destType);
10291
10292             exp.expType = expType;
10293             exp.destType = destType;
10294
10295             delete castExp;
10296
10297             exp.prev = prev;
10298             exp.next = next;
10299
10300          }
10301          else
10302          {
10303             exp.isConstant = exp.cast.exp.isConstant;
10304          }
10305          //FreeType(type);
10306          break;
10307       }
10308       case extensionInitializerExp:
10309       {
10310          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10311          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10312          // ProcessInitializer(exp.initializer.initializer, type);
10313          exp.expType = type;
10314          break;
10315       }
10316       case vaArgExp:
10317       {
10318          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10319          ProcessExpressionType(exp.vaArg.exp);
10320          exp.expType = type;
10321          break;
10322       }
10323       case conditionExp:
10324       {
10325          Expression e;
10326          exp.isConstant = true;
10327
10328          FreeType(exp.cond.cond.destType);
10329          exp.cond.cond.destType = MkClassType("bool");
10330          exp.cond.cond.destType.truth = true;
10331          ProcessExpressionType(exp.cond.cond);
10332          if(!exp.cond.cond.isConstant)
10333             exp.isConstant = false;
10334          for(e = exp.cond.exp->first; e; e = e.next)
10335          {
10336             if(!e.next)
10337             {
10338                FreeType(e.destType);
10339                e.destType = exp.destType;
10340                if(e.destType) e.destType.refCount++;
10341             }
10342             ProcessExpressionType(e);
10343             if(!e.next)
10344             {
10345                exp.expType = e.expType;
10346                if(e.expType) e.expType.refCount++;
10347             }
10348             if(!e.isConstant)
10349                exp.isConstant = false;
10350          }
10351
10352          FreeType(exp.cond.elseExp.destType);
10353          // Added this check if we failed to find an expType
10354          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10355
10356          // Reversed it...
10357          exp.cond.elseExp.destType = exp.destType ? exp.destType : exp.expType;
10358
10359          if(exp.cond.elseExp.destType)
10360             exp.cond.elseExp.destType.refCount++;
10361          ProcessExpressionType(exp.cond.elseExp);
10362
10363          // FIXED THIS: Was done before calling process on elseExp
10364          if(!exp.cond.elseExp.isConstant)
10365             exp.isConstant = false;
10366          break;
10367       }
10368       case extensionCompoundExp:
10369       {
10370          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10371          {
10372             Statement last = exp.compound.compound.statements->last;
10373             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10374             {
10375                ((Expression)last.expressions->last).destType = exp.destType;
10376                if(exp.destType)
10377                   exp.destType.refCount++;
10378             }
10379             ProcessStatement(exp.compound);
10380             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10381             if(exp.expType)
10382                exp.expType.refCount++;
10383          }
10384          break;
10385       }
10386       case classExp:
10387       {
10388          Specifier spec = exp._classExp.specifiers->first;
10389          if(spec && spec.type == nameSpecifier)
10390          {
10391             exp.expType = MkClassType(spec.name);
10392             exp.expType.kind = subClassType;
10393             exp.byReference = true;
10394          }
10395          else
10396          {
10397             exp.expType = MkClassType("ecere::com::Class");
10398             exp.byReference = true;
10399          }
10400          break;
10401       }
10402       case classDataExp:
10403       {
10404          Class _class = thisClass ? thisClass : currentClass;
10405          if(_class)
10406          {
10407             Identifier id = exp.classData.id;
10408             char structName[1024];
10409             Expression classExp;
10410             strcpy(structName, "__ecereClassData_");
10411             FullClassNameCat(structName, _class.fullName, false);
10412             exp.type = pointerExp;
10413             exp.member.member = id;
10414             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10415                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10416             else
10417                classExp = MkExpIdentifier(MkIdentifier("class"));
10418
10419             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10420                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10421                   MkExpBrackets(MkListOne(MkExpOp(
10422                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10423                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10424                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10425                      )));
10426
10427             ProcessExpressionType(exp);
10428             return;
10429          }
10430          break;
10431       }
10432       case arrayExp:
10433       {
10434          Type type = null;
10435          char * typeString = null;
10436          char typeStringBuf[1024];
10437          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
10438             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
10439          {
10440             Class templateClass = exp.destType._class.registered;
10441             typeString = templateClass.templateArgs[2].dataTypeString;
10442          }
10443          else if(exp.list)
10444          {
10445             // Guess type from expressions in the array
10446             Expression e;
10447             for(e = exp.list->first; e; e = e.next)
10448             {
10449                ProcessExpressionType(e);
10450                if(e.expType)
10451                {
10452                   if(!type) { type = e.expType; type.refCount++; }
10453                   else
10454                   {
10455                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
10456                      if(!MatchTypeExpression(e, type, null, false))
10457                      {
10458                         FreeType(type);
10459                         type = e.expType;
10460                         e.expType = null;
10461
10462                         e = exp.list->first;
10463                         ProcessExpressionType(e);
10464                         if(e.expType)
10465                         {
10466                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
10467                            if(!MatchTypeExpression(e, type, null, false))
10468                            {
10469                               FreeType(e.expType);
10470                               e.expType = null;
10471                               FreeType(type);
10472                               type = null;
10473                               break;
10474                            }
10475                         }
10476                      }
10477                   }
10478                   if(e.expType)
10479                   {
10480                      FreeType(e.expType);
10481                      e.expType = null;
10482                   }
10483                }
10484             }
10485             if(type)
10486             {
10487                typeStringBuf[0] = '\0';
10488                PrintTypeNoConst(type, typeStringBuf, false, true);
10489                typeString = typeStringBuf;
10490                FreeType(type);
10491                type = null;
10492             }
10493          }
10494          if(typeString)
10495          {
10496             /*
10497             (Container)& (struct BuiltInContainer)
10498             {
10499                ._vTbl = class(BuiltInContainer)._vTbl,
10500                ._class = class(BuiltInContainer),
10501                .refCount = 0,
10502                .data = (int[]){ 1, 7, 3, 4, 5 },
10503                .count = 5,
10504                .type = class(int),
10505             }
10506             */
10507             char templateString[1024];
10508             OldList * initializers = MkList();
10509             OldList * structInitializers = MkList();
10510             OldList * specs = MkList();
10511             Expression expExt;
10512             Declarator decl = SpecDeclFromString(typeString, specs, null);
10513             sprintf(templateString, "Container<%s>", typeString);
10514
10515             if(exp.list)
10516             {
10517                Expression e;
10518                type = ProcessTypeString(typeString, false);
10519                while(e = exp.list->first)
10520                {
10521                   exp.list->Remove(e);
10522                   e.destType = type;
10523                   type.refCount++;
10524                   ProcessExpressionType(e);
10525                   ListAdd(initializers, MkInitializerAssignment(e));
10526                }
10527                FreeType(type);
10528                delete exp.list;
10529             }
10530
10531             DeclareStruct("ecere::com::BuiltInContainer", false);
10532
10533             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
10534                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10535             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
10536                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10537             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
10538                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10539             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
10540                MkTypeName(specs, MkDeclaratorArray(decl, null)),
10541                MkInitializerList(initializers))));
10542                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10543             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
10544                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10545             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
10546                ProcessExpressionType(((Initializer)structInitializers->last).exp);
10547             exp.expType = ProcessTypeString(templateString, false);
10548             exp.type = bracketsExp;
10549             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
10550                MkExpOp(null, '&',
10551                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
10552                   MkInitializerList(structInitializers)))));
10553             ProcessExpressionType(expExt);
10554          }
10555          else
10556          {
10557             exp.expType = ProcessTypeString("Container", false);
10558             Compiler_Error($"Couldn't determine type of array elements\n");
10559          }
10560          break;
10561       }
10562    }
10563
10564    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
10565    {
10566       FreeType(exp.expType);
10567       exp.expType = ReplaceThisClassType(thisClass);
10568    }
10569
10570    // Resolve structures here
10571    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
10572    {
10573       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
10574       // TODO: Fix members reference...
10575       if(symbol)
10576       {
10577          if(exp.expType.kind != enumType)
10578          {
10579             Type member;
10580             String enumName = CopyString(exp.expType.enumName);
10581
10582             // Fixed a memory leak on self-referencing C structs typedefs
10583             // by instantiating a new type rather than simply copying members
10584             // into exp.expType
10585             FreeType(exp.expType);
10586             exp.expType = Type { };
10587             exp.expType.kind = symbol.type.kind;
10588             exp.expType.refCount++;
10589             exp.expType.enumName = enumName;
10590
10591             exp.expType.members = symbol.type.members;
10592             for(member = symbol.type.members.first; member; member = member.next)
10593                member.refCount++;
10594          }
10595          else
10596          {
10597             NamedLink member;
10598             for(member = symbol.type.members.first; member; member = member.next)
10599             {
10600                NamedLink value { name = CopyString(member.name) };
10601                exp.expType.members.Add(value);
10602             }
10603          }
10604       }
10605    }
10606
10607    yylloc = exp.loc;
10608    if(exp.destType && (exp.destType.kind == voidType || exp.destType.kind == dummyType) );
10609    else if(exp.destType && !exp.destType.keepCast)
10610    {
10611       if(!CheckExpressionType(exp, exp.destType, false))
10612       {
10613          if(!exp.destType.count || unresolved)
10614          {
10615             if(!exp.expType)
10616             {
10617                yylloc = exp.loc;
10618                if(exp.destType.kind != ellipsisType)
10619                {
10620                   char type2[1024];
10621                   type2[0] = '\0';
10622                   if(inCompiler)
10623                   {
10624                      char expString[10240];
10625                      expString[0] = '\0';
10626
10627                      PrintType(exp.destType, type2, false, true);
10628
10629                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10630                      if(unresolved)
10631                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
10632                      else if(exp.type != dummyExp)
10633                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
10634                   }
10635                }
10636                else
10637                {
10638                   char expString[10240] ;
10639                   expString[0] = '\0';
10640                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10641
10642                   if(unresolved)
10643                      Compiler_Error($"unresolved identifier %s\n", expString);
10644                   else if(exp.type != dummyExp)
10645                      Compiler_Error($"couldn't determine type of %s\n", expString);
10646                }
10647             }
10648             else
10649             {
10650                char type1[1024];
10651                char type2[1024];
10652                type1[0] = '\0';
10653                type2[0] = '\0';
10654                if(inCompiler)
10655                {
10656                   PrintType(exp.expType, type1, false, true);
10657                   PrintType(exp.destType, type2, false, true);
10658                }
10659
10660                //CheckExpressionType(exp, exp.destType, false);
10661
10662                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
10663                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
10664                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
10665                else
10666                {
10667                   char expString[10240];
10668                   expString[0] = '\0';
10669                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10670
10671 #ifdef _DEBUG
10672                   CheckExpressionType(exp, exp.destType, false);
10673 #endif
10674                   // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
10675                   if(!sourceFile || (strcmp(sourceFile, "src\\lexer.ec") && strcmp(sourceFile, "src/lexer.ec") && strcmp(sourceFile, "src\\grammar.ec") && strcmp(sourceFile, "src/grammar.ec")))
10676                      Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
10677
10678                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
10679                   FreeType(exp.expType);
10680                   exp.destType.refCount++;
10681                   exp.expType = exp.destType;
10682                }
10683             }
10684          }
10685       }
10686       else if(exp.destType && exp.destType.kind == ellipsisType && exp.expType && exp.expType.passAsTemplate)
10687       {
10688          Expression newExp { };
10689          char typeString[1024];
10690          OldList * specs = MkList();
10691          Declarator decl;
10692
10693          typeString[0] = '\0';
10694
10695          *newExp = *exp;
10696
10697          if(exp.expType)  exp.expType.refCount++;
10698          if(exp.expType)  exp.expType.refCount++;
10699          exp.type = castExp;
10700          newExp.destType = exp.expType;
10701
10702          PrintType(exp.expType, typeString, false, false);
10703          decl = SpecDeclFromString(typeString, specs, null);
10704
10705          exp.cast.typeName = MkTypeName(specs, decl);
10706          exp.cast.exp = newExp;
10707       }
10708    }
10709    else if(unresolved)
10710    {
10711       if(exp.identifier._class && exp.identifier._class.name)
10712          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
10713       else if(exp.identifier.string && exp.identifier.string[0])
10714          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
10715    }
10716    else if(!exp.expType && exp.type != dummyExp)
10717    {
10718       char expString[10240];
10719       expString[0] = '\0';
10720       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10721       Compiler_Error($"couldn't determine type of %s\n", expString);
10722    }
10723
10724    // Let's try to support any_object & typed_object here:
10725    if(inCompiler)
10726       ApplyAnyObjectLogic(exp);
10727
10728    // Mark nohead classes as by reference, unless we're casting them to an integral type
10729    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
10730       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
10731          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
10732           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
10733    {
10734       exp.byReference = true;
10735    }
10736    yylloc = oldyylloc;
10737 }
10738
10739 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
10740 {
10741    // THIS CODE WILL FIND NEXT MEMBER...
10742    if(*curMember)
10743    {
10744       *curMember = (*curMember).next;
10745
10746       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
10747       {
10748          *curMember = subMemberStack[--(*subMemberStackPos)];
10749          *curMember = (*curMember).next;
10750       }
10751
10752       // SKIP ALL PROPERTIES HERE...
10753       while((*curMember) && (*curMember).isProperty)
10754          *curMember = (*curMember).next;
10755
10756       if(subMemberStackPos)
10757       {
10758          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
10759          {
10760             subMemberStack[(*subMemberStackPos)++] = *curMember;
10761
10762             *curMember = (*curMember).members.first;
10763             while(*curMember && (*curMember).isProperty)
10764                *curMember = (*curMember).next;
10765          }
10766       }
10767    }
10768    while(!*curMember)
10769    {
10770       if(!*curMember)
10771       {
10772          if(subMemberStackPos && *subMemberStackPos)
10773          {
10774             *curMember = subMemberStack[--(*subMemberStackPos)];
10775             *curMember = (*curMember).next;
10776          }
10777          else
10778          {
10779             Class lastCurClass = *curClass;
10780
10781             if(*curClass == _class) break;     // REACHED THE END
10782
10783             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
10784             *curMember = (*curClass).membersAndProperties.first;
10785          }
10786
10787          while((*curMember) && (*curMember).isProperty)
10788             *curMember = (*curMember).next;
10789          if(subMemberStackPos)
10790          {
10791             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
10792             {
10793                subMemberStack[(*subMemberStackPos)++] = *curMember;
10794
10795                *curMember = (*curMember).members.first;
10796                while(*curMember && (*curMember).isProperty)
10797                   *curMember = (*curMember).next;
10798             }
10799          }
10800       }
10801    }
10802 }
10803
10804
10805 static void ProcessInitializer(Initializer init, Type type)
10806 {
10807    switch(init.type)
10808    {
10809       case expInitializer:
10810          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
10811          {
10812             // TESTING THIS FOR SHUTTING = 0 WARNING
10813             if(init.exp && !init.exp.destType)
10814             {
10815                FreeType(init.exp.destType);
10816                init.exp.destType = type;
10817                if(type) type.refCount++;
10818             }
10819             if(init.exp)
10820             {
10821                ProcessExpressionType(init.exp);
10822                init.isConstant = init.exp.isConstant;
10823             }
10824             break;
10825          }
10826          else
10827          {
10828             Expression exp = init.exp;
10829             Instantiation inst = exp.instance;
10830             MembersInit members;
10831
10832             init.type = listInitializer;
10833             init.list = MkList();
10834
10835             if(inst.members)
10836             {
10837                for(members = inst.members->first; members; members = members.next)
10838                {
10839                   if(members.type == dataMembersInit)
10840                   {
10841                      MemberInit member;
10842                      for(member = members.dataMembers->first; member; member = member.next)
10843                      {
10844                         ListAdd(init.list, member.initializer);
10845                         member.initializer = null;
10846                      }
10847                   }
10848                   // Discard all MembersInitMethod
10849                }
10850             }
10851             FreeExpression(exp);
10852          }
10853       case listInitializer:
10854       {
10855          Initializer i;
10856          Type initializerType = null;
10857          Class curClass = null;
10858          DataMember curMember = null;
10859          DataMember subMemberStack[256];
10860          int subMemberStackPos = 0;
10861
10862          if(type && type.kind == arrayType)
10863             initializerType = Dereference(type);
10864          else if(type && (type.kind == structType || type.kind == unionType))
10865             initializerType = type.members.first;
10866
10867          for(i = init.list->first; i; i = i.next)
10868          {
10869             if(type && type.kind == classType && type._class && type._class.registered)
10870             {
10871                // 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)
10872                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
10873                // TODO: Generate error on initializing a private data member this way from another module...
10874                if(curMember)
10875                {
10876                   if(!curMember.dataType)
10877                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
10878                   initializerType = curMember.dataType;
10879                }
10880             }
10881             ProcessInitializer(i, initializerType);
10882             if(initializerType && type && (type.kind == structType || type.kind == unionType))
10883                initializerType = initializerType.next;
10884             if(!i.isConstant)
10885                init.isConstant = false;
10886          }
10887
10888          if(type && type.kind == arrayType)
10889             FreeType(initializerType);
10890
10891          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
10892          {
10893             Compiler_Error($"Assigning list initializer to non list\n");
10894          }
10895          break;
10896       }
10897    }
10898 }
10899
10900 static void ProcessSpecifier(Specifier spec, bool declareStruct)
10901 {
10902    switch(spec.type)
10903    {
10904       case baseSpecifier:
10905       {
10906          if(spec.specifier == THISCLASS)
10907          {
10908             if(thisClass)
10909             {
10910                spec.type = nameSpecifier;
10911                spec.name = ReplaceThisClass(thisClass);
10912                spec.symbol = FindClass(spec.name);
10913                ProcessSpecifier(spec, declareStruct);
10914             }
10915          }
10916          break;
10917       }
10918       case nameSpecifier:
10919       {
10920          Symbol symbol = FindType(curContext, spec.name);
10921          if(symbol)
10922             DeclareType(symbol.type, true, true);
10923          else if((symbol = spec.symbol /*FindClass(spec.name)*/) && symbol.registered && symbol.registered.type == structClass && declareStruct)
10924             DeclareStruct(spec.name, false);
10925          break;
10926       }
10927       case enumSpecifier:
10928       {
10929          Enumerator e;
10930          if(spec.list)
10931          {
10932             for(e = spec.list->first; e; e = e.next)
10933             {
10934                if(e.exp)
10935                   ProcessExpressionType(e.exp);
10936             }
10937          }
10938          break;
10939       }
10940       case structSpecifier:
10941       case unionSpecifier:
10942       {
10943          if(spec.definitions)
10944          {
10945             ClassDef def;
10946             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
10947             //if(symbol)
10948                ProcessClass(spec.definitions, symbol);
10949             /*else
10950             {
10951                for(def = spec.definitions->first; def; def = def.next)
10952                {
10953                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
10954                      ProcessDeclaration(def.decl);
10955                }
10956             }*/
10957          }
10958          break;
10959       }
10960       /*
10961       case classSpecifier:
10962       {
10963          Symbol classSym = FindClass(spec.name);
10964          if(classSym && classSym.registered && classSym.registered.type == structClass)
10965             DeclareStruct(spec.name, false);
10966          break;
10967       }
10968       */
10969    }
10970 }
10971
10972
10973 static void ProcessDeclarator(Declarator decl)
10974 {
10975    switch(decl.type)
10976    {
10977       case identifierDeclarator:
10978          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
10979          {
10980             FreeSpecifier(decl.identifier._class);
10981             decl.identifier._class = null;
10982          }
10983          break;
10984       case arrayDeclarator:
10985          if(decl.array.exp)
10986             ProcessExpressionType(decl.array.exp);
10987       case structDeclarator:
10988       case bracketsDeclarator:
10989       case functionDeclarator:
10990       case pointerDeclarator:
10991       case extendedDeclarator:
10992       case extendedDeclaratorEnd:
10993          if(decl.declarator)
10994             ProcessDeclarator(decl.declarator);
10995          if(decl.type == functionDeclarator)
10996          {
10997             Identifier id = GetDeclId(decl);
10998             if(id && id._class)
10999             {
11000                TypeName param
11001                {
11002                   qualifiers = MkListOne(id._class);
11003                   declarator = null;
11004                };
11005                if(!decl.function.parameters)
11006                   decl.function.parameters = MkList();
11007                decl.function.parameters->Insert(null, param);
11008                id._class = null;
11009             }
11010             if(decl.function.parameters)
11011             {
11012                TypeName param;
11013
11014                for(param = decl.function.parameters->first; param; param = param.next)
11015                {
11016                   if(param.qualifiers && param.qualifiers->first)
11017                   {
11018                      Specifier spec = param.qualifiers->first;
11019                      if(spec && spec.specifier == TYPED_OBJECT)
11020                      {
11021                         Declarator d = param.declarator;
11022                         TypeName newParam
11023                         {
11024                            qualifiers = MkListOne(MkSpecifier(VOID));
11025                            declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11026                         };
11027
11028                         FreeList(param.qualifiers, FreeSpecifier);
11029
11030                         param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11031                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11032
11033                         decl.function.parameters->Insert(param, newParam);
11034                         param = newParam;
11035                      }
11036                      else if(spec && spec.specifier == ANY_OBJECT)
11037                      {
11038                         Declarator d = param.declarator;
11039
11040                         FreeList(param.qualifiers, FreeSpecifier);
11041
11042                         param.qualifiers = MkListOne(MkSpecifier(VOID));
11043                         param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11044                      }
11045                      else if(spec.specifier == THISCLASS)
11046                      {
11047                         if(thisClass)
11048                         {
11049                            spec.type = nameSpecifier;
11050                            spec.name = ReplaceThisClass(thisClass);
11051                            spec.symbol = FindClass(spec.name);
11052                            ProcessSpecifier(spec, false);
11053                         }
11054                      }
11055                   }
11056
11057                   if(param.declarator)
11058                      ProcessDeclarator(param.declarator);
11059                }
11060             }
11061          }
11062          break;
11063    }
11064 }
11065
11066 static void ProcessDeclaration(Declaration decl)
11067 {
11068    yylloc = decl.loc;
11069    switch(decl.type)
11070    {
11071       case initDeclaration:
11072       {
11073          bool declareStruct = false;
11074          /*
11075          lineNum = decl.pos.line;
11076          column = decl.pos.col;
11077          */
11078
11079          if(decl.declarators)
11080          {
11081             InitDeclarator d;
11082
11083             for(d = decl.declarators->first; d; d = d.next)
11084             {
11085                Type type, subType;
11086                ProcessDeclarator(d.declarator);
11087
11088                type = ProcessType(decl.specifiers, d.declarator);
11089
11090                if(d.initializer)
11091                {
11092                   ProcessInitializer(d.initializer, type);
11093
11094                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11095
11096                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11097                      d.initializer.exp.type == instanceExp)
11098                   {
11099                      if(type.kind == classType && type._class ==
11100                         d.initializer.exp.expType._class)
11101                      {
11102                         Instantiation inst = d.initializer.exp.instance;
11103                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11104
11105                         d.initializer.exp.instance = null;
11106                         if(decl.specifiers)
11107                            FreeList(decl.specifiers, FreeSpecifier);
11108                         FreeList(decl.declarators, FreeInitDeclarator);
11109
11110                         d = null;
11111
11112                         decl.type = instDeclaration;
11113                         decl.inst = inst;
11114                      }
11115                   }
11116                }
11117                for(subType = type; subType;)
11118                {
11119                   if(subType.kind == classType)
11120                   {
11121                      declareStruct = true;
11122                      break;
11123                   }
11124                   else if(subType.kind == pointerType)
11125                      break;
11126                   else if(subType.kind == arrayType)
11127                      subType = subType.arrayType;
11128                   else
11129                      break;
11130                }
11131
11132                FreeType(type);
11133                if(!d) break;
11134             }
11135          }
11136
11137          if(decl.specifiers)
11138          {
11139             Specifier s;
11140             for(s = decl.specifiers->first; s; s = s.next)
11141             {
11142                ProcessSpecifier(s, declareStruct);
11143             }
11144          }
11145          break;
11146       }
11147       case instDeclaration:
11148       {
11149          ProcessInstantiationType(decl.inst);
11150          break;
11151       }
11152       case structDeclaration:
11153       {
11154          Specifier spec;
11155          Declarator d;
11156          bool declareStruct = false;
11157
11158          if(decl.declarators)
11159          {
11160             for(d = decl.declarators->first; d; d = d.next)
11161             {
11162                Type type = ProcessType(decl.specifiers, d.declarator);
11163                Type subType;
11164                ProcessDeclarator(d);
11165                for(subType = type; subType;)
11166                {
11167                   if(subType.kind == classType)
11168                   {
11169                      declareStruct = true;
11170                      break;
11171                   }
11172                   else if(subType.kind == pointerType)
11173                      break;
11174                   else if(subType.kind == arrayType)
11175                      subType = subType.arrayType;
11176                   else
11177                      break;
11178                }
11179                FreeType(type);
11180             }
11181          }
11182          if(decl.specifiers)
11183          {
11184             for(spec = decl.specifiers->first; spec; spec = spec.next)
11185                ProcessSpecifier(spec, declareStruct);
11186          }
11187          break;
11188       }
11189    }
11190 }
11191
11192 static FunctionDefinition curFunction;
11193
11194 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11195 {
11196    char propName[1024], propNameM[1024];
11197    char getName[1024], setName[1024];
11198    OldList * args;
11199
11200    DeclareProperty(prop, setName, getName);
11201
11202    // eInstance_FireWatchers(object, prop);
11203    strcpy(propName, "__ecereProp_");
11204    FullClassNameCat(propName, prop._class.fullName, false);
11205    strcat(propName, "_");
11206    // strcat(propName, prop.name);
11207    FullClassNameCat(propName, prop.name, true);
11208    MangleClassName(propName);
11209
11210    strcpy(propNameM, "__ecerePropM_");
11211    FullClassNameCat(propNameM, prop._class.fullName, false);
11212    strcat(propNameM, "_");
11213    // strcat(propNameM, prop.name);
11214    FullClassNameCat(propNameM, prop.name, true);
11215    MangleClassName(propNameM);
11216
11217    if(prop.isWatchable)
11218    {
11219       args = MkList();
11220       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11221       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11222       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11223
11224       args = MkList();
11225       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11226       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11227       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11228    }
11229
11230
11231    {
11232       args = MkList();
11233       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11234       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11235       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11236
11237       args = MkList();
11238       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11239       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11240       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11241    }
11242
11243    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11244       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11245       curFunction.propSet.fireWatchersDone = true;
11246 }
11247
11248 static void ProcessStatement(Statement stmt)
11249 {
11250    yylloc = stmt.loc;
11251    /*
11252    lineNum = stmt.pos.line;
11253    column = stmt.pos.col;
11254    */
11255    switch(stmt.type)
11256    {
11257       case labeledStmt:
11258          ProcessStatement(stmt.labeled.stmt);
11259          break;
11260       case caseStmt:
11261          // This expression should be constant...
11262          if(stmt.caseStmt.exp)
11263          {
11264             FreeType(stmt.caseStmt.exp.destType);
11265             stmt.caseStmt.exp.destType = curSwitchType;
11266             if(curSwitchType) curSwitchType.refCount++;
11267             ProcessExpressionType(stmt.caseStmt.exp);
11268             ComputeExpression(stmt.caseStmt.exp);
11269          }
11270          if(stmt.caseStmt.stmt)
11271             ProcessStatement(stmt.caseStmt.stmt);
11272          break;
11273       case compoundStmt:
11274       {
11275          if(stmt.compound.context)
11276          {
11277             Declaration decl;
11278             Statement s;
11279
11280             Statement prevCompound = curCompound;
11281             Context prevContext = curContext;
11282
11283             if(!stmt.compound.isSwitch)
11284                curCompound = stmt;
11285             curContext = stmt.compound.context;
11286
11287             if(stmt.compound.declarations)
11288             {
11289                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
11290                   ProcessDeclaration(decl);
11291             }
11292             if(stmt.compound.statements)
11293             {
11294                for(s = stmt.compound.statements->first; s; s = s.next)
11295                   ProcessStatement(s);
11296             }
11297
11298             curContext = prevContext;
11299             curCompound = prevCompound;
11300          }
11301          break;
11302       }
11303       case expressionStmt:
11304       {
11305          Expression exp;
11306          if(stmt.expressions)
11307          {
11308             for(exp = stmt.expressions->first; exp; exp = exp.next)
11309                ProcessExpressionType(exp);
11310          }
11311          break;
11312       }
11313       case ifStmt:
11314       {
11315          Expression exp;
11316
11317          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
11318          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
11319          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
11320          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
11321          {
11322             ProcessExpressionType(exp);
11323          }
11324          if(stmt.ifStmt.stmt)
11325             ProcessStatement(stmt.ifStmt.stmt);
11326          if(stmt.ifStmt.elseStmt)
11327             ProcessStatement(stmt.ifStmt.elseStmt);
11328          break;
11329       }
11330       case switchStmt:
11331       {
11332          Type oldSwitchType = curSwitchType;
11333          if(stmt.switchStmt.exp)
11334          {
11335             Expression exp;
11336             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
11337             {
11338                if(!exp.next)
11339                {
11340                   /*
11341                   Type destType
11342                   {
11343                      kind = intType;
11344                      refCount = 1;
11345                   };
11346                   e.exp.destType = destType;
11347                   */
11348
11349                   ProcessExpressionType(exp);
11350                }
11351                if(!exp.next)
11352                   curSwitchType = exp.expType;
11353             }
11354          }
11355          ProcessStatement(stmt.switchStmt.stmt);
11356          curSwitchType = oldSwitchType;
11357          break;
11358       }
11359       case whileStmt:
11360       {
11361          if(stmt.whileStmt.exp)
11362          {
11363             Expression exp;
11364
11365             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
11366             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
11367             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
11368             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
11369             {
11370                ProcessExpressionType(exp);
11371             }
11372          }
11373          if(stmt.whileStmt.stmt)
11374             ProcessStatement(stmt.whileStmt.stmt);
11375          break;
11376       }
11377       case doWhileStmt:
11378       {
11379          if(stmt.doWhile.exp)
11380          {
11381             Expression exp;
11382
11383             if(stmt.doWhile.exp->last)
11384             {
11385                FreeType(((Expression)stmt.doWhile.exp->last).destType);
11386                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
11387                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
11388             }
11389             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
11390             {
11391                ProcessExpressionType(exp);
11392             }
11393          }
11394          if(stmt.doWhile.stmt)
11395             ProcessStatement(stmt.doWhile.stmt);
11396          break;
11397       }
11398       case forStmt:
11399       {
11400          Expression exp;
11401          if(stmt.forStmt.init)
11402             ProcessStatement(stmt.forStmt.init);
11403
11404          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
11405          {
11406             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
11407             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
11408             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
11409          }
11410
11411          if(stmt.forStmt.check)
11412             ProcessStatement(stmt.forStmt.check);
11413          if(stmt.forStmt.increment)
11414          {
11415             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
11416                ProcessExpressionType(exp);
11417          }
11418
11419          if(stmt.forStmt.stmt)
11420             ProcessStatement(stmt.forStmt.stmt);
11421          break;
11422       }
11423       case forEachStmt:
11424       {
11425          Identifier id = stmt.forEachStmt.id;
11426          OldList * exp = stmt.forEachStmt.exp;
11427          OldList * filter = stmt.forEachStmt.filter;
11428          Statement block = stmt.forEachStmt.stmt;
11429          char iteratorType[1024];
11430          Type source;
11431          Expression e;
11432          bool isBuiltin = exp && exp->last &&
11433             (((Expression)exp->last).type == ExpressionType::arrayExp ||
11434               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
11435          Expression arrayExp;
11436          char * typeString = null;
11437          int builtinCount = 0;
11438
11439          for(e = exp ? exp->first : null; e; e = e.next)
11440          {
11441             if(!e.next)
11442             {
11443                FreeType(e.destType);
11444                e.destType = ProcessTypeString("Container", false);
11445             }
11446             if(!isBuiltin || e.next)
11447                ProcessExpressionType(e);
11448          }
11449
11450          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
11451          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
11452             eClass_IsDerived(source._class.registered, containerClass)))
11453          {
11454             Class _class = source ? source._class.registered : null;
11455             Symbol symbol;
11456             Expression expIt = null;
11457             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false, isAVLTree = false;
11458             Class arrayClass = eSystem_FindClass(privateModule, "Array");
11459             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
11460             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
11461             stmt.type = compoundStmt;
11462
11463             stmt.compound.context = Context { };
11464             stmt.compound.context.parent = curContext;
11465             curContext = stmt.compound.context;
11466
11467             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
11468             {
11469                Class mapClass = eSystem_FindClass(privateModule, "Map");
11470                Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
11471                isCustomAVLTree = true;
11472                if(eClass_IsDerived(source._class.registered, avlTreeClass))
11473                   isAVLTree = true;
11474                else if(eClass_IsDerived(source._class.registered, mapClass))
11475                   isMap = true;
11476             }
11477             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
11478             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
11479             {
11480                Class listClass = eSystem_FindClass(privateModule, "List");
11481                isLinkList = true;
11482                isList = eClass_IsDerived(source._class.registered, listClass);
11483             }
11484
11485             if(isArray)
11486             {
11487                Declarator decl;
11488                OldList * specs = MkList();
11489                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
11490                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
11491                stmt.compound.declarations = MkListOne(
11492                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11493                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11494                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
11495                      MkInitializerAssignment(MkExpBrackets(exp))))));
11496             }
11497             else if(isBuiltin)
11498             {
11499                Type type = null;
11500                char typeStringBuf[1024];
11501
11502                // TODO: Merge this code?
11503                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
11504                if(((Expression)exp->last).type == castExp)
11505                {
11506                   TypeName typeName = ((Expression)exp->last).cast.typeName;
11507                   if(typeName)
11508                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
11509                }
11510
11511                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
11512                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
11513                   arrayExp.destType._class.registered.templateArgs)
11514                {
11515                   Class templateClass = arrayExp.destType._class.registered;
11516                   typeString = templateClass.templateArgs[2].dataTypeString;
11517                }
11518                else if(arrayExp.list)
11519                {
11520                   // Guess type from expressions in the array
11521                   Expression e;
11522                   for(e = arrayExp.list->first; e; e = e.next)
11523                   {
11524                      ProcessExpressionType(e);
11525                      if(e.expType)
11526                      {
11527                         if(!type) { type = e.expType; type.refCount++; }
11528                         else
11529                         {
11530                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11531                            if(!MatchTypeExpression(e, type, null, false))
11532                            {
11533                               FreeType(type);
11534                               type = e.expType;
11535                               e.expType = null;
11536
11537                               e = arrayExp.list->first;
11538                               ProcessExpressionType(e);
11539                               if(e.expType)
11540                               {
11541                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
11542                                  if(!MatchTypeExpression(e, type, null, false))
11543                                  {
11544                                     FreeType(e.expType);
11545                                     e.expType = null;
11546                                     FreeType(type);
11547                                     type = null;
11548                                     break;
11549                                  }
11550                               }
11551                            }
11552                         }
11553                         if(e.expType)
11554                         {
11555                            FreeType(e.expType);
11556                            e.expType = null;
11557                         }
11558                      }
11559                   }
11560                   if(type)
11561                   {
11562                      typeStringBuf[0] = '\0';
11563                      PrintType(type, typeStringBuf, false, true);
11564                      typeString = typeStringBuf;
11565                      FreeType(type);
11566                   }
11567                }
11568                if(typeString)
11569                {
11570                   OldList * initializers = MkList();
11571                   Declarator decl;
11572                   OldList * specs = MkList();
11573                   if(arrayExp.list)
11574                   {
11575                      Expression e;
11576
11577                      builtinCount = arrayExp.list->count;
11578                      type = ProcessTypeString(typeString, false);
11579                      while(e = arrayExp.list->first)
11580                      {
11581                         arrayExp.list->Remove(e);
11582                         e.destType = type;
11583                         type.refCount++;
11584                         ProcessExpressionType(e);
11585                         ListAdd(initializers, MkInitializerAssignment(e));
11586                      }
11587                      FreeType(type);
11588                      delete arrayExp.list;
11589                   }
11590                   decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
11591                   stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
11592                      MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
11593
11594                   ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
11595                      PlugDeclarator(
11596                         /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
11597                         ), MkInitializerList(initializers)))));
11598                   FreeList(exp, FreeExpression);
11599                }
11600                else
11601                {
11602                   arrayExp.expType = ProcessTypeString("Container", false);
11603                   Compiler_Error($"Couldn't determine type of array elements\n");
11604                }
11605
11606                /*
11607                Declarator decl;
11608                OldList * specs = MkList();
11609
11610                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
11611                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
11612                stmt.compound.declarations = MkListOne(
11613                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11614                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
11615                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
11616                      MkInitializerAssignment(MkExpBrackets(exp))))));
11617                */
11618             }
11619             else if(isLinkList && !isList)
11620             {
11621                Declarator decl;
11622                OldList * specs = MkList();
11623                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
11624                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11625                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11626                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
11627                      MkInitializerAssignment(MkExpBrackets(exp))))));
11628             }
11629             /*else if(isCustomAVLTree)
11630             {
11631                Declarator decl;
11632                OldList * specs = MkList();
11633                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
11634                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
11635                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
11636                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
11637                      MkInitializerAssignment(MkExpBrackets(exp))))));
11638             }*/
11639             else if(_class.templateArgs)
11640             {
11641                if(isMap)
11642                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
11643                else
11644                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
11645
11646                stmt.compound.declarations = MkListOne(
11647                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
11648                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
11649                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
11650             }
11651             symbol = FindSymbol(id.string, curContext, curContext, false, false);
11652
11653             if(block)
11654             {
11655                // Reparent sub-contexts in this statement
11656                switch(block.type)
11657                {
11658                   case compoundStmt:
11659                      if(block.compound.context)
11660                         block.compound.context.parent = stmt.compound.context;
11661                      break;
11662                   case ifStmt:
11663                      if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
11664                         block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
11665                      if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
11666                         block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
11667                      break;
11668                   case switchStmt:
11669                      if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
11670                         block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
11671                      break;
11672                   case whileStmt:
11673                      if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
11674                         block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
11675                      break;
11676                   case doWhileStmt:
11677                      if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
11678                         block.doWhile.stmt.compound.context.parent = stmt.compound.context;
11679                      break;
11680                   case forStmt:
11681                      if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
11682                         block.forStmt.stmt.compound.context.parent = stmt.compound.context;
11683                      break;
11684                   case forEachStmt:
11685                      if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
11686                         block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
11687                      break;
11688                   /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
11689                   case labeledStmt:
11690                   case caseStmt
11691                   case expressionStmt:
11692                   case gotoStmt:
11693                   case continueStmt:
11694                   case breakStmt
11695                   case returnStmt:
11696                   case asmStmt:
11697                   case badDeclarationStmt:
11698                   case fireWatchersStmt:
11699                   case stopWatchingStmt:
11700                   case watchStmt:
11701                   */
11702                }
11703             }
11704             if(filter)
11705             {
11706                block = MkIfStmt(filter, block, null);
11707             }
11708             if(isArray)
11709             {
11710                stmt.compound.statements = MkListOne(MkForStmt(
11711                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
11712                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
11713                      MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
11714                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
11715                   block));
11716               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11717               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11718               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11719             }
11720             else if(isBuiltin)
11721             {
11722                char count[128];
11723                //OldList * specs = MkList();
11724                // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
11725
11726                sprintf(count, "%d", builtinCount);
11727
11728                stmt.compound.statements = MkListOne(MkForStmt(
11729                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
11730                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
11731                      MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
11732                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
11733                   block));
11734
11735                /*
11736                Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
11737                stmt.compound.statements = MkListOne(MkForStmt(
11738                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
11739                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
11740                      MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
11741                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
11742                   block));
11743               */
11744               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11745               ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11746               ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11747             }
11748             else if(isLinkList && !isList)
11749             {
11750                Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
11751                Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
11752                if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
11753                   !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
11754                {
11755                   stmt.compound.statements = MkListOne(MkForStmt(
11756                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
11757                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
11758                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
11759                      block));
11760                }
11761                else
11762                {
11763                   OldList * specs = MkList();
11764                   Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
11765                   stmt.compound.statements = MkListOne(MkForStmt(
11766                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
11767                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
11768                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
11769                         MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
11770                            MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
11771                      block));
11772                }
11773                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11774                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11775                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11776             }
11777             /*else if(isCustomAVLTree)
11778             {
11779                stmt.compound.statements = MkListOne(MkForStmt(
11780                   MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
11781                      MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
11782                   MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
11783                   MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
11784                   block));
11785
11786                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
11787                ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
11788                ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
11789             }*/
11790             else
11791             {
11792                stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
11793                   MkIdentifier("Next")), null)), block));
11794             }
11795             ProcessExpressionType(expIt);
11796             if(stmt.compound.declarations->first)
11797                ProcessDeclaration(stmt.compound.declarations->first);
11798
11799             if(symbol)
11800                symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
11801
11802             ProcessStatement(stmt);
11803             curContext = stmt.compound.context.parent;
11804             break;
11805          }
11806          else
11807          {
11808             Compiler_Error($"Expression is not a container\n");
11809          }
11810          break;
11811       }
11812       case gotoStmt:
11813          break;
11814       case continueStmt:
11815          break;
11816       case breakStmt:
11817          break;
11818       case returnStmt:
11819       {
11820          Expression exp;
11821          if(stmt.expressions)
11822          {
11823             for(exp = stmt.expressions->first; exp; exp = exp.next)
11824             {
11825                if(!exp.next)
11826                {
11827                   if(curFunction && !curFunction.type)
11828                      curFunction.type = ProcessType(
11829                         curFunction.specifiers, curFunction.declarator);
11830                   FreeType(exp.destType);
11831                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
11832                   if(exp.destType) exp.destType.refCount++;
11833                }
11834                ProcessExpressionType(exp);
11835             }
11836          }
11837          break;
11838       }
11839       case badDeclarationStmt:
11840       {
11841          ProcessDeclaration(stmt.decl);
11842          break;
11843       }
11844       case asmStmt:
11845       {
11846          AsmField field;
11847          if(stmt.asmStmt.inputFields)
11848          {
11849             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
11850                if(field.expression)
11851                   ProcessExpressionType(field.expression);
11852          }
11853          if(stmt.asmStmt.outputFields)
11854          {
11855             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
11856                if(field.expression)
11857                   ProcessExpressionType(field.expression);
11858          }
11859          if(stmt.asmStmt.clobberedFields)
11860          {
11861             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
11862             {
11863                if(field.expression)
11864                   ProcessExpressionType(field.expression);
11865             }
11866          }
11867          break;
11868       }
11869       case watchStmt:
11870       {
11871          PropertyWatch propWatch;
11872          OldList * watches = stmt._watch.watches;
11873          Expression object = stmt._watch.object;
11874          Expression watcher = stmt._watch.watcher;
11875          if(watcher)
11876             ProcessExpressionType(watcher);
11877          if(object)
11878             ProcessExpressionType(object);
11879
11880          if(inCompiler)
11881          {
11882             if(watcher || thisClass)
11883             {
11884                External external = curExternal;
11885                Context context = curContext;
11886
11887                stmt.type = expressionStmt;
11888                stmt.expressions = MkList();
11889
11890                curExternal = external.prev;
11891
11892                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
11893                {
11894                   ClassFunction func;
11895                   char watcherName[1024];
11896                   Class watcherClass = watcher ?
11897                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
11898                   External createdExternal;
11899
11900                   // Create a declaration above
11901                   External externalDecl = MkExternalDeclaration(null);
11902                   ast->Insert(curExternal.prev, externalDecl);
11903
11904                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
11905                   if(propWatch.deleteWatch)
11906                      strcat(watcherName, "_delete");
11907                   else
11908                   {
11909                      Identifier propID;
11910                      for(propID = propWatch.properties->first; propID; propID = propID.next)
11911                      {
11912                         strcat(watcherName, "_");
11913                         strcat(watcherName, propID.string);
11914                      }
11915                   }
11916
11917                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
11918                   {
11919                      // TESTING THIS STUFF... BEWARE OF SYMBOL ID ISSUES
11920                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
11921                         //MkListOne(MkTypeName(MkListOne(MkSpecifier(VOID)), null))), null);
11922                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
11923                      ProcessClassFunctionBody(func, propWatch.compound);
11924                      propWatch.compound = null;
11925
11926                      //afterExternal = afterExternal ? afterExternal : curExternal;
11927
11928                      //createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal.prev);
11929                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
11930                      // TESTING THIS...
11931                      createdExternal.symbol.idCode = external.symbol.idCode;
11932
11933                      curExternal = createdExternal;
11934                      ProcessFunction(createdExternal.function);
11935
11936
11937                      // Create a declaration above
11938                      {
11939                         Declaration decl = MkDeclaration(CopyList(createdExternal.function.specifiers, CopySpecifier),
11940                            MkListOne(MkInitDeclarator(CopyDeclarator(createdExternal.function.declarator), null)));
11941                         externalDecl.declaration = decl;
11942                         if(decl.symbol && !decl.symbol.pointerExternal)
11943                            decl.symbol.pointerExternal = externalDecl;
11944                      }
11945
11946                      if(propWatch.deleteWatch)
11947                      {
11948                         OldList * args = MkList();
11949                         ListAdd(args, CopyExpression(object));
11950                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
11951                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
11952                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
11953                      }
11954                      else
11955                      {
11956                         Class _class = object.expType._class.registered;
11957                         Identifier propID;
11958
11959                         for(propID = propWatch.properties->first; propID; propID = propID.next)
11960                         {
11961                            char propName[1024];
11962                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
11963                            if(prop)
11964                            {
11965                               char getName[1024], setName[1024];
11966                               OldList * args = MkList();
11967
11968                               DeclareProperty(prop, setName, getName);
11969
11970                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
11971                               strcpy(propName, "__ecereProp_");
11972                               FullClassNameCat(propName, prop._class.fullName, false);
11973                               strcat(propName, "_");
11974                               // strcat(propName, prop.name);
11975                               FullClassNameCat(propName, prop.name, true);
11976
11977                               ListAdd(args, CopyExpression(object));
11978                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11979                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
11980                               ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
11981
11982                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
11983                            }
11984                            else
11985                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
11986                         }
11987                      }
11988                   }
11989                   else
11990                      Compiler_Error($"Invalid watched object\n");
11991                }
11992
11993                curExternal = external;
11994                curContext = context;
11995
11996                if(watcher)
11997                   FreeExpression(watcher);
11998                if(object)
11999                   FreeExpression(object);
12000                FreeList(watches, FreePropertyWatch);
12001             }
12002             else
12003                Compiler_Error($"No observer specified and not inside a _class\n");
12004          }
12005          else
12006          {
12007             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12008             {
12009                ProcessStatement(propWatch.compound);
12010             }
12011
12012          }
12013          break;
12014       }
12015       case fireWatchersStmt:
12016       {
12017          OldList * watches = stmt._watch.watches;
12018          Expression object = stmt._watch.object;
12019          Class _class;
12020          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12021          // printf("%X\n", watches);
12022          // printf("%X\n", stmt._watch.watches);
12023          if(object)
12024             ProcessExpressionType(object);
12025
12026          if(inCompiler)
12027          {
12028             _class = object ?
12029                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12030
12031             if(_class)
12032             {
12033                Identifier propID;
12034
12035                stmt.type = expressionStmt;
12036                stmt.expressions = MkList();
12037
12038                // Check if we're inside a property set
12039                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12040                {
12041                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12042                }
12043                else if(!watches)
12044                {
12045                   //Compiler_Error($"No property specified and not inside a property set\n");
12046                }
12047                if(watches)
12048                {
12049                   for(propID = watches->first; propID; propID = propID.next)
12050                   {
12051                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12052                      if(prop)
12053                      {
12054                         CreateFireWatcher(prop, object, stmt);
12055                      }
12056                      else
12057                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12058                   }
12059                }
12060                else
12061                {
12062                   // Fire all properties!
12063                   Property prop;
12064                   Class base;
12065                   for(base = _class; base; base = base.base)
12066                   {
12067                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12068                      {
12069                         if(prop.isProperty && prop.isWatchable)
12070                         {
12071                            CreateFireWatcher(prop, object, stmt);
12072                         }
12073                      }
12074                   }
12075                }
12076
12077                if(object)
12078                   FreeExpression(object);
12079                FreeList(watches, FreeIdentifier);
12080             }
12081             else
12082                Compiler_Error($"Invalid object specified and not inside a class\n");
12083          }
12084          break;
12085       }
12086       case stopWatchingStmt:
12087       {
12088          OldList * watches = stmt._watch.watches;
12089          Expression object = stmt._watch.object;
12090          Expression watcher = stmt._watch.watcher;
12091          Class _class;
12092          if(object)
12093             ProcessExpressionType(object);
12094          if(watcher)
12095             ProcessExpressionType(watcher);
12096          if(inCompiler)
12097          {
12098             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12099
12100             if(watcher || thisClass)
12101             {
12102                if(_class)
12103                {
12104                   Identifier propID;
12105
12106                   stmt.type = expressionStmt;
12107                   stmt.expressions = MkList();
12108
12109                   if(!watches)
12110                   {
12111                      OldList * args;
12112                      // eInstance_StopWatching(object, null, watcher);
12113                      args = MkList();
12114                      ListAdd(args, CopyExpression(object));
12115                      ListAdd(args, MkExpConstant("0"));
12116                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12117                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12118                   }
12119                   else
12120                   {
12121                      for(propID = watches->first; propID; propID = propID.next)
12122                      {
12123                         char propName[1024];
12124                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12125                         if(prop)
12126                         {
12127                            char getName[1024], setName[1024];
12128                            OldList * args = MkList();
12129
12130                            DeclareProperty(prop, setName, getName);
12131
12132                            // eInstance_StopWatching(object, prop, watcher);
12133                            strcpy(propName, "__ecereProp_");
12134                            FullClassNameCat(propName, prop._class.fullName, false);
12135                            strcat(propName, "_");
12136                            // strcat(propName, prop.name);
12137                            FullClassNameCat(propName, prop.name, true);
12138                            MangleClassName(propName);
12139
12140                            ListAdd(args, CopyExpression(object));
12141                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12142                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12143                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12144                         }
12145                         else
12146                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12147                      }
12148                   }
12149
12150                   if(object)
12151                      FreeExpression(object);
12152                   if(watcher)
12153                      FreeExpression(watcher);
12154                   FreeList(watches, FreeIdentifier);
12155                }
12156                else
12157                   Compiler_Error($"Invalid object specified and not inside a class\n");
12158             }
12159             else
12160                Compiler_Error($"No observer specified and not inside a class\n");
12161          }
12162          break;
12163       }
12164    }
12165 }
12166
12167 static void ProcessFunction(FunctionDefinition function)
12168 {
12169    Identifier id = GetDeclId(function.declarator);
12170    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12171    Type type = symbol ? symbol.type : null;
12172    Class oldThisClass = thisClass;
12173    Context oldTopContext = topContext;
12174
12175    yylloc = function.loc;
12176    // Process thisClass
12177
12178    if(type && type.thisClass)
12179    {
12180       Symbol classSym = type.thisClass;
12181       Class _class = type.thisClass.registered;
12182       char className[1024];
12183       char structName[1024];
12184       Declarator funcDecl;
12185       Symbol thisSymbol;
12186
12187       bool typedObject = false;
12188
12189       if(_class && !_class.base)
12190       {
12191          _class = currentClass;
12192          if(_class && !_class.symbol)
12193             _class.symbol = FindClass(_class.fullName);
12194          classSym = _class ? _class.symbol : null;
12195          typedObject = true;
12196       }
12197
12198       thisClass = _class;
12199
12200       if(inCompiler && _class)
12201       {
12202          if(type.kind == functionType)
12203          {
12204             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12205             {
12206                //TypeName param = symbol.type.params.first;
12207                Type param = symbol.type.params.first;
12208                symbol.type.params.Remove(param);
12209                //FreeTypeName(param);
12210                FreeType(param);
12211             }
12212             if(type.classObjectType != classPointer)
12213             {
12214                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12215                symbol.type.staticMethod = true;
12216                symbol.type.thisClass = null;
12217
12218                // HIGH DANGER: VERIFYING THIS...
12219                symbol.type.extraParam = false;
12220             }
12221          }
12222
12223          strcpy(className, "__ecereClass_");
12224          FullClassNameCat(className, _class.fullName, true);
12225
12226          MangleClassName(className);
12227
12228          structName[0] = 0;
12229          FullClassNameCat(structName, _class.fullName, false);
12230
12231          // [class] this
12232
12233
12234          funcDecl = GetFuncDecl(function.declarator);
12235          if(funcDecl)
12236          {
12237             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12238             {
12239                TypeName param = funcDecl.function.parameters->first;
12240                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12241                {
12242                   funcDecl.function.parameters->Remove(param);
12243                   FreeTypeName(param);
12244                }
12245             }
12246
12247             // DANGER: Watch for this... Check if it's a Conversion?
12248             // if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12249
12250             // WAS TRYING THIS FOR CONVERSION PROPERTIES ON NOHEAD CLASSES: if((_class.type == structClass) || function != (FunctionDefinition)symbol.externalSet)
12251             if(!function.propertyNoThis)
12252             {
12253                TypeName thisParam;
12254
12255                if(type.classObjectType != classPointer)
12256                {
12257                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12258                   if(!funcDecl.function.parameters)
12259                      funcDecl.function.parameters = MkList();
12260                   funcDecl.function.parameters->Insert(null, thisParam);
12261                }
12262
12263                if(typedObject)
12264                {
12265                   if(type.classObjectType != classPointer)
12266                   {
12267                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
12268                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
12269                   }
12270
12271                   thisParam = TypeName
12272                   {
12273                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
12274                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
12275                   };
12276                   funcDecl.function.parameters->Insert(null, thisParam);
12277                }
12278             }
12279          }
12280
12281          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12282          {
12283             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12284             funcDecl = GetFuncDecl(initDecl.declarator);
12285             if(funcDecl)
12286             {
12287                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12288                {
12289                   TypeName param = funcDecl.function.parameters->first;
12290                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12291                   {
12292                      funcDecl.function.parameters->Remove(param);
12293                      FreeTypeName(param);
12294                   }
12295                }
12296
12297                if(type.classObjectType != classPointer)
12298                {
12299                   // DANGER: Watch for this... Check if it's a Conversion?
12300                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12301                   {
12302                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12303
12304                      if(!funcDecl.function.parameters)
12305                         funcDecl.function.parameters = MkList();
12306                      funcDecl.function.parameters->Insert(null, thisParam);
12307                   }
12308                }
12309             }
12310          }
12311       }
12312
12313       // Add this to the context
12314       if(function.body)
12315       {
12316          if(type.classObjectType != classPointer)
12317          {
12318             thisSymbol = Symbol
12319             {
12320                string = CopyString("this");
12321                type = classSym ? MkClassType(classSym.string) : null; //_class.fullName);
12322             };
12323             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
12324
12325             if(typedObject && thisSymbol.type)
12326             {
12327                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
12328                thisSymbol.type.byReference = type.byReference;
12329                thisSymbol.type.typedByReference = type.byReference;
12330                /*
12331                thisSymbol = Symbol { string = CopyString("class") };
12332                function.body.compound.context.symbols.Add(thisSymbol);
12333                */
12334             }
12335          }
12336       }
12337
12338       // Pointer to class data
12339
12340       if(inCompiler && _class && (_class.type == normalClass /*|| _class.type == noHeadClass*/) && type.classObjectType != classPointer)
12341       {
12342          DataMember member = null;
12343          {
12344             Class base;
12345             for(base = _class; base && base.type != systemClass; base = base.next)
12346             {
12347                for(member = base.membersAndProperties.first; member; member = member.next)
12348                   if(!member.isProperty)
12349                      break;
12350                if(member)
12351                   break;
12352             }
12353          }
12354          for(member = _class.membersAndProperties.first; member; member = member.next)
12355             if(!member.isProperty)
12356                break;
12357          if(member)
12358          {
12359             char pointerName[1024];
12360
12361             Declaration decl;
12362             Initializer initializer;
12363             Expression exp, bytePtr;
12364
12365             strcpy(pointerName, "__ecerePointer_");
12366             FullClassNameCat(pointerName, _class.fullName, false);
12367             {
12368                char className[1024];
12369                strcpy(className, "__ecereClass_");
12370                FullClassNameCat(className, classSym.string, true);
12371                MangleClassName(className);
12372
12373                // Testing This
12374                DeclareClass(classSym, className);
12375             }
12376
12377             // ((byte *) this)
12378             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
12379
12380             if(_class.fixed)
12381             {
12382                char string[256];
12383                sprintf(string, "%d", _class.offset);
12384                exp = QBrackets(MkExpOp(bytePtr, '+', MkExpConstant(string)));
12385             }
12386             else
12387             {
12388                // ([bytePtr] + [className]->offset)
12389                exp = QBrackets(MkExpOp(bytePtr, '+',
12390                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
12391             }
12392
12393             // (this ? [exp] : 0)
12394             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
12395             exp.expType = Type
12396             {
12397                refCount = 1;
12398                kind = pointerType;
12399                type = Type { refCount = 1, kind = voidType };
12400             };
12401
12402             if(function.body)
12403             {
12404                yylloc = function.body.loc;
12405                // ([structName] *) [exp]
12406                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
12407                initializer = MkInitializerAssignment(
12408                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
12409
12410                // [structName] * [pointerName] = [initializer];
12411                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
12412
12413                {
12414                   Context prevContext = curContext;
12415                   curContext = function.body.compound.context;
12416
12417                   decl = MkDeclaration(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)),
12418                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
12419
12420                   curContext = prevContext;
12421                }
12422
12423                // WHY?
12424                decl.symbol = null;
12425
12426                if(!function.body.compound.declarations)
12427                   function.body.compound.declarations = MkList();
12428                function.body.compound.declarations->Insert(null, decl);
12429             }
12430          }
12431       }
12432
12433
12434       // Loop through the function and replace undeclared identifiers
12435       // which are a member of the class (methods, properties or data)
12436       // by "this.[member]"
12437    }
12438    else
12439       thisClass = null;
12440
12441    if(id)
12442    {
12443       FreeSpecifier(id._class);
12444       id._class = null;
12445
12446       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12447       {
12448          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12449          id = GetDeclId(initDecl.declarator);
12450
12451          FreeSpecifier(id._class);
12452          id._class = null;
12453       }
12454    }
12455    if(function.body)
12456       topContext = function.body.compound.context;
12457    {
12458       FunctionDefinition oldFunction = curFunction;
12459       curFunction = function;
12460       if(function.body)
12461          ProcessStatement(function.body);
12462
12463       // If this is a property set and no firewatchers has been done yet, add one here
12464       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
12465       {
12466          Statement prevCompound = curCompound;
12467          Context prevContext = curContext;
12468
12469          Statement fireWatchers = MkFireWatchersStmt(null, null);
12470          if(!function.body.compound.statements) function.body.compound.statements = MkList();
12471          ListAdd(function.body.compound.statements, fireWatchers);
12472
12473          curCompound = function.body;
12474          curContext = function.body.compound.context;
12475
12476          ProcessStatement(fireWatchers);
12477
12478          curContext = prevContext;
12479          curCompound = prevCompound;
12480
12481       }
12482
12483       curFunction = oldFunction;
12484    }
12485
12486    if(function.declarator)
12487    {
12488       ProcessDeclarator(function.declarator);
12489    }
12490
12491    topContext = oldTopContext;
12492    thisClass = oldThisClass;
12493 }
12494
12495 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
12496 static void ProcessClass(OldList definitions, Symbol symbol)
12497 {
12498    ClassDef def;
12499    External external = curExternal;
12500    Class regClass = symbol ? symbol.registered : null;
12501
12502    // Process all functions
12503    for(def = definitions.first; def; def = def.next)
12504    {
12505       if(def.type == functionClassDef)
12506       {
12507          if(def.function.declarator)
12508             curExternal = def.function.declarator.symbol.pointerExternal;
12509          else
12510             curExternal = external;
12511
12512          ProcessFunction((FunctionDefinition)def.function);
12513       }
12514       else if(def.type == declarationClassDef)
12515       {
12516          if(def.decl.type == instDeclaration)
12517          {
12518             thisClass = regClass;
12519             ProcessInstantiationType(def.decl.inst);
12520             thisClass = null;
12521          }
12522          // Testing this
12523          else
12524          {
12525             Class backThisClass = thisClass;
12526             if(regClass) thisClass = regClass;
12527             ProcessDeclaration(def.decl);
12528             thisClass = backThisClass;
12529          }
12530       }
12531       else if(def.type == defaultPropertiesClassDef && def.defProperties)
12532       {
12533          MemberInit defProperty;
12534
12535          // Add this to the context
12536          Symbol thisSymbol = Symbol
12537          {
12538             string = CopyString("this");
12539             type = regClass ? MkClassType(regClass.fullName) : null;
12540          };
12541          globalContext.symbols.Add((BTNode)thisSymbol);
12542
12543          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
12544          {
12545             thisClass = regClass;
12546             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
12547             thisClass = null;
12548          }
12549
12550          globalContext.symbols.Remove((BTNode)thisSymbol);
12551          FreeSymbol(thisSymbol);
12552       }
12553       else if(def.type == propertyClassDef && def.propertyDef)
12554       {
12555          PropertyDef prop = def.propertyDef;
12556
12557          // Add this to the context
12558          /*
12559          Symbol thisSymbol = Symbol { string = CopyString("this"), type = MkClassType(regClass.fullName) };
12560          globalContext.symbols.Add(thisSymbol);
12561          */
12562
12563          thisClass = regClass;
12564          if(prop.setStmt)
12565          {
12566             if(regClass)
12567             {
12568                Symbol thisSymbol
12569                {
12570                   string = CopyString("this");
12571                   type = MkClassType(regClass.fullName);
12572                };
12573                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
12574             }
12575
12576             curExternal = prop.symbol ? prop.symbol.externalSet : null;
12577             ProcessStatement(prop.setStmt);
12578          }
12579          if(prop.getStmt)
12580          {
12581             if(regClass)
12582             {
12583                Symbol thisSymbol
12584                {
12585                   string = CopyString("this");
12586                   type = MkClassType(regClass.fullName);
12587                };
12588                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
12589             }
12590
12591             curExternal = prop.symbol ? prop.symbol.externalGet : null;
12592             ProcessStatement(prop.getStmt);
12593          }
12594          if(prop.issetStmt)
12595          {
12596             if(regClass)
12597             {
12598                Symbol thisSymbol
12599                {
12600                   string = CopyString("this");
12601                   type = MkClassType(regClass.fullName);
12602                };
12603                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
12604             }
12605
12606             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
12607             ProcessStatement(prop.issetStmt);
12608          }
12609
12610          thisClass = null;
12611
12612          /*
12613          globalContext.symbols.Remove(thisSymbol);
12614          FreeSymbol(thisSymbol);
12615          */
12616       }
12617       else if(def.type == propertyWatchClassDef && def.propertyWatch)
12618       {
12619          PropertyWatch propertyWatch = def.propertyWatch;
12620
12621          thisClass = regClass;
12622          if(propertyWatch.compound)
12623          {
12624             Symbol thisSymbol
12625             {
12626                string = CopyString("this");
12627                type = regClass ? MkClassType(regClass.fullName) : null;
12628             };
12629
12630             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
12631
12632             curExternal = null;
12633             ProcessStatement(propertyWatch.compound);
12634          }
12635          thisClass = null;
12636       }
12637    }
12638 }
12639
12640 void DeclareFunctionUtil(String s)
12641 {
12642    GlobalFunction function = eSystem_FindFunction(privateModule, s);
12643    if(function)
12644    {
12645       char name[1024];
12646       name[0] = 0;
12647       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
12648          strcpy(name, "__ecereFunction_");
12649       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
12650       DeclareFunction(function, name);
12651    }
12652 }
12653
12654 void ComputeDataTypes()
12655 {
12656    External external;
12657    External temp { };
12658    External after = null;
12659
12660    currentClass = null;
12661
12662    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
12663
12664    for(external = ast->first; external; external = external.next)
12665    {
12666       if(external.type == declarationExternal)
12667       {
12668          Declaration decl = external.declaration;
12669          if(decl)
12670          {
12671             OldList * decls = decl.declarators;
12672             if(decls)
12673             {
12674                InitDeclarator initDecl = decls->first;
12675                if(initDecl)
12676                {
12677                   Declarator declarator = initDecl.declarator;
12678                   if(declarator && declarator.type == identifierDeclarator)
12679                   {
12680                      Identifier id = declarator.identifier;
12681                      if(id && id.string)
12682                      {
12683                         if(!strcmp(id.string, "uintptr_t") || !strcmp(id.string, "intptr_t") || !strcmp(id.string, "size_t") || !strcmp(id.string, "ssize_t"))
12684                         {
12685                            external.symbol.id = -1001, external.symbol.idCode = -1001;
12686                            after = external;
12687                         }
12688                      }
12689                   }
12690                }
12691             }
12692          }
12693        }
12694    }
12695
12696    temp.symbol = Symbol { id = -1000, idCode = -1000 };
12697    ast->Insert(after, temp);
12698    curExternal = temp;
12699
12700    DeclareFunctionUtil("eSystem_New");
12701    DeclareFunctionUtil("eSystem_New0");
12702    DeclareFunctionUtil("eSystem_Renew");
12703    DeclareFunctionUtil("eSystem_Renew0");
12704    DeclareFunctionUtil("eSystem_Delete");
12705    DeclareFunctionUtil("eClass_GetProperty");
12706    DeclareFunctionUtil("eInstance_FireSelfWatchers");
12707
12708    DeclareStruct("ecere::com::Class", false);
12709    DeclareStruct("ecere::com::Instance", false);
12710    DeclareStruct("ecere::com::Property", false);
12711    DeclareStruct("ecere::com::DataMember", false);
12712    DeclareStruct("ecere::com::Method", false);
12713    DeclareStruct("ecere::com::SerialBuffer", false);
12714    DeclareStruct("ecere::com::ClassTemplateArgument", false);
12715
12716    ast->Remove(temp);
12717
12718    for(external = ast->first; external; external = external.next)
12719    {
12720       afterExternal = curExternal = external;
12721       if(external.type == functionExternal)
12722       {
12723          currentClass = external.function._class;
12724          ProcessFunction(external.function);
12725       }
12726       // There shouldn't be any _class member access here anyways...
12727       else if(external.type == declarationExternal)
12728       {
12729          currentClass = null;
12730          ProcessDeclaration(external.declaration);
12731       }
12732       else if(external.type == classExternal)
12733       {
12734          ClassDefinition _class = external._class;
12735          currentClass = external.symbol.registered;
12736          if(_class.definitions)
12737          {
12738             ProcessClass(_class.definitions, _class.symbol);
12739          }
12740          if(inCompiler)
12741          {
12742             // Free class data...
12743             ast->Remove(external);
12744             delete external;
12745          }
12746       }
12747       else if(external.type == nameSpaceExternal)
12748       {
12749          thisNameSpace = external.id.string;
12750       }
12751    }
12752    currentClass = null;
12753    thisNameSpace = null;
12754
12755    delete temp.symbol;
12756    delete temp;
12757 }