compiler/libec (ide): Fixed crash on null expression type
[sdk] / compiler / libec / src / pass15.ec
1 import "ecdefs"
2
3 // UNTIL IMPLEMENTED IN GRAMMAR
4 #define ACCESS_CLASSDATA(_class, baseClass) \
5    (_class ? ((void *)(((char *)_class.data) + baseClass.offsetClass)) : null)
6
7 #define YYLTYPE Location
8 #include "grammar.h"
9
10 extern OldList * ast;
11 extern int returnCode;
12 extern Expression parsedExpression;
13 extern bool yydebug;
14 public void SetYydebug(bool b) { yydebug = b; }
15 extern bool echoOn;
16
17 void resetScanner();
18
19 // TODO: Reset this to 0 on reinitialization
20 int propWatcherID;
21
22 int expression_yyparse();
23 static Statement curCompound;
24 External curExternal, afterExternal;
25 static Type curSwitchType;
26 static Class currentClass;
27 Class thisClass;
28 public void SetThisClass(Class c) { thisClass = c; } public Class GetThisClass() { return thisClass; }
29 static char * thisNameSpace;
30 /*static */Class containerClass;
31 bool thisClassParams = true;
32
33 uint internalValueCounter;
34
35 #ifdef _DEBUG
36 Time findSymbolTotalTime;
37 #endif
38
39 // WARNING: PrintExpression CONCATENATES to string. Please initialize.
40 /*static */public void PrintExpression(Expression exp, char * string)
41 {
42    //if(inCompiler)
43    {
44       TempFile f { };
45       int count;
46       bool backOutputLineNumbers = outputLineNumbers;
47       outputLineNumbers = false;
48
49       if(exp)
50          OutputExpression(exp, f);
51       f.Seek(0, start);
52       count = strlen(string);
53       count += f.Read(string + count, 1, 1023);
54       string[count] = '\0';
55       delete f;
56
57       outputLineNumbers = backOutputLineNumbers;
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 && type1.isLong == type2.isLong)
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 (type1.type && type2.type && type1.type.constant != type2.type.constant) || 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%I64X"*/, 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    if(result > MAXINT || result < MININT)
229       sprintf(temp, FORMAT64DLL /*"%I64d"*/, result);
230    else
231       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
232    return CopyString(temp);
233 }
234
235 public char * PrintUInt64(uint64 result)
236 {
237    char temp[100];
238    if(result > MAXDWORD)
239       sprintf(temp, FORMAT64HEXLL /*"0x%I64XLL"*/, result);
240    else if(result > MAXINT)
241       sprintf(temp, FORMAT64HEX /*"0x%I64XLL"*/, result);
242    else
243       sprintf(temp, FORMAT64D /*"%I64d"*/, result);
244    return CopyString(temp);
245 }
246
247 public char * PrintHexUInt(uint64 result)
248 {
249    char temp[100];
250    if(result > MAXDWORD)
251       sprintf(temp, FORMAT64HEX /*"0x%I64xLL"*/, result);
252    else
253       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
254    if(result > MAXDWORD)
255       strcat(temp, "LL");
256    return CopyString(temp);
257 }
258
259 public char * PrintHexUInt64(uint64 result)
260 {
261    char temp[100];
262    if(result > MAXDWORD)
263       sprintf(temp, FORMAT64HEXLL /*"0x%I64xLL"*/, result);
264    else
265       sprintf(temp, FORMAT64HEX /*"0x%I64x"*/, result);
266    return CopyString(temp);
267 }
268
269 public char * PrintShort(short result)
270 {
271    char temp[100];
272    sprintf(temp, "%d", (unsigned short)result);
273    return CopyString(temp);
274 }
275
276 public char * PrintUShort(unsigned short result)
277 {
278    char temp[100];
279    if(result > 32767)
280       sprintf(temp, "0x%X", (int)result);
281    else
282       sprintf(temp, "%d", (int)result);
283    return CopyString(temp);
284 }
285
286 public char * PrintChar(char result)
287 {
288    char temp[100];
289    if(result > 0 && isprint(result))
290       sprintf(temp, "'%c'", result);
291    else if(result < 0)
292       sprintf(temp, "%d", (int)result);
293    else
294       //sprintf(temp, "%#X", result);
295       sprintf(temp, "0x%X", (unsigned char)result);
296    return CopyString(temp);
297 }
298
299 public char * PrintUChar(unsigned char result)
300 {
301    char temp[100];
302    sprintf(temp, "0x%X", result);
303    return CopyString(temp);
304 }
305
306 public char * PrintFloat(float result)
307 {
308    char temp[350];
309    if(result.isInf)
310    {
311       if(result.signBit)
312          strcpy(temp, "-inf");
313       else
314          strcpy(temp, "inf");
315    }
316    else if(result.isNan)
317    {
318       if(result.signBit)
319          strcpy(temp, "-nan");
320       else
321          strcpy(temp, "nan");
322    }
323    else
324       sprintf(temp, "%.16ff", result);
325    return CopyString(temp);
326 }
327
328 public char * PrintDouble(double result)
329 {
330    char temp[350];
331    if(result.isInf)
332    {
333       if(result.signBit)
334          strcpy(temp, "-inf");
335       else
336          strcpy(temp, "inf");
337    }
338    else if(result.isNan)
339    {
340       if(result.signBit)
341          strcpy(temp, "-nan");
342       else
343          strcpy(temp, "nan");
344    }
345    else
346       sprintf(temp, "%.16f", result);
347    return CopyString(temp);
348 }
349
350 ////////////////////////////////////////////////////////////////////////
351 ////////////////////////////////////////////////////////////////////////
352
353 //public Operand GetOperand(Expression exp);
354
355 #define GETVALUE(name, t) \
356    public bool GetOp##name(Operand op2, t * value2) \
357    {                                                        \
358       if(op2.kind == intType && op2.type.isSigned) *value2 = (t) op2.i; \
359       else if(op2.kind == intType) *value2 = (t) op2.ui;                 \
360       else if(op2.kind == int64Type && op2.type.isSigned) *value2 = (t) op2.i64; \
361       else if(op2.kind == int64Type) *value2 = (t) op2.ui64;                 \
362       else if(op2.kind == intSizeType && op2.type.isSigned) *value2 = (t) op2.i64; \
363       else if(op2.kind == intSizeType) *value2 = (t) op2.ui64; \
364       else if(op2.kind == intPtrType && op2.type.isSigned) *value2 = (t) op2.i64; \
365       else if(op2.kind == intPtrType) *value2 = (t) op2.ui64;                 \
366       else if(op2.kind == shortType && op2.type.isSigned) *value2 = (t) op2.s;   \
367       else if(op2.kind == shortType) *value2 = (t) op2.us;                        \
368       else if(op2.kind == charType && op2.type.isSigned) *value2 = (t) op2.c;    \
369       else if(op2.kind == _BoolType || op2.kind == charType) *value2 = (t) op2.uc; \
370       else if(op2.kind == floatType) *value2 = (t) op2.f;                         \
371       else if(op2.kind == doubleType) *value2 = (t) op2.d;                        \
372       else if(op2.kind == pointerType) *value2 = (t) op2.ui64;                    \
373       else                                                                          \
374          return false;                                                              \
375       return true;                                                                  \
376    } \
377    public bool Get##name(Expression exp, t * value2) \
378    {                                                        \
379       Operand op2 = GetOperand(exp);                        \
380       return GetOp##name(op2, value2); \
381    }
382
383 // To help the debugger currently not preprocessing...
384 #define HELP(x) x
385
386 GETVALUE(Int, HELP(int));
387 GETVALUE(UInt, HELP(unsigned int));
388 GETVALUE(Int64, HELP(int64));
389 GETVALUE(UInt64, HELP(uint64));
390 GETVALUE(IntPtr, HELP(intptr));
391 GETVALUE(UIntPtr, HELP(uintptr));
392 GETVALUE(IntSize, HELP(intsize));
393 GETVALUE(UIntSize, HELP(uintsize));
394 GETVALUE(Short, HELP(short));
395 GETVALUE(UShort, HELP(unsigned short));
396 GETVALUE(Char, HELP(char));
397 GETVALUE(UChar, HELP(unsigned char));
398 GETVALUE(Float, HELP(float));
399 GETVALUE(Double, HELP(double));
400
401 void ComputeExpression(Expression exp);
402
403 void ComputeClassMembers(Class _class, bool isMember)
404 {
405    DataMember member = isMember ? (DataMember) _class : null;
406    Context context = isMember ? null : SetupTemplatesContext(_class);
407    if(member || ((_class.type == bitClass || _class.type == normalClass || _class.type == structClass || _class.type == noHeadClass) &&
408                  (_class.type == bitClass || (!_class.structSize || _class.structSize == _class.offset)) && _class.computeSize))
409    {
410       int unionMemberOffset = 0;
411       int bitFields = 0;
412
413       /*
414       if(!member && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass) && _class.memberOffset && _class.memberOffset > _class.base.structSize)
415          _class.memberOffset = (_class.base && _class.base.type != systemClass) ? _class.base.structSize : 0;
416       */
417
418       if(member)
419       {
420          member.memberOffset = 0;
421          if(targetBits < sizeof(void *) * 8)
422             member.structAlignment = 0;
423       }
424       else if(targetBits < sizeof(void *) * 8)
425          _class.structAlignment = 0;
426
427       // Confusion here: non struct classes seem to have their memberOffset restart at 0 at each hierarchy level
428       if(!member && ((_class.type == normalClass || _class.type == noHeadClass) || (_class.type == structClass && _class.memberOffset && _class.memberOffset > _class.base.structSize)))
429          _class.memberOffset = (_class.base && _class.type == structClass) ? _class.base.structSize : 0;
430
431       if(!member && _class.destructionWatchOffset)
432          _class.memberOffset += sizeof(OldList);
433
434       // To avoid reentrancy...
435       //_class.structSize = -1;
436
437       {
438          DataMember dataMember;
439          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
440          {
441             if(!dataMember.isProperty)
442             {
443                if(dataMember.type == normalMember && dataMember.dataTypeString && !dataMember.dataType)
444                {
445                   dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
446                   /*if(!dataMember.dataType)
447                      dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
448                      */
449                }
450             }
451          }
452       }
453
454       {
455          DataMember dataMember;
456          for(dataMember = member ? member.members.first : _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
457          {
458             if(!dataMember.isProperty && (dataMember.type != normalMember || dataMember.dataTypeString))
459             {
460                if(!isMember && _class.type == bitClass && dataMember.dataType)
461                {
462                   BitMember bitMember = (BitMember) dataMember;
463                   uint64 mask = 0;
464                   int d;
465
466                   ComputeTypeSize(dataMember.dataType);
467
468                   if(bitMember.pos == -1) bitMember.pos = _class.memberOffset;
469                   if(!bitMember.size) bitMember.size = dataMember.dataType.size * 8;
470
471                   _class.memberOffset = bitMember.pos + bitMember.size;
472                   for(d = 0; d<bitMember.size; d++)
473                   {
474                      if(d)
475                         mask <<= 1;
476                      mask |= 1;
477                   }
478                   bitMember.mask = mask << bitMember.pos;
479                }
480                else if(dataMember.type == normalMember && dataMember.dataType)
481                {
482                   int size;
483                   int alignment = 0;
484
485                   // Prevent infinite recursion
486                   if(dataMember.dataType.kind != classType ||
487                      ((!dataMember.dataType._class || !dataMember.dataType._class.registered || dataMember.dataType._class.registered != _class ||
488                      _class.type != structClass)))
489                      ComputeTypeSize(dataMember.dataType);
490
491                   if(dataMember.dataType.bitFieldCount)
492                   {
493                      bitFields += dataMember.dataType.bitFieldCount;
494                      size = 0;
495                   }
496                   else
497                   {
498                      if(bitFields)
499                      {
500                         int size = (bitFields + 7) / 8;
501
502                         if(isMember)
503                         {
504                            // TESTING THIS PADDING CODE
505                            if(alignment)
506                            {
507                               member.structAlignment = Max(member.structAlignment, alignment);
508
509                               if(member.memberOffset % alignment)
510                                  member.memberOffset += alignment - (member.memberOffset % alignment);
511                            }
512
513                            dataMember.offset = member.memberOffset;
514                            if(member.type == unionMember)
515                               unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
516                            else
517                            {
518                               member.memberOffset += size;
519                            }
520                         }
521                         else
522                         {
523                            // TESTING THIS PADDING CODE
524                            if(alignment)
525                            {
526                               _class.structAlignment = Max(_class.structAlignment, alignment);
527
528                               if(_class.memberOffset % alignment)
529                                  _class.memberOffset += alignment - (_class.memberOffset % alignment);
530                            }
531
532                            dataMember.offset = _class.memberOffset;
533                            _class.memberOffset += size;
534                         }
535                         bitFields = 0;
536                      }
537                      size = dataMember.dataType.size;
538                      alignment = dataMember.dataType.alignment;
539                   }
540
541                   if(isMember)
542                   {
543                      // TESTING THIS PADDING CODE
544                      if(alignment)
545                      {
546                         member.structAlignment = Max(member.structAlignment, alignment);
547
548                         if(member.memberOffset % alignment)
549                            member.memberOffset += alignment - (member.memberOffset % alignment);
550                      }
551
552                      dataMember.offset = member.memberOffset;
553                      if(member.type == unionMember)
554                         unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
555                      else
556                      {
557                         member.memberOffset += size;
558                      }
559                   }
560                   else
561                   {
562                      // TESTING THIS PADDING CODE
563                      if(alignment)
564                      {
565                         _class.structAlignment = Max(_class.structAlignment, alignment);
566
567                         if(_class.memberOffset % alignment)
568                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
569                      }
570
571                      dataMember.offset = _class.memberOffset;
572                      _class.memberOffset += size;
573                   }
574                }
575                else
576                {
577                   int alignment;
578
579                   ComputeClassMembers((Class)dataMember, true);
580                   alignment = dataMember.structAlignment;
581
582                   if(isMember)
583                   {
584                      if(alignment)
585                      {
586                         if(member.memberOffset % alignment)
587                            member.memberOffset += alignment - (member.memberOffset % alignment);
588
589                         member.structAlignment = Max(member.structAlignment, alignment);
590                      }
591                      dataMember.offset = member.memberOffset;
592                      if(member.type == unionMember)
593                         unionMemberOffset = Max(unionMemberOffset, dataMember.memberOffset);
594                      else
595                         member.memberOffset += dataMember.memberOffset;
596                   }
597                   else
598                   {
599                      if(alignment)
600                      {
601                         if(_class.memberOffset % alignment)
602                            _class.memberOffset += alignment - (_class.memberOffset % alignment);
603                         _class.structAlignment = Max(_class.structAlignment, alignment);
604                      }
605                      dataMember.offset = _class.memberOffset;
606                      _class.memberOffset += dataMember.memberOffset;
607                   }
608                }
609             }
610          }
611          if(bitFields)
612          {
613             int alignment = 0;
614             int size = (bitFields + 7) / 8;
615
616             if(isMember)
617             {
618                // TESTING THIS PADDING CODE
619                if(alignment)
620                {
621                   member.structAlignment = Max(member.structAlignment, alignment);
622
623                   if(member.memberOffset % alignment)
624                      member.memberOffset += alignment - (member.memberOffset % alignment);
625                }
626
627                if(member.type == unionMember)
628                   unionMemberOffset = Max(unionMemberOffset, dataMember.dataType.size);
629                else
630                {
631                   member.memberOffset += size;
632                }
633             }
634             else
635             {
636                // TESTING THIS PADDING CODE
637                if(alignment)
638                {
639                   _class.structAlignment = Max(_class.structAlignment, alignment);
640
641                   if(_class.memberOffset % alignment)
642                      _class.memberOffset += alignment - (_class.memberOffset % alignment);
643                }
644                _class.memberOffset += size;
645             }
646             bitFields = 0;
647          }
648       }
649       if(member && member.type == unionMember)
650       {
651          member.memberOffset = unionMemberOffset;
652       }
653
654       if(!isMember)
655       {
656          /*if(_class.type == structClass)
657             _class.size = _class.memberOffset;
658          else
659          */
660
661          if(_class.type != bitClass)
662          {
663             int extra = 0;
664             if(_class.structAlignment)
665             {
666                if(_class.memberOffset % _class.structAlignment)
667                   extra += _class.structAlignment - (_class.memberOffset % _class.structAlignment);
668             }
669             _class.structSize = (_class.base ? (_class.base.templateClass ?
670                (_class.base.type == noHeadClass ? _class.base.templateClass.memberOffset : _class.base.templateClass.structSize) :
671                   (_class.base.type == noHeadClass ? _class.base.memberOffset : _class.base.structSize) ) : 0) + _class.memberOffset + extra;
672             if(!member)
673             {
674                Property prop;
675                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
676                {
677                   if(prop.isProperty && prop.isWatchable)
678                   {
679                      prop.watcherOffset = _class.structSize;
680                      _class.structSize += sizeof(OldList);
681                   }
682                }
683             }
684
685             // Fix Derivatives
686             {
687                OldLink derivative;
688                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
689                {
690                   Class deriv = derivative.data;
691
692                   if(deriv.computeSize)
693                   {
694                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
695                      deriv.offset = /*_class.offset + */(_class.type == noHeadClass ? _class.memberOffset : _class.structSize);
696                      deriv.memberOffset = 0;
697                      // ----------------------
698
699                      deriv.structSize = deriv.offset;
700
701                      ComputeClassMembers(deriv, false);
702                   }
703                }
704             }
705          }
706       }
707    }
708    if(context)
709       FinishTemplatesContext(context);
710 }
711
712 public void ComputeModuleClasses(Module module)
713 {
714    Class _class;
715    OldLink subModule;
716
717    for(subModule = module.modules.first; subModule; subModule = subModule.next)
718       ComputeModuleClasses(subModule.data);
719    for(_class = module.classes.first; _class; _class = _class.next)
720       ComputeClassMembers(_class, false);
721 }
722
723
724 public int ComputeTypeSize(Type type)
725 {
726    uint size = type ? type.size : 0;
727    if(!size && type && !type.computing)
728    {
729       type.computing = true;
730       switch(type.kind)
731       {
732          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
733          case charType: type.alignment = size = sizeof(char); break;
734          case intType: type.alignment = size = sizeof(int); break;
735          case int64Type: type.alignment = size = sizeof(int64); break;
736          case intPtrType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
737          case intSizeType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
738          case longType: type.alignment = size = sizeof(long); break;
739          case shortType: type.alignment = size = sizeof(short); break;
740          case floatType: type.alignment = size = sizeof(float); break;
741          case doubleType: type.alignment = size = sizeof(double); break;
742          case classType:
743          {
744             Class _class = type._class ? type._class.registered : null;
745
746             if(_class && _class.type == structClass)
747             {
748                // Ensure all members are properly registered
749                ComputeClassMembers(_class, false);
750                type.alignment = _class.structAlignment;
751                type.pointerAlignment = (bool)_class.pointerAlignment;
752                size = _class.structSize;
753                if(type.alignment && size % type.alignment)
754                   size += type.alignment - (size % type.alignment);
755
756             }
757             else if(_class && (_class.type == unitClass ||
758                    _class.type == enumClass ||
759                    _class.type == bitClass))
760             {
761                if(!_class.dataType)
762                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
763                size = type.alignment = ComputeTypeSize(_class.dataType);
764             }
765             else
766             {
767                size = type.alignment = targetBits / 8; // sizeof(Instance *);
768                type.pointerAlignment = true;
769             }
770             break;
771          }
772          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */ type.pointerAlignment = true; break;
773          case arrayType:
774             if(type.arraySizeExp)
775             {
776                ProcessExpressionType(type.arraySizeExp);
777                ComputeExpression(type.arraySizeExp);
778                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType &&
779                   type.arraySizeExp.expType.kind != shortType &&
780                   type.arraySizeExp.expType.kind != charType &&
781                   type.arraySizeExp.expType.kind != longType &&
782                   type.arraySizeExp.expType.kind != int64Type &&
783                   type.arraySizeExp.expType.kind != intSizeType &&
784                   type.arraySizeExp.expType.kind != intPtrType &&
785                   type.arraySizeExp.expType.kind != enumType &&
786                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
787                {
788                   Location oldLoc = yylloc;
789                   // bool isConstant = type.arraySizeExp.isConstant;
790                   char expression[10240];
791                   expression[0] = '\0';
792                   type.arraySizeExp.expType = null;
793                   yylloc = type.arraySizeExp.loc;
794                   if(inCompiler)
795                      PrintExpression(type.arraySizeExp, expression);
796                   Compiler_Error($"Array size not constant int (%s)\n", expression);
797                   yylloc = oldLoc;
798                }
799                GetInt(type.arraySizeExp, &type.arraySize);
800             }
801             else if(type.enumClass)
802             {
803                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
804                {
805                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
806                }
807                else
808                   type.arraySize = 0;
809             }
810             else
811             {
812                // Unimplemented auto size
813                type.arraySize = 0;
814             }
815
816             size = ComputeTypeSize(type.type) * type.arraySize;
817             if(type.type)
818             {
819                type.alignment = type.type.alignment;
820                type.pointerAlignment = type.type.pointerAlignment;
821             }
822
823             break;
824          case structType:
825          {
826             if(!type.members.first && type.enumName)
827             {
828                Symbol symbol = FindStruct(curContext, type.enumName);
829                if(symbol && symbol.type)
830                {
831                   ComputeTypeSize(symbol.type);
832                   size = symbol.type.size;
833                }
834             }
835             else
836             {
837                Type member;
838                for(member = type.members.first; member; member = member.next)
839                {
840                   uint addSize = ComputeTypeSize(member);
841
842                   member.offset = size;
843                   if(member.alignment && size % member.alignment)
844                      member.offset += member.alignment - (size % member.alignment);
845                   size = member.offset;
846
847                   if(member.pointerAlignment && type.size <= 4)
848                      type.pointerAlignment = true;
849                   else if(!member.pointerAlignment && member.alignment >= 8)
850                      type.pointerAlignment = false;
851
852                   type.alignment = Max(type.alignment, member.alignment);
853                   size += addSize;
854                }
855                if(type.alignment && size % type.alignment)
856                   size += type.alignment - (size % type.alignment);
857             }
858             break;
859          }
860          case unionType:
861          {
862             if(!type.members.first && type.enumName)
863             {
864                Symbol symbol = FindStruct(curContext, type.enumName);
865                if(symbol && symbol.type)
866                {
867                   ComputeTypeSize(symbol.type);
868                   size = symbol.type.size;
869                   type.alignment = symbol.type.alignment;
870                }
871             }
872             else
873             {
874                Type member;
875                for(member = type.members.first; member; member = member.next)
876                {
877                   uint addSize = ComputeTypeSize(member);
878
879                   member.offset = size;
880                   if(member.alignment && size % member.alignment)
881                      member.offset += member.alignment - (size % member.alignment);
882                   size = member.offset;
883
884                   if(member.pointerAlignment && type.size <= 4)
885                      type.pointerAlignment = true;
886                   else if(!member.pointerAlignment && member.alignment >= 8)
887                      type.pointerAlignment = false;
888
889                   type.alignment = Max(type.alignment, member.alignment);
890
891                   size = Max(size, addSize);
892                }
893                if(type.alignment && size % type.alignment)
894                   size += type.alignment - (size % type.alignment);
895             }
896             break;
897          }
898          case templateType:
899          {
900             TemplateParameter param = type.templateParameter;
901             Type baseType = ProcessTemplateParameterType(param);
902             if(baseType)
903             {
904                size = ComputeTypeSize(baseType);
905                type.alignment = baseType.alignment;
906                type.pointerAlignment = baseType.pointerAlignment;
907             }
908             else
909                type.alignment = size = sizeof(uint64);
910             break;
911          }
912          case enumType:
913          {
914             type.alignment = size = sizeof(enum { test });
915             break;
916          }
917          case thisClassType:
918          {
919             type.alignment = size = targetBits / 8; //sizeof(void *);
920             type.pointerAlignment = true;
921             break;
922          }
923       }
924       type.size = size;
925       type.computing = false;
926    }
927    return size;
928 }
929
930
931 /*static */int AddMembers(External neededBy, OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
932 {
933    // This function is in need of a major review when implementing private members etc.
934    DataMember topMember = isMember ? (DataMember) _class : null;
935    uint totalSize = 0;
936    uint maxSize = 0;
937    int alignment;
938    uint size;
939    DataMember member;
940    int anonID = 1;
941    Context context = isMember ? null : SetupTemplatesContext(_class);
942    if(addedPadding)
943       *addedPadding = false;
944
945    if(!isMember && _class.base)
946    {
947       maxSize = _class.structSize;
948       //if(_class.base.type != systemClass) // Commented out with new Instance _class
949       {
950          // DANGER: Testing this noHeadClass here...
951          if(_class.type == structClass || _class.type == noHeadClass)
952             /*totalSize = */AddMembers(neededBy, declarations, _class.base, false, &totalSize, topClass, null);
953          else
954          {
955             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
956             if(maxSize > baseSize)
957                maxSize -= baseSize;
958             else
959                maxSize = 0;
960          }
961       }
962    }
963
964    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
965    {
966       if(!member.isProperty)
967       {
968          switch(member.type)
969          {
970             case normalMember:
971             {
972                if(member.dataTypeString)
973                {
974                   OldList * specs = MkList(), * decls = MkList();
975                   Declarator decl;
976
977                   decl = SpecDeclFromString(member.dataTypeString, specs,
978                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
979                   ListAdd(decls, MkStructDeclarator(decl, null));
980                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
981
982                   if(!member.dataType)
983                      member.dataType = ProcessType(specs, decl);
984
985                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
986
987                   {
988                      Type type = ProcessType(specs, decl);
989                      DeclareType(neededBy, member.dataType, true, false);
990                      FreeType(type);
991                   }
992                   /*
993                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
994                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
995                      DeclareStruct(member.dataType._class.string, false);
996                   */
997
998                   ComputeTypeSize(member.dataType);
999                   size = member.dataType.size;
1000                   alignment = member.dataType.alignment;
1001
1002                   if(alignment)
1003                   {
1004                      if(totalSize % alignment)
1005                         totalSize += alignment - (totalSize % alignment);
1006                   }
1007                   totalSize += size;
1008                }
1009                break;
1010             }
1011             case unionMember:
1012             case structMember:
1013             {
1014                OldList * specs = MkList(), * list = MkList();
1015                char id[100];
1016                sprintf(id, "__anon%d", anonID++);
1017
1018                size = 0;
1019                AddMembers(neededBy, list, (Class)member, true, &size, topClass, null);
1020                ListAdd(specs,
1021                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
1022                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, MkListOne(MkDeclaratorIdentifier(MkIdentifier(id))),null)));
1023                alignment = member.structAlignment;
1024
1025                if(alignment)
1026                {
1027                   if(totalSize % alignment)
1028                      totalSize += alignment - (totalSize % alignment);
1029                }
1030                totalSize += size;
1031                break;
1032             }
1033          }
1034       }
1035    }
1036    if(retSize)
1037    {
1038       if(topMember && topMember.type == unionMember)
1039          *retSize = Max(*retSize, totalSize);
1040       else
1041          *retSize += totalSize;
1042    }
1043    else if(totalSize < maxSize && _class.type != systemClass)
1044    {
1045       int autoPadding = 0;
1046       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
1047          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
1048       if(totalSize + autoPadding < maxSize)
1049       {
1050          char sizeString[50];
1051          sprintf(sizeString, "%d", maxSize - totalSize);
1052          ListAdd(declarations,
1053             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
1054             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
1055          if(addedPadding)
1056             *addedPadding = true;
1057       }
1058    }
1059    if(context)
1060       FinishTemplatesContext(context);
1061    return topMember ? topMember.memberID : _class.memberID;
1062 }
1063
1064 static int DeclareMembers(External neededBy, Class _class, bool isMember)
1065 {
1066    DataMember topMember = isMember ? (DataMember) _class : null;
1067    DataMember member;
1068    Context context = isMember ? null : SetupTemplatesContext(_class);
1069
1070    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1071       DeclareMembers(neededBy, _class.base, false);
1072
1073    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1074    {
1075       if(!member.isProperty)
1076       {
1077          switch(member.type)
1078          {
1079             case normalMember:
1080             {
1081                if(!member.dataType && member.dataTypeString)
1082                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1083                if(member.dataType)
1084                   DeclareType(neededBy, member.dataType, true, false);
1085                break;
1086             }
1087             case unionMember:
1088             case structMember:
1089             {
1090                DeclareMembers(neededBy, (Class)member, true);
1091                break;
1092             }
1093          }
1094       }
1095    }
1096    if(context)
1097       FinishTemplatesContext(context);
1098
1099    return topMember ? topMember.memberID : _class.memberID;
1100 }
1101
1102 static void IdentifyAnonStructs(OldList/*<ClassDef>*/ *  definitions)
1103 {
1104    ClassDef def;
1105    int anonID = 1;
1106    for(def = definitions->first; def; def = def.next)
1107    {
1108       if(def.type == declarationClassDef)
1109       {
1110          Declaration decl = def.decl;
1111          if(decl && decl.specifiers)
1112          {
1113             Specifier spec;
1114             bool isStruct = false;
1115             for(spec = decl.specifiers->first; spec; spec = spec.next)
1116             {
1117                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1118                {
1119                   if(spec.definitions)
1120                      IdentifyAnonStructs(spec.definitions);
1121                   isStruct = true;
1122                }
1123             }
1124             if(isStruct)
1125             {
1126                Declarator d = null;
1127                if(decl.declarators)
1128                {
1129                   for(d = decl.declarators->first; d; d = d.next)
1130                   {
1131                      Identifier idDecl = GetDeclId(d);
1132                      if(idDecl)
1133                         break;
1134                   }
1135                }
1136                if(!d)
1137                {
1138                   char id[100];
1139                   sprintf(id, "__anon%d", anonID++);
1140                   if(!decl.declarators)
1141                      decl.declarators = MkList();
1142                   ListAdd(decl.declarators, MkDeclaratorIdentifier(MkIdentifier(id)));
1143                }
1144             }
1145          }
1146       }
1147    }
1148 }
1149
1150 External DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference)
1151 {
1152    return _DeclareStruct(neededBy, name, skipNoHead, needDereference, false);
1153 }
1154
1155 External _DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference, bool fwdDecl)
1156 {
1157    External external = null;
1158    Symbol classSym = FindClass(name);
1159    OldList * curDeclarations = null;
1160
1161    if(!inCompiler || !classSym) return null;
1162
1163    // We don't need any declaration for bit classes...
1164    if(classSym.registered &&
1165       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1166       return null;
1167
1168    if(!classSym.registered || (classSym.registered.type == normalClass && classSym.registered.structSize && classSym.registered.base && classSym.registered.base.base))
1169       _DeclareStruct(neededBy, "ecere::com::Instance", false, true, fwdDecl);
1170
1171    external = classSym.structExternal;
1172
1173    if(external && external.declaration)
1174    {
1175       Specifier spec;
1176       for(spec = external.declaration.specifiers ? external.declaration.specifiers->first : null; spec; spec = spec.next)
1177          if(spec.type == structSpecifier || spec.type == unionSpecifier)
1178          {
1179             curDeclarations = spec.definitions;
1180             break;
1181          }
1182    }
1183
1184    if(classSym.registered && !classSym.declaring && classSym.imported && (!classSym.declaredStructSym || (classSym.registered.type == noHeadClass && !skipNoHead && external && !curDeclarations)))
1185    {
1186       OldList * specifiers, * declarators;
1187       OldList * declarations = null;
1188       char structName[1024];
1189       bool addedPadding = false;
1190       Specifier curSpec = null;
1191
1192       classSym.declaring++;
1193
1194       if(strchr(classSym.string, '<'))
1195       {
1196          if(classSym.registered.templateClass)
1197             external = _DeclareStruct(neededBy, classSym.registered.templateClass.fullName, skipNoHead, needDereference, fwdDecl);
1198          classSym.declaring--;
1199          return external;
1200       }
1201
1202       structName[0] = 0;
1203       FullClassNameCat(structName, name, false);
1204
1205       classSym.declaredStructSym = true;
1206       if(!external || (classSym.registered.type == noHeadClass && !skipNoHead && !curDeclarations))
1207       {
1208          bool add = false;
1209          if(!external)
1210          {
1211             external = MkExternalDeclaration(null);
1212             classSym.structExternal = external;
1213             external.symbol = classSym;
1214
1215             add = true;
1216          }
1217
1218          if(!skipNoHead)
1219          {
1220             declarations = MkList();
1221             AddMembers(external, declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1222          }
1223
1224          if(external.declaration)
1225          {
1226             Specifier spec;
1227             for(spec = external.declaration.specifiers ? external.declaration.specifiers->first : null; spec; spec = spec.next)
1228                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1229                {
1230                   curSpec = spec;
1231                   curDeclarations = spec.definitions;
1232                   break;
1233                }
1234          }
1235
1236          if(declarations && (!declarations->count || (declarations->count == 1 && addedPadding)))
1237          {
1238             FreeList(declarations, FreeClassDef);
1239             declarations = null;
1240          }
1241
1242          if(classSym.registered.type != noHeadClass && !declarations)
1243          {
1244             FreeExternal(external);
1245             external = null;
1246             classSym.structExternal = null;
1247          }
1248          else
1249          {
1250             if(curSpec)
1251                curSpec.definitions = declarations;
1252             else
1253             {
1254                specifiers = MkList();
1255                declarators = MkList();
1256                ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1257                external.declaration = MkDeclaration(specifiers, declarators);
1258             }
1259             if(add)
1260                ast->Add(external);
1261          }
1262       }
1263       classSym.declaring--;
1264    }
1265    else if(!classSym.declaredStructSym && classSym.structExternal)
1266    {
1267       classSym.declaredStructSym = true;
1268
1269       if(classSym.registered)
1270          DeclareMembers(classSym.structExternal, classSym.registered, false);
1271
1272       if(classSym.structExternal.declaration && classSym.structExternal.declaration.specifiers)
1273       {
1274          Specifier spec;
1275          for(spec = classSym.structExternal.declaration.specifiers->first; spec; spec = spec.next)
1276          {
1277             if(spec.definitions)
1278                IdentifyAnonStructs(spec.definitions);
1279          }
1280       }
1281    }
1282    if(inCompiler && neededBy && (external || !classSym.imported))
1283    {
1284       if(!external)
1285       {
1286          classSym.structExternal = external = MkExternalDeclaration(null);
1287          external.symbol = classSym;
1288          ast->Add(external);
1289       }
1290       if(reachedPass15 && !external.declaration && classSym.registered && classSym.registered.type == noHeadClass)
1291       {
1292          // Declare nohead classes without definitions here (e.g. IteratorPointer)
1293          char structName[1024];
1294          OldList * specifiers, * declarators;
1295          structName[0] = 0;
1296          FullClassNameCat(structName, name, false);
1297          specifiers = MkList();
1298          declarators = MkList();
1299          ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), null));
1300          external.declaration = MkDeclaration(specifiers, declarators);
1301       }
1302       if(fwdDecl)
1303       {
1304          External e = external.fwdDecl ? external.fwdDecl : external;
1305          if(e.incoming.count)
1306             neededBy.CreateUniqueEdge(e, !needDereference && !external.fwdDecl);
1307       }
1308       else
1309          neededBy.CreateUniqueEdge(external, !needDereference);
1310    }
1311    return external;
1312 }
1313
1314 void DeclareProperty(External neededBy, Property prop, char * setName, char * getName)
1315 {
1316    Symbol symbol = prop.symbol;
1317    bool imported = false;
1318    bool dllImport = false;
1319    External structExternal = null;
1320    External instExternal = null;
1321
1322    strcpy(setName, "__ecereProp_");
1323    FullClassNameCat(setName, prop._class.fullName, false);
1324    strcat(setName, "_Set_");
1325    FullClassNameCat(setName, prop.name, true);
1326
1327    strcpy(getName, "__ecereProp_");
1328    FullClassNameCat(getName, prop._class.fullName, false);
1329    strcat(getName, "_Get_");
1330    FullClassNameCat(getName, prop.name, true);
1331
1332    if(!symbol || symbol._import)
1333    {
1334       if(!symbol)
1335       {
1336          Symbol classSym;
1337
1338          if(!prop._class.symbol)
1339             prop._class.symbol = FindClass(prop._class.fullName);
1340          classSym = prop._class.symbol;
1341          if(classSym && !classSym._import)
1342          {
1343             ModuleImport module;
1344
1345             if(prop._class.module)
1346                module = FindModule(prop._class.module);
1347             else
1348                module = mainModule;
1349
1350             classSym._import = ClassImport
1351             {
1352                name = CopyString(prop._class.fullName);
1353                isRemote = prop._class.isRemote;
1354             };
1355             module.classes.Add(classSym._import);
1356          }
1357          symbol = prop.symbol = Symbol { };
1358          symbol._import = (ClassImport)PropertyImport
1359          {
1360             name = CopyString(prop.name);
1361             isVirtual = false; //prop.isVirtual;
1362             hasSet = prop.Set ? true : false;
1363             hasGet = prop.Get ? true : false;
1364          };
1365          if(classSym)
1366             classSym._import.properties.Add(symbol._import);
1367       }
1368       imported = true;
1369       // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1370       if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1371          prop._class.module.importType != staticImport)
1372          dllImport = true;
1373    }
1374
1375    if(!symbol.type)
1376    {
1377       Context context = SetupTemplatesContext(prop._class);
1378       symbol.type = ProcessTypeString(prop.dataTypeString, false);
1379       FinishTemplatesContext(context);
1380    }
1381
1382    if((prop.Get && !symbol.externalGet) || (prop.Set && !symbol.externalSet))
1383    {
1384       if(prop._class.type == normalClass && prop._class.structSize)
1385          instExternal = DeclareStruct(null, "ecere::com::Instance", false, true);
1386       structExternal = DeclareStruct(null, prop._class.fullName, prop._class.type != structClass /*true*/, false);
1387    }
1388
1389    // Get
1390    if(prop.Get && !symbol.externalGet)
1391    {
1392       Declaration decl;
1393       OldList * specifiers, * declarators;
1394       Declarator d;
1395       OldList * params;
1396       Specifier spec = null;
1397       External external;
1398       Declarator typeDecl;
1399       bool simple = false;
1400       bool needReference;
1401
1402       specifiers = MkList();
1403       declarators = MkList();
1404       params = MkList();
1405
1406       ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1407          MkDeclaratorIdentifier(MkIdentifier("this"))));
1408
1409       d = MkDeclaratorIdentifier(MkIdentifier(getName));
1410       //if(imported)
1411       if(dllImport)
1412          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1413
1414       {
1415          Context context = SetupTemplatesContext(prop._class);
1416          typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1417          FinishTemplatesContext(context);
1418       }
1419
1420       // Make sure the simple _class's type is declared
1421       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1422       for(spec = specifiers->first; spec; spec = spec.next)
1423       {
1424          if(spec.type == nameSpecifier)
1425          {
1426             Symbol classSym = spec.symbol;
1427             if(needReference)
1428             {
1429                symbol._class = classSym.registered;
1430                if(classSym.registered && classSym.registered.type == structClass)
1431                   simple = true;
1432             }
1433             break;
1434          }
1435       }
1436
1437       if(!simple)
1438          d = PlugDeclarator(typeDecl, d);
1439       else
1440       {
1441          ListAdd(params, MkTypeName(specifiers,
1442             PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1443          specifiers = MkList();
1444       }
1445
1446       d = MkDeclaratorFunction(d, params);
1447
1448       //if(imported)
1449       if(dllImport)
1450          specifiers->Insert(null, MkSpecifier(EXTERN));
1451       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1452          specifiers->Insert(null, MkSpecifier(STATIC));
1453       if(simple)
1454          ListAdd(specifiers, MkSpecifier(VOID));
1455
1456       ListAdd(declarators, MkInitDeclarator(d, null));
1457
1458       decl = MkDeclaration(specifiers, declarators);
1459
1460       external = MkExternalDeclaration(decl);
1461
1462       if(structExternal)
1463          external.CreateEdge(structExternal, false);
1464       if(instExternal)
1465          external.CreateEdge(instExternal, false);
1466
1467       if(spec)
1468          DeclareStruct(external, spec.name, false, needReference);
1469
1470       ast->Add(external);
1471       external.symbol = symbol;
1472       symbol.externalGet = external;
1473
1474       ReplaceThisClassSpecifiers(specifiers, prop._class);
1475
1476       if(typeDecl)
1477          FreeDeclarator(typeDecl);
1478    }
1479
1480    // Set
1481    if(prop.Set && !symbol.externalSet)
1482    {
1483       Declaration decl;
1484       OldList * specifiers, * declarators;
1485       Declarator d;
1486       OldList * params;
1487       Specifier spec = null;
1488       External external;
1489       Declarator typeDecl;
1490       bool needReference;
1491
1492       declarators = MkList();
1493       params = MkList();
1494
1495       if(!prop.conversion || prop._class.type == structClass)
1496       {
1497          ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1498             MkDeclaratorIdentifier(MkIdentifier("this"))));
1499       }
1500
1501       specifiers = MkList();
1502
1503       {
1504          Context context = SetupTemplatesContext(prop._class);
1505          typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1506             MkDeclaratorIdentifier(MkIdentifier("value")));
1507          FinishTemplatesContext(context);
1508       }
1509       if(!strcmp(prop._class.base.fullName, "eda::Row") || !strcmp(prop._class.base.fullName, "eda::Id"))
1510          specifiers->Insert(null, MkSpecifier(CONST));
1511
1512       ListAdd(params, MkTypeName(specifiers, d));
1513
1514       d = MkDeclaratorIdentifier(MkIdentifier(setName));
1515       if(dllImport)
1516          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1517       d = MkDeclaratorFunction(d, params);
1518
1519       // Make sure the simple _class's type is declared
1520       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1521       for(spec = specifiers->first; spec; spec = spec.next)
1522       {
1523          if(spec.type == nameSpecifier)
1524          {
1525             Symbol classSym = spec.symbol;
1526             if(needReference)
1527                symbol._class = classSym.registered;
1528             break;
1529          }
1530       }
1531
1532       ListAdd(declarators, MkInitDeclarator(d, null));
1533
1534       specifiers = MkList();
1535       if(dllImport)
1536          specifiers->Insert(null, MkSpecifier(EXTERN));
1537       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1538          specifiers->Insert(null, MkSpecifier(STATIC));
1539
1540       if(!prop.conversion || prop._class.type == structClass)
1541          ListAdd(specifiers, MkSpecifier(VOID));
1542       else
1543          ListAdd(specifiers, MkSpecifierName(prop._class.fullName));
1544
1545       decl = MkDeclaration(specifiers, declarators);
1546
1547       external = MkExternalDeclaration(decl);
1548
1549       if(structExternal)
1550          external.CreateEdge(structExternal, false);
1551       if(instExternal)
1552          external.CreateEdge(instExternal, false);
1553
1554       if(spec)
1555          DeclareStruct(external, spec.name, false, needReference);
1556
1557       ast->Add(external);
1558       external.symbol = symbol;
1559       symbol.externalSet = external;
1560
1561       ReplaceThisClassSpecifiers(specifiers, prop._class);
1562    }
1563
1564    // Property (for Watchers)
1565    if(!symbol.externalPtr)
1566    {
1567       Declaration decl;
1568       External external;
1569       OldList * specifiers = MkList();
1570       char propName[1024];
1571
1572       if(imported)
1573          specifiers->Insert(null, MkSpecifier(EXTERN));
1574       else
1575       {
1576          specifiers->Insert(null, MkSpecifier(STATIC));
1577          specifiers->Add(MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
1578       }
1579
1580       ListAdd(specifiers, MkSpecifierName("Property"));
1581
1582       strcpy(propName, "__ecereProp_");
1583       FullClassNameCat(propName, prop._class.fullName, false);
1584       strcat(propName, "_");
1585       FullClassNameCat(propName, prop.name, true);
1586
1587       {
1588          OldList * list = MkList();
1589          ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1590
1591          if(!imported)
1592          {
1593             strcpy(propName, "__ecerePropM_");
1594             FullClassNameCat(propName, prop._class.fullName, false);
1595             strcat(propName, "_");
1596             FullClassNameCat(propName, prop.name, true);
1597
1598             ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1599          }
1600          decl = MkDeclaration(specifiers, list);
1601       }
1602
1603       external = MkExternalDeclaration(decl);
1604       ast->Insert(curExternal.prev, external);
1605       external.symbol = symbol;
1606       symbol.externalPtr = external;
1607    }
1608
1609    if(inCompiler && neededBy)
1610    {
1611       // Could improve this to create edge on only what is needed...
1612       if(symbol.externalPtr)
1613          neededBy.CreateUniqueEdge(symbol.externalPtr, false);
1614
1615       if(symbol.externalGet)
1616          neededBy.CreateUniqueEdge(symbol.externalGet, symbol.externalGet.type == functionExternal);
1617
1618       if(symbol.externalSet)
1619          neededBy.CreateUniqueEdge(symbol.externalSet, symbol.externalSet.type == functionExternal);
1620
1621       // IsSet ?
1622    }
1623 }
1624
1625 // ***************** EXPRESSION PROCESSING ***************************
1626 public Type Dereference(Type source)
1627 {
1628    Type type = null;
1629    if(source)
1630    {
1631       if(source.kind == pointerType || source.kind == arrayType)
1632       {
1633          type = source.type;
1634          source.type.refCount++;
1635       }
1636       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1637       {
1638          type = Type
1639          {
1640             kind = charType;
1641             refCount = 1;
1642          };
1643       }
1644       // Support dereferencing of no head classes for now...
1645       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1646       {
1647          type = source;
1648          source.refCount++;
1649       }
1650       else
1651          Compiler_Error($"cannot dereference type\n");
1652    }
1653    return type;
1654 }
1655
1656 static Type Reference(Type source)
1657 {
1658    Type type = null;
1659    if(source)
1660    {
1661       type = Type
1662       {
1663          kind = pointerType;
1664          type = source;
1665          refCount = 1;
1666       };
1667       source.refCount++;
1668    }
1669    return type;
1670 }
1671
1672 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1673 {
1674    Identifier ident = member.identifiers ? member.identifiers->first : null;
1675    bool found = false;
1676    DataMember dataMember = null;
1677    Method method = null;
1678    bool freeType = false;
1679
1680    yylloc = member.loc;
1681
1682    if(!ident)
1683    {
1684       if(curMember)
1685       {
1686          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1687          if(*curMember)
1688          {
1689             found = true;
1690             dataMember = *curMember;
1691          }
1692       }
1693    }
1694    else
1695    {
1696       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1697       DataMember _subMemberStack[256];
1698       int _subMemberStackPos = 0;
1699
1700       // FILL MEMBER STACK
1701       if(!thisMember)
1702          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1703       if(thisMember)
1704       {
1705          dataMember = thisMember;
1706          if(curMember && thisMember.memberAccess == publicAccess)
1707          {
1708             *curMember = thisMember;
1709             *curClass = thisMember._class;
1710             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1711             *subMemberStackPos = _subMemberStackPos;
1712          }
1713          found = true;
1714       }
1715       else
1716       {
1717          // Setting a method
1718          method = eClass_FindMethod(_class, ident.string, privateModule);
1719          if(method && method.type == virtualMethod)
1720             found = true;
1721          else
1722             method = null;
1723       }
1724    }
1725
1726    if(found)
1727    {
1728       Type type = null;
1729       if(dataMember)
1730       {
1731          if(!dataMember.dataType && dataMember.dataTypeString)
1732          {
1733             //Context context = SetupTemplatesContext(dataMember._class);
1734             Context context = SetupTemplatesContext(_class);
1735             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1736             FinishTemplatesContext(context);
1737          }
1738          type = dataMember.dataType;
1739       }
1740       else if(method)
1741       {
1742          // This is for destination type...
1743          if(!method.dataType)
1744             ProcessMethodType(method);
1745          //DeclareMethod(method);
1746          // method.dataType = ((Symbol)method.symbol)->type;
1747          type = method.dataType;
1748       }
1749
1750       if(ident && ident.next)
1751       {
1752          for(ident = ident.next; ident && type; ident = ident.next)
1753          {
1754             if(type.kind == classType)
1755             {
1756                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1757                if(!dataMember)
1758                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1759                if(dataMember)
1760                   type = dataMember.dataType;
1761             }
1762             else if(type.kind == structType || type.kind == unionType)
1763             {
1764                Type memberType;
1765                for(memberType = type.members.first; memberType; memberType = memberType.next)
1766                {
1767                   if(!strcmp(memberType.name, ident.string))
1768                   {
1769                      type = memberType;
1770                      break;
1771                   }
1772                }
1773             }
1774          }
1775       }
1776
1777       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1778       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1779       {
1780          int id = 0;
1781          ClassTemplateParameter curParam = null;
1782          Class sClass;
1783          for(sClass = _class; sClass; sClass = sClass.base)
1784          {
1785             id = 0;
1786             if(sClass.templateClass) sClass = sClass.templateClass;
1787             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1788             {
1789                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1790                {
1791                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1792                   {
1793                      if(sClass.templateClass) sClass = sClass.templateClass;
1794                      id += sClass.templateParams.count;
1795                   }
1796                   break;
1797                }
1798                id++;
1799             }
1800             if(curParam) break;
1801          }
1802
1803          if(curParam)
1804          {
1805             ClassTemplateArgument arg = _class.templateArgs[id];
1806             if(arg.dataTypeString)
1807             {
1808                bool constant = type.constant;
1809                // FreeType(type);
1810                type = ProcessTypeString(arg.dataTypeString, false);
1811                if(type.kind == classType && constant) type.constant = true;
1812                else if(type.kind == pointerType)
1813                {
1814                   Type t = type.type;
1815                   while(t.kind == pointerType) t = t.type;
1816                   if(constant) t.constant = constant;
1817                }
1818                freeType = true;
1819                if(type && _class.templateClass)
1820                   type.passAsTemplate = true;
1821                if(type)
1822                {
1823                   // type.refCount++;
1824                   /*if(!exp.destType)
1825                   {
1826                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1827                      exp.destType.refCount++;
1828                   }*/
1829                }
1830             }
1831          }
1832       }
1833       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1834       {
1835          Class expClass = type._class.registered;
1836          Class cClass = null;
1837          int paramCount = 0;
1838          int lastParam = -1;
1839
1840          char templateString[1024];
1841          ClassTemplateParameter param;
1842          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1843          for(cClass = expClass; cClass; cClass = cClass.base)
1844          {
1845             int p = 0;
1846             if(cClass.templateClass) cClass = cClass.templateClass;
1847             for(param = cClass.templateParams.first; param; param = param.next)
1848             {
1849                int id = p;
1850                Class sClass;
1851                ClassTemplateArgument arg;
1852                for(sClass = cClass.base; sClass; sClass = sClass.base)
1853                {
1854                   if(sClass.templateClass) sClass = sClass.templateClass;
1855                   id += sClass.templateParams.count;
1856                }
1857                arg = expClass.templateArgs[id];
1858
1859                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1860                {
1861                   ClassTemplateParameter cParam;
1862                   //int p = numParams - sClass.templateParams.count;
1863                   int p = 0;
1864                   Class nextClass;
1865                   if(sClass.templateClass) sClass = sClass.templateClass;
1866
1867                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1868                   {
1869                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1870                      p += nextClass.templateParams.count;
1871                   }
1872
1873                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1874                   {
1875                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1876                      {
1877                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1878                         {
1879                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1880                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1881                            break;
1882                         }
1883                      }
1884                   }
1885                }
1886
1887                {
1888                   char argument[256];
1889                   argument[0] = '\0';
1890                   /*if(arg.name)
1891                   {
1892                      strcat(argument, arg.name.string);
1893                      strcat(argument, " = ");
1894                   }*/
1895                   switch(param.type)
1896                   {
1897                      case expression:
1898                      {
1899                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1900                         char expString[1024];
1901                         OldList * specs = MkList();
1902                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1903                         Expression exp;
1904                         char * string = PrintHexUInt64(arg.expression.ui64);
1905                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1906                         delete string;
1907
1908                         ProcessExpressionType(exp);
1909                         ComputeExpression(exp);
1910                         expString[0] = '\0';
1911                         PrintExpression(exp, expString);
1912                         strcat(argument, expString);
1913                         //delete exp;
1914                         FreeExpression(exp);
1915                         break;
1916                      }
1917                      case identifier:
1918                      {
1919                         strcat(argument, arg.member.name);
1920                         break;
1921                      }
1922                      case TemplateParameterType::type:
1923                      {
1924                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1925                            strcat(argument, arg.dataTypeString);
1926                         break;
1927                      }
1928                   }
1929                   if(argument[0])
1930                   {
1931                      if(paramCount) strcat(templateString, ", ");
1932                      if(lastParam != p - 1)
1933                      {
1934                         strcat(templateString, param.name);
1935                         strcat(templateString, " = ");
1936                      }
1937                      strcat(templateString, argument);
1938                      paramCount++;
1939                      lastParam = p;
1940                   }
1941                   p++;
1942                }
1943             }
1944          }
1945          {
1946             int len = strlen(templateString);
1947             if(templateString[len-1] == '<')
1948                len--;
1949             else
1950             {
1951                if(templateString[len-1] == '>')
1952                   templateString[len++] = ' ';
1953                templateString[len++] = '>';
1954             }
1955             templateString[len++] = '\0';
1956          }
1957          {
1958             Context context = SetupTemplatesContext(_class);
1959             if(freeType) FreeType(type);
1960             type = ProcessTypeString(templateString, false);
1961             freeType = true;
1962             FinishTemplatesContext(context);
1963          }
1964       }
1965
1966       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1967       {
1968          ProcessExpressionType(member.initializer.exp);
1969          if(!member.initializer.exp.expType)
1970          {
1971             if(inCompiler)
1972             {
1973                char expString[10240];
1974                expString[0] = '\0';
1975                PrintExpression(member.initializer.exp, expString);
1976                ChangeCh(expString, '\n', ' ');
1977                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1978             }
1979          }
1980          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1981          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
1982          {
1983             Compiler_Error($"incompatible instance method %s\n", ident.string);
1984          }
1985       }
1986       else if(member.initializer)
1987       {
1988          /*
1989          FreeType(member.exp.destType);
1990          member.exp.destType = type;
1991          if(member.exp.destType)
1992             member.exp.destType.refCount++;
1993          ProcessExpressionType(member.exp);
1994          */
1995
1996          ProcessInitializer(member.initializer, type);
1997       }
1998       if(freeType) FreeType(type);
1999    }
2000    else
2001    {
2002       if(_class && _class.type == unitClass)
2003       {
2004          if(member.initializer)
2005          {
2006             /*
2007             FreeType(member.exp.destType);
2008             member.exp.destType = MkClassType(_class.fullName);
2009             ProcessExpressionType(member.initializer, type);
2010             */
2011             Type type = MkClassType(_class.fullName);
2012             ProcessInitializer(member.initializer, type);
2013             FreeType(type);
2014          }
2015       }
2016       else
2017       {
2018          if(member.initializer)
2019          {
2020             //ProcessExpressionType(member.exp);
2021             ProcessInitializer(member.initializer, null);
2022          }
2023          if(ident)
2024          {
2025             if(method)
2026             {
2027                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2028             }
2029             else if(_class)
2030             {
2031                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2032                if(inCompiler)
2033                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2034             }
2035          }
2036          else if(_class)
2037             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2038       }
2039    }
2040 }
2041
2042 void ProcessInstantiationType(Instantiation inst)
2043 {
2044    yylloc = inst.loc;
2045    if(inst._class)
2046    {
2047       MembersInit members;
2048       Symbol classSym;
2049       Class _class;
2050
2051       classSym = inst._class.symbol;
2052       _class = classSym ? classSym.registered : null;
2053
2054       if(!_class || _class.type != noHeadClass)
2055          DeclareStruct(curExternal, inst._class.name, false, true);
2056
2057       afterExternal = afterExternal ? afterExternal : curExternal;
2058
2059       if(inst.exp)
2060          ProcessExpressionType(inst.exp);
2061
2062       inst.isConstant = true;
2063       if(inst.members)
2064       {
2065          DataMember curMember = null;
2066          Class curClass = null;
2067          DataMember subMemberStack[256];
2068          int subMemberStackPos = 0;
2069
2070          for(members = inst.members->first; members; members = members.next)
2071          {
2072             switch(members.type)
2073             {
2074                case methodMembersInit:
2075                {
2076                   char name[1024];
2077                   static uint instMethodID = 0;
2078                   External external = curExternal;
2079                   Context context = curContext;
2080                   Declarator declarator = members.function.declarator;
2081                   Identifier nameID = GetDeclId(declarator);
2082                   char * unmangled = nameID ? nameID.string : null;
2083                   Expression exp;
2084                   External createdExternal = null;
2085
2086                   if(inCompiler)
2087                   {
2088                      char number[16];
2089                      strcpy(name, "__ecereInstMeth_");
2090                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2091                      strcat(name, "_");
2092                      strcat(name, nameID.string);
2093                      strcat(name, "_");
2094                      sprintf(number, "_%08d", instMethodID++);
2095                      strcat(name, number);
2096                      nameID.string = CopyString(name);
2097                   }
2098
2099                   // Do modifications here...
2100                   if(declarator)
2101                   {
2102                      Symbol symbol = declarator.symbol;
2103                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2104
2105                      if(method && method.type == virtualMethod)
2106                      {
2107                         symbol.method = method;
2108                         ProcessMethodType(method);
2109
2110                         if(!symbol.type.thisClass)
2111                         {
2112                            if(method.dataType.thisClass && currentClass &&
2113                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2114                            {
2115                               if(!currentClass.symbol)
2116                                  currentClass.symbol = FindClass(currentClass.fullName);
2117                               symbol.type.thisClass = currentClass.symbol;
2118                            }
2119                            else
2120                            {
2121                               if(!_class.symbol)
2122                                  _class.symbol = FindClass(_class.fullName);
2123                               symbol.type.thisClass = _class.symbol;
2124                            }
2125                         }
2126                         DeclareType(curExternal, symbol.type, true, true);
2127
2128                      }
2129                      else if(classSym)
2130                      {
2131                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2132                            unmangled, classSym.string);
2133                      }
2134                   }
2135
2136                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2137
2138                   if(nameID)
2139                   {
2140                      FreeSpecifier(nameID._class);
2141                      nameID._class = null;
2142                   }
2143
2144                   curExternal = createdExternal;
2145                   if(inCompiler)
2146                   {
2147                      if(createdExternal.function)
2148                         ProcessFunction(createdExternal.function);
2149                   }
2150                   else if(declarator)
2151                   {
2152                      curExternal = declarator.symbol.pointerExternal;
2153                      ProcessFunction((FunctionDefinition)members.function);
2154                   }
2155                   curExternal = external;
2156                   curContext = context;
2157
2158                   if(inCompiler)
2159                   {
2160                      FreeClassFunction(members.function);
2161
2162                      // In this pass, turn this into a MemberInitData
2163                      exp = QMkExpId(name);
2164                      members.type = dataMembersInit;
2165                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2166
2167                      delete unmangled;
2168                   }
2169                   break;
2170                }
2171                case dataMembersInit:
2172                {
2173                   if(members.dataMembers && classSym)
2174                   {
2175                      MemberInit member;
2176                      Location oldyyloc = yylloc;
2177                      for(member = members.dataMembers->first; member; member = member.next)
2178                      {
2179                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2180                         if(member.initializer && !member.initializer.isConstant)
2181                            inst.isConstant = false;
2182                      }
2183                      yylloc = oldyyloc;
2184                   }
2185                   break;
2186                }
2187             }
2188          }
2189       }
2190    }
2191 }
2192
2193 void DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2194 {
2195    _DeclareType(neededFor, type, needDereference, forFunctionDef, false);
2196 }
2197
2198 void DeclareTypeForwardDeclare(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2199 {
2200    _DeclareType(neededFor, type, needDereference, forFunctionDef, true);
2201 }
2202
2203 static void _DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef, bool fwdDecl)
2204 {
2205    if(inCompiler)
2206    {
2207       if(type.kind == functionType)
2208       {
2209          Type param;
2210          for(param = type.params.first; param; param = param.next)
2211             _DeclareType(neededFor, param, forFunctionDef, false, fwdDecl);
2212          _DeclareType(neededFor, type.returnType, forFunctionDef, false, fwdDecl);
2213       }
2214       else if(type.kind == pointerType)
2215          _DeclareType(neededFor, type.type, false, false, fwdDecl);
2216       else if(type.kind == classType)
2217       {
2218          Class c = type._class.registered;
2219          _DeclareStruct(neededFor, c ? c.fullName : "ecere::com::Instance", c ? c.type == noHeadClass : false, needDereference && c && c.type == structClass, fwdDecl);
2220       }
2221       else if(type.kind == structType || type.kind == unionType)
2222       {
2223          Type member;
2224          for(member = type.members.first; member; member = member.next)
2225             _DeclareType(neededFor, member, needDereference, forFunctionDef, fwdDecl);
2226       }
2227       else if(type.kind == arrayType)
2228          _DeclareType(neededFor, type.arrayType, true, false, fwdDecl);
2229    }
2230 }
2231
2232 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2233 {
2234    ClassTemplateArgument * arg = null;
2235    int id = 0;
2236    ClassTemplateParameter curParam = null;
2237    Class sClass;
2238    for(sClass = _class; sClass; sClass = sClass.base)
2239    {
2240       id = 0;
2241       if(sClass.templateClass) sClass = sClass.templateClass;
2242       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2243       {
2244          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2245          {
2246             for(sClass = sClass.base; sClass; sClass = sClass.base)
2247             {
2248                if(sClass.templateClass) sClass = sClass.templateClass;
2249                id += sClass.templateParams.count;
2250             }
2251             break;
2252          }
2253          id++;
2254       }
2255       if(curParam) break;
2256    }
2257    if(curParam)
2258    {
2259       arg = &_class.templateArgs[id];
2260       if(arg && param.type == type)
2261          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2262    }
2263    return arg;
2264 }
2265
2266 public Context SetupTemplatesContext(Class _class)
2267 {
2268    Context context = PushContext();
2269    context.templateTypesOnly = true;
2270    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2271    {
2272       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2273       for(; param; param = param.next)
2274       {
2275          if(param.type == type && param.identifier)
2276          {
2277             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2278             curContext.templateTypes.Add((BTNode)type);
2279          }
2280       }
2281    }
2282    else if(_class)
2283    {
2284       Class sClass;
2285       for(sClass = _class; sClass; sClass = sClass.base)
2286       {
2287          ClassTemplateParameter p;
2288          for(p = sClass.templateParams.first; p; p = p.next)
2289          {
2290             //OldList * specs = MkList();
2291             //Declarator decl = null;
2292             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2293             if(p.type == type)
2294             {
2295                TemplateParameter param = p.param;
2296                TemplatedType type;
2297                if(!param)
2298                {
2299                   // ADD DATA TYPE HERE...
2300                   p.param = param = TemplateParameter
2301                   {
2302                      identifier = MkIdentifier(p.name), type = p.type,
2303                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2304                   };
2305                }
2306                type = TemplatedType { key = (uintptr)p.name, param = param };
2307                curContext.templateTypes.Add((BTNode)type);
2308             }
2309          }
2310       }
2311    }
2312    return context;
2313 }
2314
2315 public void FinishTemplatesContext(Context context)
2316 {
2317    PopContext(context);
2318    FreeContext(context);
2319    delete context;
2320 }
2321
2322 public void ProcessMethodType(Method method)
2323 {
2324    if(!method.dataType)
2325    {
2326       Context context = SetupTemplatesContext(method._class);
2327
2328       method.dataType = ProcessTypeString(method.dataTypeString, false);
2329
2330       FinishTemplatesContext(context);
2331
2332       if(method.type != virtualMethod && method.dataType)
2333       {
2334          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2335          {
2336             if(!method._class.symbol)
2337                method._class.symbol = FindClass(method._class.fullName);
2338             method.dataType.thisClass = method._class.symbol;
2339          }
2340       }
2341
2342       // Why was this commented out? Working fine without now...
2343
2344       /*
2345       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2346          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2347          */
2348    }
2349
2350    /*
2351    if(type)
2352    {
2353       char * par = strstr(type, "(");
2354       char * classOp = null;
2355       int classOpLen = 0;
2356       if(par)
2357       {
2358          int c;
2359          for(c = par-type-1; c >= 0; c++)
2360          {
2361             if(type[c] == ':' && type[c+1] == ':')
2362             {
2363                classOp = type + c - 1;
2364                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2365                {
2366                   classOp--;
2367                   classOpLen++;
2368                }
2369                break;
2370             }
2371             else if(!isspace(type[c]))
2372                break;
2373          }
2374       }
2375       if(classOp)
2376       {
2377          char temp[1024];
2378          int typeLen = strlen(type);
2379          memcpy(temp, classOp, classOpLen);
2380          temp[classOpLen] = '\0';
2381          if(temp[0])
2382             _class = eSystem_FindClass(module, temp);
2383          else
2384             _class = null;
2385          method.dataTypeString = new char[typeLen - classOpLen + 1];
2386          memcpy(method.dataTypeString, type, classOp - type);
2387          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2388       }
2389       else
2390          method.dataTypeString = type;
2391    }
2392    */
2393 }
2394
2395
2396 public void ProcessPropertyType(Property prop)
2397 {
2398    if(!prop.dataType)
2399    {
2400       Context context = SetupTemplatesContext(prop._class);
2401       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2402       FinishTemplatesContext(context);
2403    }
2404 }
2405
2406 public void DeclareMethod(External neededFor, Method method, const char * name)
2407 {
2408    Symbol symbol = method.symbol;
2409    if(!symbol || (!symbol.pointerExternal && (!symbol.methodCodeExternal || method.type == virtualMethod)))
2410    {
2411       bool dllImport = false;
2412
2413       if(!method.dataType)
2414          method.dataType = ProcessTypeString(method.dataTypeString, false);
2415
2416       //if(!symbol || symbol._import || method.type == virtualMethod)
2417       {
2418          if(!symbol || method.type == virtualMethod)
2419          {
2420             Symbol classSym;
2421             if(!method._class.symbol)
2422                method._class.symbol = FindClass(method._class.fullName);
2423             classSym = method._class.symbol;
2424             if(!classSym._import)
2425             {
2426                ModuleImport module;
2427
2428                if(method._class.module && method._class.module.name)
2429                   module = FindModule(method._class.module);
2430                else
2431                   module = mainModule;
2432                classSym._import = ClassImport
2433                {
2434                   name = CopyString(method._class.fullName);
2435                   isRemote = method._class.isRemote;
2436                };
2437                module.classes.Add(classSym._import);
2438             }
2439             if(!symbol)
2440             {
2441                symbol = method.symbol = Symbol { };
2442             }
2443             if(!symbol._import)
2444             {
2445                symbol._import = (ClassImport)MethodImport
2446                {
2447                   name = CopyString(method.name);
2448                   isVirtual = method.type == virtualMethod;
2449                };
2450                classSym._import.methods.Add(symbol._import);
2451             }
2452             if(!symbol)
2453             {
2454                symbol.type = method.dataType;
2455                if(symbol.type) symbol.type.refCount++;
2456             }
2457          }
2458          if(!method.dataType.dllExport)
2459          {
2460             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2461                dllImport = true;
2462          }
2463       }
2464
2465       if(inCompiler)
2466       {
2467          // We need a declaration here :)
2468          Declaration decl;
2469          OldList * specifiers, * declarators;
2470          Declarator d;
2471          Declarator funcDecl;
2472          External external;
2473
2474          specifiers = MkList();
2475          declarators = MkList();
2476
2477          if(dllImport)
2478             ListAdd(specifiers, MkSpecifier(EXTERN));
2479          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2480             ListAdd(specifiers, MkSpecifier(STATIC));
2481
2482          if(method.type == virtualMethod)
2483          {
2484             ListAdd(specifiers, MkSpecifier(INT));
2485             d = MkDeclaratorIdentifier(MkIdentifier(name));
2486          }
2487          else
2488          {
2489             d = MkDeclaratorIdentifier(MkIdentifier(name));
2490             if(dllImport)
2491                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2492             {
2493                Context context = SetupTemplatesContext(method._class);
2494                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2495                FinishTemplatesContext(context);
2496             }
2497             funcDecl = GetFuncDecl(d);
2498
2499             if(dllImport)
2500             {
2501                Specifier spec, next;
2502                for(spec = specifiers->first; spec; spec = next)
2503                {
2504                   next = spec.next;
2505                   if(spec.type == extendedSpecifier)
2506                   {
2507                      specifiers->Remove(spec);
2508                      FreeSpecifier(spec);
2509                   }
2510                }
2511             }
2512
2513             // Add this parameter if not a static method
2514             if(method.dataType && !method.dataType.staticMethod)
2515             {
2516                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2517                {
2518                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2519                   TypeName thisParam = MkTypeName(MkListOne(
2520                      MkSpecifierName(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2521                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2522                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2523                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2524
2525                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2526                   {
2527                      TypeName param = funcDecl.function.parameters->first;
2528                      funcDecl.function.parameters->Remove(param);
2529                      FreeTypeName(param);
2530                   }
2531
2532                   if(!funcDecl.function.parameters)
2533                      funcDecl.function.parameters = MkList();
2534                   funcDecl.function.parameters->Insert(null, thisParam);
2535                }
2536             }
2537          }
2538          ProcessDeclarator(d, true);
2539
2540          ListAdd(declarators, MkInitDeclarator(d, null));
2541
2542          decl = MkDeclaration(specifiers, declarators);
2543
2544          ReplaceThisClassSpecifiers(specifiers, method._class);
2545
2546          external = MkExternalDeclaration(decl);
2547          external.symbol = symbol;
2548          symbol.pointerExternal = external;
2549          ast->Add(external);
2550          DeclareStruct(external, method._class.fullName, true, true);
2551          if(method.dataType)
2552             DeclareType(external, method.dataType, true, true);
2553       }
2554    }
2555    if(inCompiler && neededFor)
2556    {
2557       External external = symbol.pointerExternal ? symbol.pointerExternal : symbol.methodCodeExternal;
2558       neededFor.CreateUniqueEdge(external, external.type == functionExternal);
2559    }
2560 }
2561
2562 char * ReplaceThisClass(Class _class)
2563 {
2564    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2565    {
2566       bool first = true;
2567       int p = 0;
2568       ClassTemplateParameter param;
2569       int lastParam = -1;
2570
2571       char className[1024];
2572       strcpy(className, _class.fullName);
2573       for(param = _class.templateParams.first; param; param = param.next)
2574       {
2575          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2576          {
2577             if(first) strcat(className, "<");
2578             if(!first) strcat(className, ", ");
2579             if(lastParam + 1 != p)
2580             {
2581                strcat(className, param.name);
2582                strcat(className, " = ");
2583             }
2584             strcat(className, param.name);
2585             first = false;
2586             lastParam = p;
2587          }
2588          p++;
2589       }
2590       if(!first)
2591       {
2592          int len = strlen(className);
2593          if(className[len-1] == '>') className[len++] = ' ';
2594          className[len++] = '>';
2595          className[len++] = '\0';
2596       }
2597       return CopyString(className);
2598    }
2599    else
2600       return CopyString(_class.fullName);
2601 }
2602
2603 Type ReplaceThisClassType(Class _class)
2604 {
2605    Type type;
2606    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2607    {
2608       bool first = true;
2609       int p = 0;
2610       ClassTemplateParameter param;
2611       int lastParam = -1;
2612       char className[1024];
2613       strcpy(className, _class.fullName);
2614
2615       for(param = _class.templateParams.first; param; param = param.next)
2616       {
2617          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2618          {
2619             if(first) strcat(className, "<");
2620             if(!first) strcat(className, ", ");
2621             if(lastParam + 1 != p)
2622             {
2623                strcat(className, param.name);
2624                strcat(className, " = ");
2625             }
2626             strcat(className, param.name);
2627             first = false;
2628             lastParam = p;
2629          }
2630          p++;
2631       }
2632       if(!first)
2633       {
2634          int len = strlen(className);
2635          if(className[len-1] == '>') className[len++] = ' ';
2636          className[len++] = '>';
2637          className[len++] = '\0';
2638       }
2639       type = MkClassType(className);
2640       //type = ProcessTypeString(className, false);
2641    }
2642    else
2643    {
2644       type = MkClassType(_class.fullName);
2645       //type = ProcessTypeString(_class.fullName, false);
2646    }
2647    //type.wasThisClass = true;
2648    return type;
2649 }
2650
2651 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2652 {
2653    if(specs != null && _class)
2654    {
2655       Specifier spec;
2656       for(spec = specs.first; spec; spec = spec.next)
2657       {
2658          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2659          {
2660             spec.type = nameSpecifier;
2661             spec.name = ReplaceThisClass(_class);
2662             spec.symbol = FindClass(spec.name); //_class.symbol;
2663          }
2664       }
2665    }
2666 }
2667
2668 // Returns imported or not
2669 bool DeclareFunction(External neededFor, GlobalFunction function, char * name)
2670 {
2671    Symbol symbol = function.symbol;
2672    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2673    if(!symbol || !symbol.pointerExternal)
2674    {
2675       bool imported = false;
2676       bool dllImport = false;
2677
2678       if(!function.dataType)
2679       {
2680          function.dataType = ProcessTypeString(function.dataTypeString, false);
2681          if(!function.dataType.thisClass)
2682             function.dataType.staticMethod = true;
2683       }
2684
2685       if(inCompiler)
2686       {
2687          if(!symbol)
2688          {
2689             ModuleImport module = FindModule(function.module);
2690             // WARNING: This is not added anywhere...
2691             symbol = function.symbol = Symbol {  };
2692
2693             if(module.name)
2694             {
2695                if(!function.dataType.dllExport)
2696                {
2697                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2698                   module.functions.Add(symbol._import);
2699                }
2700             }
2701             // Set the symbol type
2702             {
2703                symbol.type = ProcessTypeString(function.dataTypeString, false);
2704                if(!symbol.type.thisClass)
2705                   symbol.type.staticMethod = true;
2706             }
2707          }
2708          imported = symbol._import ? true : false;
2709          if(imported && function.module != privateModule && function.module.importType != staticImport)
2710             dllImport = true;
2711       }
2712
2713       if(inCompiler)
2714       {
2715          // TOCHECK: What's with the functionExternal check here? Is it Edge breaking / forward declaration?
2716          //if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2717          {
2718             // We need a declaration here :)
2719             Declaration decl;
2720             OldList * specifiers, * declarators;
2721             Declarator d;
2722             Declarator funcDecl;
2723             External external;
2724
2725             specifiers = MkList();
2726             declarators = MkList();
2727
2728             ListAdd(specifiers, MkSpecifier(EXTERN));
2729
2730             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2731             if(dllImport)
2732                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2733
2734             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2735             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2736             if(function.module.importType == staticImport)
2737             {
2738                Specifier spec;
2739                for(spec = specifiers->first; spec; spec = spec.next)
2740                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2741                   {
2742                      specifiers->Remove(spec);
2743                      FreeSpecifier(spec);
2744                      break;
2745                   }
2746             }
2747
2748             funcDecl = GetFuncDecl(d);
2749
2750             // Make sure we don't have empty parameter declarations for static methods...
2751             if(funcDecl && !funcDecl.function.parameters)
2752             {
2753                funcDecl.function.parameters = MkList();
2754                funcDecl.function.parameters->Insert(null,
2755                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2756             }
2757
2758             ListAdd(declarators, MkInitDeclarator(d, null));
2759
2760             {
2761                Context oldCtx = curContext;
2762                curContext = globalContext;
2763                decl = MkDeclaration(specifiers, declarators);
2764                curContext = oldCtx;
2765             }
2766
2767             // Keep a different symbol for the function definition than the declaration...
2768             /* Note: This should be handled by the edge breaking...
2769             if(symbol.pointerExternal && symbol.pointerExternal.type == functionExternal)
2770             {
2771                Symbol functionSymbol { };
2772                // Copy symbol
2773                {
2774                   *functionSymbol = *symbol;
2775                   functionSymbol.string = CopyString(symbol.string);
2776                   if(functionSymbol.type)
2777                      functionSymbol.type.refCount++;
2778                }
2779
2780                excludedSymbols->Add(functionSymbol);
2781
2782                symbol.pointerExternal.symbol = functionSymbol;
2783             }
2784             */
2785             external = MkExternalDeclaration(decl);
2786             ast->Add(external);
2787             external.symbol = symbol;
2788             symbol.pointerExternal = external;
2789
2790             DeclareType(external, function.dataType, true, true);
2791          }
2792       }
2793    }
2794    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2795       neededFor.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
2796    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2797 }
2798
2799 void DeclareGlobalData(External neededFor, GlobalData data)
2800 {
2801    Symbol symbol = data.symbol;
2802    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2803    if(!symbol || !symbol.pointerExternal)
2804    {
2805       if(inCompiler)
2806       {
2807          if(!symbol)
2808             symbol = data.symbol = Symbol { };
2809       }
2810       if(!data.dataType)
2811          data.dataType = ProcessTypeString(data.dataTypeString, false);
2812
2813       if(inCompiler)
2814       {
2815          // We need a declaration here :)
2816          Declaration decl;
2817          OldList * specifiers, * declarators;
2818          Declarator d;
2819          External external;
2820
2821          specifiers = MkList();
2822          declarators = MkList();
2823
2824          ListAdd(specifiers, MkSpecifier(EXTERN));
2825          d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2826          d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2827
2828          ListAdd(declarators, MkInitDeclarator(d, null));
2829
2830          decl = MkDeclaration(specifiers, declarators);
2831          external = MkExternalDeclaration(decl);
2832          if(curExternal)
2833             ast->Insert(curExternal.prev, external);
2834          external.symbol = symbol;
2835          symbol.pointerExternal = external;
2836
2837          DeclareType(external, data.dataType, true, true);
2838       }
2839    }
2840    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2841       neededFor.CreateUniqueEdge(symbol.pointerExternal, false);
2842 }
2843
2844 class Conversion : struct
2845 {
2846    Conversion prev, next;
2847    Property convert;
2848    bool isGet;
2849    Type resultType;
2850 };
2851
2852 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
2853 {
2854    bool status = true;
2855    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
2856       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
2857    {
2858       Class sourceClass = source.kind == classType ? source._class.registered : null;
2859       Class destClass = dest.kind == classType ? dest._class.registered : null;
2860       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
2861          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
2862       {
2863          Type sourceType = source, destType = dest;
2864          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
2865          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
2866          if(!destType.constant && sourceType.constant)
2867          {
2868             status = false;
2869             if(warn)
2870                Compiler_Warning($"discarding const qualifier\n");
2871          }
2872       }
2873    }
2874    return status;
2875 }
2876
2877 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
2878                        bool isConversionExploration, bool warnConst)
2879 {
2880    if(source && dest)
2881    {
2882       if(warnConst)
2883          CheckConstCompatibility(source, dest, true);
2884       // Property convert;
2885
2886       if(source.kind == templateType && dest.kind != templateType)
2887       {
2888          Type type = ProcessTemplateParameterType(source.templateParameter);
2889          if(type) source = type;
2890       }
2891
2892       if(dest.kind == templateType && source.kind != templateType)
2893       {
2894          Type type = ProcessTemplateParameterType(dest.templateParameter);
2895          if(type) dest = type;
2896       }
2897
2898       if(dest.classObjectType == typedObject && dest.kind != functionType)
2899       {
2900          if(source.classObjectType != anyObject)
2901             return true;
2902          else
2903          {
2904             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
2905             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
2906             {
2907                return true;
2908             }
2909          }
2910       }
2911       else
2912       {
2913          if(source.kind != functionType && source.classObjectType == anyObject)
2914             return true;
2915          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
2916             return true;
2917       }
2918
2919       if((dest.kind == structType && source.kind == structType) ||
2920          (dest.kind == unionType && source.kind == unionType))
2921       {
2922          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
2923              (source.members.first && source.members.first == dest.members.first))
2924             return true;
2925       }
2926
2927       if(dest.kind == ellipsisType && source.kind != voidType)
2928          return true;
2929
2930       if(dest.kind == pointerType && dest.type.kind == voidType &&
2931          ((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))
2932          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
2933
2934          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
2935
2936          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
2937          return true;
2938       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
2939          ((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))
2940          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
2941          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
2942
2943          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
2944          return true;
2945
2946       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
2947       {
2948          if(source._class.registered && source._class.registered.type == unitClass)
2949          {
2950             if(conversions != null)
2951             {
2952                if(source._class.registered == dest._class.registered)
2953                   return true;
2954             }
2955             else
2956             {
2957                Class sourceBase, destBase;
2958                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
2959                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
2960                if(sourceBase == destBase)
2961                   return true;
2962             }
2963          }
2964          // Don't match enum inheriting from other enum if resolving enumeration values
2965          // TESTING: !dest.classObjectType
2966          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
2967             (enumBaseType ||
2968                (!source._class.registered || source._class.registered.type != enumClass) ||
2969                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
2970             return true;
2971          else
2972          {
2973             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
2974             if(enumBaseType &&
2975                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
2976                ((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)
2977             {
2978                if(eClass_IsDerived(dest._class.registered, source._class.registered))
2979                {
2980                   return true;
2981                }
2982             }
2983          }
2984       }
2985
2986       // JUST ADDED THIS...
2987       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
2988          return true;
2989
2990       if(doConversion)
2991       {
2992          // Just added this for Straight conversion of ColorAlpha => Color
2993          if(source.kind == classType)
2994          {
2995             Class _class;
2996             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
2997             {
2998                Property convert;
2999                for(convert = _class.conversions.first; convert; convert = convert.next)
3000                {
3001                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3002                   {
3003                      Conversion after = (conversions != null) ? conversions.last : null;
3004
3005                      if(!convert.dataType)
3006                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3007                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
3008                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3009                         MatchTypes(convert.dataType, dest, conversions, null, null,
3010                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
3011                               convert.dataType.kind == classType, false, true, warnConst))
3012                      {
3013                         if(!conversions && !convert.Get)
3014                            return true;
3015                         else if(conversions != null)
3016                         {
3017                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3018                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3019                               (dest.kind != classType || dest._class.registered != _class.base))
3020                               return true;
3021                            else
3022                            {
3023                               Conversion conv { convert = convert, isGet = true };
3024                               // conversions.Add(conv);
3025                               conversions.Insert(after, conv);
3026
3027                               return true;
3028                            }
3029                         }
3030                      }
3031                   }
3032                }
3033             }
3034          }
3035
3036          // MOVING THIS??
3037
3038          if(dest.kind == classType)
3039          {
3040             Class _class;
3041             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3042             {
3043                Property convert;
3044                for(convert = _class.conversions.first; convert; convert = convert.next)
3045                {
3046                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3047                   {
3048                      Type constType = null;
3049                      bool success = false;
3050                      // Conversion after = (conversions != null) ? conversions.last : null;
3051
3052                      if(!convert.dataType)
3053                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3054
3055                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3056                      {
3057                         Type ptrType { };
3058                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3059                         CopyTypeInto(ptrType, convert.dataType.type);
3060                         ptrType.constant = true;
3061                      }
3062
3063                      // Just added this equality check to prevent recursion.... Make it safer?
3064                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3065                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3066                      {
3067                         if(!conversions && !convert.Set)
3068                            success = true;
3069                         else if(conversions != null)
3070                         {
3071                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3072                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3073                               (source.kind != classType || source._class.registered != _class.base))
3074                               success = true;
3075                            else
3076                            {
3077                               // *** Testing this! ***
3078                               Conversion conv { convert = convert };
3079                               conversions.Add(conv);
3080                               //conversions.Insert(after, conv);
3081                               success = true;
3082                            }
3083                         }
3084                      }
3085                      if(constType)
3086                         FreeType(constType);
3087                      if(success)
3088                         return true;
3089                   }
3090                }
3091             }
3092             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3093             {
3094                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3095                   (source.kind != classType || source._class.registered.type != structClass))
3096                   return true;
3097             }*/
3098
3099             // TESTING THIS... IS THIS OK??
3100             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3101             {
3102                if(!dest._class.registered.dataType)
3103                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3104                // Only support this for classes...
3105                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3106                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3107                {
3108                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3109                   {
3110                      return true;
3111                   }
3112                }
3113             }
3114          }
3115
3116          // Moved this lower
3117          if(source.kind == classType)
3118          {
3119             Class _class;
3120             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3121             {
3122                Property convert;
3123                for(convert = _class.conversions.first; convert; convert = convert.next)
3124                {
3125                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3126                   {
3127                      Conversion after = (conversions != null) ? conversions.last : null;
3128
3129                      if(!convert.dataType)
3130                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3131                      if(convert.dataType != source &&
3132                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3133                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3134                      {
3135                         if(!conversions && !convert.Get)
3136                            return true;
3137                         else if(conversions != null)
3138                         {
3139                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3140                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3141                               (dest.kind != classType || dest._class.registered != _class.base))
3142                               return true;
3143                            else
3144                            {
3145                               Conversion conv { convert = convert, isGet = true };
3146
3147                               // conversions.Add(conv);
3148                               conversions.Insert(after, conv);
3149                               return true;
3150                            }
3151                         }
3152                      }
3153                   }
3154                }
3155             }
3156
3157             // TESTING THIS... IS THIS OK??
3158             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3159             {
3160                if(!source._class.registered.dataType)
3161                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3162                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3163                {
3164                   if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, source._class.registered.dataType.kind == classType, source._class.registered.dataType.kind == classType, false, false, warnConst))
3165                      return true;
3166                   // For bool to be accepted by byte, short, etc.
3167                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3168                      return true;
3169                }
3170             }
3171          }
3172       }
3173
3174       if(source.kind == classType || source.kind == subClassType)
3175          ;
3176       else if(dest.kind == source.kind &&
3177          (dest.kind != structType && dest.kind != unionType &&
3178           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3179           return true;
3180       // RECENTLY ADDED THESE
3181       else if(dest.kind == doubleType && source.kind == floatType)
3182          return true;
3183       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3184          return true;
3185       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3186          return true;
3187       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3188          return true;
3189       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3190          return true;
3191       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3192          return true;
3193       else if(source.kind == enumType &&
3194          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3195           return true;
3196       else if(dest.kind == enumType && !isConversionExploration &&
3197          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3198           return true;
3199       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3200               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3201       {
3202          Type paramSource, paramDest;
3203
3204          if(dest.kind == methodType)
3205             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3206          if(source.kind == methodType)
3207             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3208
3209          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3210          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3211          if(dest.kind == methodType)
3212             dest = dest.method.dataType;
3213          if(source.kind == methodType)
3214             source = source.method.dataType;
3215
3216          paramSource = source.params.first;
3217          if(paramSource && paramSource.kind == voidType) paramSource = null;
3218          paramDest = dest.params.first;
3219          if(paramDest && paramDest.kind == voidType) paramDest = null;
3220
3221
3222          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3223             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3224          {
3225             // Source thisClass must be derived from destination thisClass
3226             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3227                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3228             {
3229                if(paramDest && paramDest.kind == classType)
3230                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3231                else
3232                   Compiler_Error($"method class should not take an object\n");
3233                return false;
3234             }
3235             paramDest = paramDest.next;
3236          }
3237          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3238          {
3239             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3240             {
3241                if(dest.thisClass)
3242                {
3243                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3244                   {
3245                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3246                      return false;
3247                   }
3248                }
3249                else
3250                {
3251                   // THIS WAS BACKWARDS:
3252                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3253                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3254                   {
3255                      if(owningClassDest)
3256                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3257                      else
3258                         Compiler_Error($"overriding class expected to be derived from method class\n");
3259                      return false;
3260                   }
3261                }
3262                paramSource = paramSource.next;
3263             }
3264             else
3265             {
3266                if(dest.thisClass)
3267                {
3268                   // Source thisClass must be derived from destination thisClass
3269                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3270                   {
3271                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3272                      return false;
3273                   }
3274                }
3275                else
3276                {
3277                   // THIS WAS BACKWARDS TOO??
3278                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3279                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3280                   {
3281                      //if(owningClass)
3282                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3283                      //else
3284                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3285                      return false;
3286                   }
3287                }
3288             }
3289          }
3290
3291
3292          // Source return type must be derived from destination return type
3293          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3294          {
3295             Compiler_Warning($"incompatible return type for function\n");
3296             return false;
3297          }
3298          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3299          else
3300             CheckConstCompatibility(dest.returnType, source.returnType, true);
3301
3302          // Check parameters
3303
3304          for(; paramDest; paramDest = paramDest.next)
3305          {
3306             if(!paramSource)
3307             {
3308                //Compiler_Warning($"not enough parameters\n");
3309                Compiler_Error($"not enough parameters\n");
3310                return false;
3311             }
3312             {
3313                Type paramDestType = paramDest;
3314                Type paramSourceType = paramSource;
3315                Type type = paramDestType;
3316
3317                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3318                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3319                   paramSource.kind != templateType)
3320                {
3321                   int id = 0;
3322                   ClassTemplateParameter curParam = null;
3323                   Class sClass;
3324                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3325                   {
3326                      id = 0;
3327                      if(sClass.templateClass) sClass = sClass.templateClass;
3328                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3329                      {
3330                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3331                         {
3332                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3333                            {
3334                               if(sClass.templateClass) sClass = sClass.templateClass;
3335                               id += sClass.templateParams.count;
3336                            }
3337                            break;
3338                         }
3339                         id++;
3340                      }
3341                      if(curParam) break;
3342                   }
3343
3344                   if(curParam)
3345                   {
3346                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3347                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3348                   }
3349                }
3350
3351                // paramDest must be derived from paramSource
3352                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3353                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3354                {
3355                   char type[1024];
3356                   type[0] = 0;
3357                   PrintType(paramDest, type, false, true);
3358                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3359
3360                   if(paramDestType != paramDest)
3361                      FreeType(paramDestType);
3362                   return false;
3363                }
3364                if(paramDestType != paramDest)
3365                   FreeType(paramDestType);
3366             }
3367
3368             paramSource = paramSource.next;
3369          }
3370          if(paramSource)
3371          {
3372             Compiler_Error($"too many parameters\n");
3373             return false;
3374          }
3375          return true;
3376       }
3377       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3378       {
3379          return true;
3380       }
3381       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3382          (source.kind == arrayType || source.kind == pointerType))
3383       {
3384          // Pointers to pointer is incompatible with non normal/nohead classes
3385          if(!(dest.type && dest.type.kind == pointerType && source.type.kind == classType && source.type._class &&
3386             source.type._class.registered && (source.type._class.registered.type != normalClass && source.type._class.registered.type != noHeadClass) && !source.type.byReference))
3387          {
3388             ComputeTypeSize(source.type);
3389             ComputeTypeSize(dest.type);
3390             if(source.type.size == dest.type.size && MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3391                return true;
3392          }
3393       }
3394    }
3395    return false;
3396 }
3397
3398 static void FreeConvert(Conversion convert)
3399 {
3400    if(convert.resultType)
3401       FreeType(convert.resultType);
3402 }
3403
3404 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3405                               char * string, OldList conversions)
3406 {
3407    BTNamedLink link;
3408
3409    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3410    {
3411       Class _class = link.data;
3412       if(_class.type == enumClass)
3413       {
3414          OldList converts { };
3415          Type type { };
3416          type.kind = classType;
3417
3418          if(!_class.symbol)
3419             _class.symbol = FindClass(_class.fullName);
3420          type._class = _class.symbol;
3421
3422          if(MatchTypes(type, dest, &converts, null, null, dest.kind != classType || !dest._class || strcmp(dest._class.string, "bool"),
3423                false, false, false, false))
3424          {
3425             NamedLink64 value;
3426             Class enumClass = eSystem_FindClass(privateModule, "enum");
3427             if(enumClass)
3428             {
3429                Class baseClass;
3430                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3431                {
3432                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3433                   for(value = e.values.first; value; value = value.next)
3434                   {
3435                      if(!strcmp(value.name, string))
3436                         break;
3437                   }
3438                   if(value)
3439                   {
3440                      FreeType(sourceExp.expType);
3441
3442                      sourceExp.isConstant = true;
3443                      sourceExp.expType = MkClassType(baseClass.fullName);
3444                      if(inCompiler || inPreCompiler || inDebugger)
3445                      {
3446                         char constant[256];
3447                         FreeExpContents(sourceExp);
3448
3449                         sourceExp.type = constantExp;
3450                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3451                            sprintf(constant, FORMAT64D, value.data);
3452                         else
3453                            sprintf(constant, FORMAT64HEXLL, value.data);
3454                         sourceExp.constant = CopyString(constant);
3455                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3456                      }
3457
3458                      while(converts.first)
3459                      {
3460                         Conversion convert = converts.first;
3461                         converts.Remove(convert);
3462                         conversions.Add(convert);
3463                      }
3464                      delete type;
3465                      return true;
3466                   }
3467                }
3468             }
3469          }
3470          if(converts.first)
3471             converts.Free(FreeConvert);
3472          delete type;
3473       }
3474    }
3475    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3476       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3477          return true;
3478    return false;
3479 }
3480
3481 public bool ModuleVisibility(Module searchIn, Module searchFor)
3482 {
3483    SubModule subModule;
3484
3485    if(searchFor == searchIn)
3486       return true;
3487
3488    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3489    {
3490       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3491       {
3492          if(ModuleVisibility(subModule.module, searchFor))
3493             return true;
3494       }
3495    }
3496    return false;
3497 }
3498
3499 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3500 {
3501    Module module;
3502
3503    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3504       return true;
3505    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3506       return true;
3507    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3508       return true;
3509
3510    for(module = mainModule.application.allModules.first; module; module = module.next)
3511    {
3512       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3513          return true;
3514    }
3515    return false;
3516 }
3517
3518 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3519 {
3520    Type source;
3521    Type realDest = dest;
3522    Type backupSourceExpType = null;
3523    Expression nbExp = GetNonBracketsExp(sourceExp);
3524    Expression computedExp = nbExp;
3525    dest.refCount++;
3526
3527    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3528       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3529    {
3530       computedExp = CopyExpression(nbExp);        // Keep the original expression, but compute for checking enum ranges
3531       ComputeExpression(computedExp /*sourceExp*/);
3532    }
3533
3534    source = sourceExp.expType;
3535
3536    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3537    {
3538       if(computedExp != nbExp)
3539       {
3540          FreeExpression(computedExp);
3541          computedExp = nbExp;
3542       }
3543       FreeType(dest);
3544       return true;
3545    }
3546
3547    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3548    {
3549        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3550        {
3551           Class sourceBase, destBase;
3552           for(sourceBase = source._class.registered;
3553               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3554               sourceBase = sourceBase.base);
3555           for(destBase = dest._class.registered;
3556               destBase && destBase.base && destBase.base.type != systemClass;
3557               destBase = destBase.base);
3558           //if(source._class.registered == dest._class.registered)
3559           if(sourceBase == destBase)
3560           {
3561             if(computedExp != nbExp)
3562             {
3563                FreeExpression(computedExp);
3564                computedExp = nbExp;
3565             }
3566             FreeType(dest);
3567             return true;
3568          }
3569       }
3570    }
3571
3572    if(source)
3573    {
3574       OldList * specs;
3575       bool flag = false;
3576       int64 value = MAXINT;
3577
3578       source.refCount++;
3579
3580       if(computedExp.type == constantExp)
3581       {
3582          if(source.isSigned)
3583             value = strtoll(computedExp.constant, null, 0);
3584          else
3585             value = strtoull(computedExp.constant, null, 0);
3586       }
3587       else if(computedExp.type == opExp && sourceExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3588       {
3589          if(source.isSigned)
3590             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3591          else
3592             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3593       }
3594       if(computedExp != nbExp)
3595       {
3596          FreeExpression(computedExp);
3597          computedExp = nbExp;
3598       }
3599
3600       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3601          !strcmp(source._class.registered.fullName, "unichar" /*"ecere::com::unichar"*/))
3602       {
3603          FreeType(source);
3604          source = Type { kind = intType, isSigned = false, refCount = 1 };
3605       }
3606
3607       if(dest.kind == classType)
3608       {
3609          Class _class = dest._class ? dest._class.registered : null;
3610
3611          if(_class && _class.type == unitClass)
3612          {
3613             if(source.kind != classType)
3614             {
3615                Type tempType { };
3616                Type tempDest, tempSource;
3617
3618                for(; _class.base.type != systemClass; _class = _class.base);
3619                tempSource = dest;
3620                tempDest = tempType;
3621
3622                tempType.kind = classType;
3623                if(!_class.symbol)
3624                   _class.symbol = FindClass(_class.fullName);
3625
3626                tempType._class = _class.symbol;
3627                tempType.truth = dest.truth;
3628                if(tempType._class)
3629                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3630
3631                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3632                backupSourceExpType = sourceExp.expType;
3633                if(dest.passAsTemplate)
3634                {
3635                   // Don't carry passAsTemplate
3636                   sourceExp.expType = { };
3637                   CopyTypeInto(sourceExp.expType, dest);
3638                   sourceExp.expType.passAsTemplate = false;
3639                }
3640                else
3641                {
3642                   sourceExp.expType = dest;
3643                   dest.refCount++;
3644                }
3645                //sourceExp.expType = MkClassType(_class.fullName);
3646                flag = true;
3647
3648                delete tempType;
3649             }
3650          }
3651
3652
3653          // Why wasn't there something like this?
3654          if(_class && _class.type == bitClass && source.kind != classType)
3655          {
3656             if(!dest._class.registered.dataType)
3657                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3658             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3659             {
3660                FreeType(source);
3661                FreeType(sourceExp.expType);
3662                source = sourceExp.expType = MkClassType(dest._class.string);
3663                source.refCount++;
3664
3665                //source.kind = classType;
3666                //source._class = dest._class;
3667             }
3668          }
3669
3670          // Adding two enumerations
3671          /*
3672          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3673          {
3674             if(!source._class.registered.dataType)
3675                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3676             if(!dest._class.registered.dataType)
3677                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3678
3679             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3680             {
3681                FreeType(source);
3682                source = sourceExp.expType = MkClassType(dest._class.string);
3683                source.refCount++;
3684
3685                //source.kind = classType;
3686                //source._class = dest._class;
3687             }
3688          }*/
3689
3690          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3691          {
3692             OldList * specs = MkList();
3693             Declarator decl;
3694             char string[1024];
3695
3696             ReadString(string, sourceExp.string);
3697             decl = SpecDeclFromString(string, specs, null);
3698
3699             FreeExpContents(sourceExp);
3700             FreeType(sourceExp.expType);
3701
3702             sourceExp.type = classExp;
3703             sourceExp._classExp.specifiers = specs;
3704             sourceExp._classExp.decl = decl;
3705             sourceExp.expType = dest;
3706             dest.refCount++;
3707
3708             FreeType(source);
3709             FreeType(dest);
3710             if(backupSourceExpType) FreeType(backupSourceExpType);
3711             return true;
3712          }
3713       }
3714       else if(source.kind == classType)
3715       {
3716          Class _class = source._class ? source._class.registered : null;
3717
3718          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || _class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3719          {
3720             /*
3721             if(dest.kind != classType)
3722             {
3723                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3724                if(!source._class.registered.dataType)
3725                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3726
3727                FreeType(dest);
3728                dest = MkClassType(source._class.string);
3729                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3730                //   dest = MkClassType(source._class.string);
3731             }
3732             */
3733
3734             if(dest.kind != classType)
3735             {
3736                Type tempType { };
3737                Type tempDest, tempSource;
3738
3739                if(!source._class.registered.dataType)
3740                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3741
3742                for(; _class.base.type != systemClass; _class = _class.base);
3743                tempDest = source;
3744                tempSource = tempType;
3745                tempType.kind = classType;
3746                tempType._class = FindClass(_class.fullName);
3747                tempType.truth = source.truth;
3748                tempType.classObjectType = source.classObjectType;
3749
3750                if(tempType._class)
3751                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3752
3753                // PUT THIS BACK TESTING UNITS?
3754                if(conversions && conversions.last)
3755                {
3756                   ((Conversion)(conversions.last)).resultType = dest;
3757                   dest.refCount++;
3758                }
3759
3760                FreeType(sourceExp.expType);
3761                sourceExp.expType = MkClassType(_class.fullName);
3762                sourceExp.expType.truth = source.truth;
3763                sourceExp.expType.classObjectType = source.classObjectType;
3764
3765                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3766
3767                if(!sourceExp.destType)
3768                {
3769                   FreeType(sourceExp.destType);
3770                   sourceExp.destType = sourceExp.expType;
3771                   if(sourceExp.expType)
3772                      sourceExp.expType.refCount++;
3773                }
3774                //flag = true;
3775                //source = _class.dataType;
3776
3777
3778                // TOCHECK: TESTING THIS NEW CODE
3779                if(!_class.dataType)
3780                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3781                FreeType(dest);
3782                dest = MkClassType(source._class.string);
3783                dest.truth = source.truth;
3784                dest.classObjectType = source.classObjectType;
3785
3786                FreeType(source);
3787                source = _class.dataType;
3788                source.refCount++;
3789
3790                delete tempType;
3791             }
3792          }
3793       }
3794
3795       if(!flag)
3796       {
3797          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3798          {
3799             FreeType(source);
3800             FreeType(dest);
3801             return true;
3802          }
3803       }
3804
3805       // Implicit Casts
3806       /*
3807       if(source.kind == classType)
3808       {
3809          Class _class = source._class.registered;
3810          if(_class.type == unitClass)
3811          {
3812             if(!_class.dataType)
3813                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3814             source = _class.dataType;
3815          }
3816       }*/
3817
3818       if(dest.kind == classType)
3819       {
3820          Class _class = dest._class ? dest._class.registered : null;
3821          bool fittingValue = false;
3822          if(_class && _class.type == enumClass)
3823          {
3824             Class enumClass = eSystem_FindClass(privateModule, "enum");
3825             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3826             if(c && value >= 0 && value <= c.largest)
3827                fittingValue = true;
3828          }
3829
3830          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3831             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3832          {
3833             if(_class.type == normalClass || _class.type == noHeadClass)
3834             {
3835                Expression newExp { };
3836                *newExp = *sourceExp;
3837                if(sourceExp.destType) sourceExp.destType.refCount++;
3838                if(sourceExp.expType)  sourceExp.expType.refCount++;
3839                sourceExp.type = castExp;
3840                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3841                sourceExp.cast.exp = newExp;
3842                FreeType(sourceExp.expType);
3843                sourceExp.expType = null;
3844                ProcessExpressionType(sourceExp);
3845
3846                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3847                if(!inCompiler)
3848                {
3849                   FreeType(sourceExp.expType);
3850                   sourceExp.expType = dest;
3851                }
3852
3853                FreeType(source);
3854                if(inCompiler) FreeType(dest);
3855
3856                if(backupSourceExpType) FreeType(backupSourceExpType);
3857                return true;
3858             }
3859
3860             if(!_class.dataType)
3861                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3862             FreeType(dest);
3863             dest = _class.dataType;
3864             dest.refCount++;
3865          }
3866
3867          // Accept lower precision types for units, since we want to keep the unit type
3868          if(dest.kind == doubleType &&
3869             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3870              source.kind == charType || source.kind == _BoolType))
3871          {
3872             specs = MkListOne(MkSpecifier(DOUBLE));
3873          }
3874          else if(dest.kind == floatType &&
3875             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3876             source.kind == _BoolType || source.kind == doubleType))
3877          {
3878             specs = MkListOne(MkSpecifier(FLOAT));
3879          }
3880          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3881             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3882          {
3883             specs = MkList();
3884             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3885             ListAdd(specs, MkSpecifier(INT64));
3886          }
3887          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
3888             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3889          {
3890             specs = MkList();
3891             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3892             ListAdd(specs, MkSpecifier(INT));
3893          }
3894          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
3895             source.kind == floatType || source.kind == doubleType))
3896          {
3897             specs = MkList();
3898             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3899             ListAdd(specs, MkSpecifier(SHORT));
3900          }
3901          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
3902             source.kind == floatType || source.kind == doubleType))
3903          {
3904             specs = MkList();
3905             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3906             ListAdd(specs, MkSpecifier(CHAR));
3907          }
3908          else
3909          {
3910             FreeType(source);
3911             FreeType(dest);
3912             if(backupSourceExpType)
3913             {
3914                // Failed to convert: revert previous exp type
3915                if(sourceExp.expType) FreeType(sourceExp.expType);
3916                sourceExp.expType = backupSourceExpType;
3917             }
3918             return false;
3919          }
3920       }
3921       else if(dest.kind == doubleType &&
3922          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
3923           source.kind == _BoolType || source.kind == charType))
3924       {
3925          specs = MkListOne(MkSpecifier(DOUBLE));
3926       }
3927       else if(dest.kind == floatType &&
3928          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3929       {
3930          specs = MkListOne(MkSpecifier(FLOAT));
3931       }
3932       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3933          (value == 1 || value == 0))
3934       {
3935          specs = MkList();
3936          ListAdd(specs, MkSpecifier(BOOL));
3937       }
3938       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3939          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
3940       {
3941          if(source.kind == intType)
3942          {
3943             FreeType(dest);
3944             FreeType(source);
3945             if(backupSourceExpType) FreeType(backupSourceExpType);
3946             return true;
3947          }
3948          else
3949          {
3950             specs = MkList();
3951             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3952             ListAdd(specs, MkSpecifier(CHAR));
3953          }
3954       }
3955       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
3956          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
3957       {
3958          if(source.kind == intType)
3959          {
3960             FreeType(dest);
3961             FreeType(source);
3962             if(backupSourceExpType) FreeType(backupSourceExpType);
3963             return true;
3964          }
3965          else
3966          {
3967             specs = MkList();
3968             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3969             ListAdd(specs, MkSpecifier(SHORT));
3970          }
3971       }
3972       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
3973       {
3974          specs = MkList();
3975          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3976          ListAdd(specs, MkSpecifier(INT));
3977       }
3978       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
3979       {
3980          specs = MkList();
3981          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3982          ListAdd(specs, MkSpecifier(INT64));
3983       }
3984       else if(dest.kind == enumType &&
3985          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3986       {
3987          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
3988       }
3989       else
3990       {
3991          FreeType(source);
3992          FreeType(dest);
3993          if(backupSourceExpType)
3994          {
3995             // Failed to convert: revert previous exp type
3996             if(sourceExp.expType) FreeType(sourceExp.expType);
3997             sourceExp.expType = backupSourceExpType;
3998          }
3999          return false;
4000       }
4001
4002       if(!flag && !sourceExp.opDestType)
4003       {
4004          Expression newExp { };
4005          *newExp = *sourceExp;
4006          newExp.prev = null;
4007          newExp.next = null;
4008          if(sourceExp.destType) sourceExp.destType.refCount++;
4009          if(sourceExp.expType)  sourceExp.expType.refCount++;
4010
4011          sourceExp.type = castExp;
4012          if(realDest.kind == classType)
4013          {
4014             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
4015             FreeList(specs, FreeSpecifier);
4016          }
4017          else
4018             sourceExp.cast.typeName = MkTypeName(specs, null);
4019          if(newExp.type == opExp)
4020          {
4021             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
4022          }
4023          else
4024             sourceExp.cast.exp = newExp;
4025
4026          FreeType(sourceExp.expType);
4027          sourceExp.expType = null;
4028          ProcessExpressionType(sourceExp);
4029       }
4030       else
4031          FreeList(specs, FreeSpecifier);
4032
4033       FreeType(dest);
4034       FreeType(source);
4035       if(backupSourceExpType) FreeType(backupSourceExpType);
4036
4037       return true;
4038    }
4039    else
4040    {
4041       if(computedExp != nbExp)
4042       {
4043          FreeExpression(computedExp);
4044          computedExp = nbExp;
4045       }
4046
4047       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4048       if(sourceExp.type == identifierExp)
4049       {
4050          Identifier id = sourceExp.identifier;
4051          if(dest.kind == classType)
4052          {
4053             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4054             {
4055                Class _class = dest._class.registered;
4056                Class enumClass = eSystem_FindClass(privateModule, "enum");
4057                if(enumClass)
4058                {
4059                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4060                   {
4061                      NamedLink64 value;
4062                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4063                      for(value = e.values.first; value; value = value.next)
4064                      {
4065                         if(!strcmp(value.name, id.string))
4066                            break;
4067                      }
4068                      if(value)
4069                      {
4070                         FreeType(sourceExp.expType);
4071
4072                         sourceExp.isConstant = true;
4073                         sourceExp.expType = MkClassType(_class.fullName);
4074                         if(inCompiler || inPreCompiler || inDebugger)
4075                         {
4076                            FreeExpContents(sourceExp);
4077
4078                            sourceExp.type = constantExp;
4079                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4080                               sourceExp.constant = PrintInt64(value.data);
4081                            else
4082                               sourceExp.constant = PrintUInt64(value.data);
4083                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4084                         }
4085                         FreeType(dest);
4086                         return true;
4087                      }
4088                   }
4089                }
4090             }
4091          }
4092
4093          // Loop through all enum classes
4094          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4095          {
4096             FreeType(dest);
4097             return true;
4098          }
4099       }
4100       FreeType(dest);
4101    }
4102    return false;
4103 }
4104
4105 #define TERTIARY(o, name, m, t, p) \
4106    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4107    {                                                              \
4108       exp.type = constantExp;                                    \
4109       exp.string = p(op1.m ? op2.m : op3.m);                     \
4110       if(!exp.expType) \
4111          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4112       return true;                                                \
4113    }
4114
4115 #define BINARY(o, name, m, t, p) \
4116    static bool name(Expression exp, Operand op1, Operand op2)   \
4117    {                                                              \
4118       t value2 = op2.m;                                           \
4119       exp.type = constantExp;                                    \
4120       exp.string = p((t)(op1.m o value2));                     \
4121       if(!exp.expType) \
4122          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4123       return true;                                                \
4124    }
4125
4126 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4127    static bool name(Expression exp, Operand op1, Operand op2)   \
4128    {                                                              \
4129       t value2 = op2.m;                                           \
4130       exp.type = constantExp;                                    \
4131       exp.string = p(value2 ? ((t)(op1.m o value2)) : 0);             \
4132       if(!exp.expType) \
4133          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4134       return true;                                                \
4135    }
4136
4137 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4138    static bool name(Expression exp, Operand op1, Operand op2)   \
4139    {                                                              \
4140       t value2 = op2.m;                                           \
4141       exp.type = constantExp;                                    \
4142       exp.string = p((t)(op1.m o value2));             \
4143       if(!exp.expType) \
4144          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4145       return true;                                                \
4146    }
4147
4148 #define UNARY(o, name, m, t, p) \
4149    static bool name(Expression exp, Operand op1)                \
4150    {                                                              \
4151       exp.type = constantExp;                                    \
4152       exp.string = p((t)(o op1.m));                                   \
4153       if(!exp.expType) \
4154          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4155       return true;                                                \
4156    }
4157
4158 #define OPERATOR_ALL(macro, o, name) \
4159    macro(o, Int##name, i, int, PrintInt) \
4160    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4161    macro(o, Int64##name, i64, int64, PrintInt64) \
4162    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4163    macro(o, Short##name, s, short, PrintShort) \
4164    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4165    macro(o, Char##name, c, char, PrintChar) \
4166    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4167    macro(o, Float##name, f, float, PrintFloat) \
4168    macro(o, Double##name, d, double, PrintDouble)
4169
4170 #define OPERATOR_INTTYPES(macro, o, name) \
4171    macro(o, Int##name, i, int, PrintInt) \
4172    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4173    macro(o, Int64##name, i64, int64, PrintInt64) \
4174    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4175    macro(o, Short##name, s, short, PrintShort) \
4176    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4177    macro(o, Char##name, c, char, PrintChar) \
4178    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4179
4180 #define OPERATOR_REALTYPES(macro, o, name) \
4181    macro(o, Float##name, f, float, PrintFloat) \
4182    macro(o, Double##name, d, double, PrintDouble)
4183
4184 // binary arithmetic
4185 OPERATOR_ALL(BINARY, +, Add)
4186 OPERATOR_ALL(BINARY, -, Sub)
4187 OPERATOR_ALL(BINARY, *, Mul)
4188 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4189 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4190 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4191
4192 // unary arithmetic
4193 OPERATOR_ALL(UNARY, -, Neg)
4194
4195 // unary arithmetic increment and decrement
4196 OPERATOR_ALL(UNARY, ++, Inc)
4197 OPERATOR_ALL(UNARY, --, Dec)
4198
4199 // binary arithmetic assignment
4200 OPERATOR_ALL(BINARY, =, Asign)
4201 OPERATOR_ALL(BINARY, +=, AddAsign)
4202 OPERATOR_ALL(BINARY, -=, SubAsign)
4203 OPERATOR_ALL(BINARY, *=, MulAsign)
4204 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4205 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4206 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4207
4208 // binary bitwise
4209 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4210 OPERATOR_INTTYPES(BINARY, |, BitOr)
4211 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4212 OPERATOR_INTTYPES(BINARY, <<, LShift)
4213 OPERATOR_INTTYPES(BINARY, >>, RShift)
4214
4215 // unary bitwise
4216 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4217
4218 // binary bitwise assignment
4219 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4220 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4221 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4222 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4223 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4224
4225 // unary logical negation
4226 OPERATOR_INTTYPES(UNARY, !, Not)
4227
4228 // binary logical equality
4229 OPERATOR_ALL(BINARY, ==, Equ)
4230 OPERATOR_ALL(BINARY, !=, Nqu)
4231
4232 // binary logical
4233 OPERATOR_ALL(BINARY, &&, And)
4234 OPERATOR_ALL(BINARY, ||, Or)
4235
4236 // binary logical relational
4237 OPERATOR_ALL(BINARY, >, Grt)
4238 OPERATOR_ALL(BINARY, <, Sma)
4239 OPERATOR_ALL(BINARY, >=, GrtEqu)
4240 OPERATOR_ALL(BINARY, <=, SmaEqu)
4241
4242 // tertiary condition operator
4243 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4244
4245 //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
4246 #define OPERATOR_TABLE_ALL(name, type) \
4247     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4248                           type##Neg, \
4249                           type##Inc, type##Dec, \
4250                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4251                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4252                           type##BitNot, \
4253                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4254                           type##Not, \
4255                           type##Equ, type##Nqu, \
4256                           type##And, type##Or, \
4257                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4258                         }; \
4259
4260 #define OPERATOR_TABLE_INTTYPES(name, type) \
4261     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4262                           type##Neg, \
4263                           type##Inc, type##Dec, \
4264                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4265                           null, null, null, null, null, \
4266                           null, \
4267                           null, null, null, null, null, \
4268                           null, \
4269                           type##Equ, type##Nqu, \
4270                           type##And, type##Or, \
4271                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4272                         }; \
4273
4274 OPERATOR_TABLE_ALL(int, Int)
4275 OPERATOR_TABLE_ALL(uint, UInt)
4276 OPERATOR_TABLE_ALL(int64, Int64)
4277 OPERATOR_TABLE_ALL(uint64, UInt64)
4278 OPERATOR_TABLE_ALL(short, Short)
4279 OPERATOR_TABLE_ALL(ushort, UShort)
4280 OPERATOR_TABLE_INTTYPES(float, Float)
4281 OPERATOR_TABLE_INTTYPES(double, Double)
4282 OPERATOR_TABLE_ALL(char, Char)
4283 OPERATOR_TABLE_ALL(uchar, UChar)
4284
4285 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4286 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4287 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4288 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4289 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4290 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4291 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4292 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4293
4294 public void ReadString(char * output,  char * string)
4295 {
4296    int len = strlen(string);
4297    int c,d = 0;
4298    bool quoted = false, escaped = false;
4299    for(c = 0; c<len; c++)
4300    {
4301       char ch = string[c];
4302       if(escaped)
4303       {
4304          switch(ch)
4305          {
4306             case 'n': output[d] = '\n'; break;
4307             case 't': output[d] = '\t'; break;
4308             case 'a': output[d] = '\a'; break;
4309             case 'b': output[d] = '\b'; break;
4310             case 'f': output[d] = '\f'; break;
4311             case 'r': output[d] = '\r'; break;
4312             case 'v': output[d] = '\v'; break;
4313             case '\\': output[d] = '\\'; break;
4314             case '\"': output[d] = '\"'; break;
4315             case '\'': output[d] = '\''; break;
4316             default: output[d] = ch;
4317          }
4318          d++;
4319          escaped = false;
4320       }
4321       else
4322       {
4323          if(ch == '\"')
4324             quoted ^= true;
4325          else if(quoted)
4326          {
4327             if(ch == '\\')
4328                escaped = true;
4329             else
4330                output[d++] = ch;
4331          }
4332       }
4333    }
4334    output[d] = '\0';
4335 }
4336
4337 // String Unescape Copy
4338
4339 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4340 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4341 public int UnescapeString(char * d, char * s, int len)
4342 {
4343    int j = 0, k = 0;
4344    char ch;
4345    while(j < len && (ch = s[j]))
4346    {
4347       switch(ch)
4348       {
4349          case '\\':
4350             switch((ch = s[++j]))
4351             {
4352                case 'n': d[k] = '\n'; break;
4353                case 't': d[k] = '\t'; break;
4354                case 'a': d[k] = '\a'; break;
4355                case 'b': d[k] = '\b'; break;
4356                case 'f': d[k] = '\f'; break;
4357                case 'r': d[k] = '\r'; break;
4358                case 'v': d[k] = '\v'; break;
4359                case '\\': d[k] = '\\'; break;
4360                case '\"': d[k] = '\"'; break;
4361                case '\'': d[k] = '\''; break;
4362                default: d[k] = '\\'; d[k] = ch;
4363             }
4364             break;
4365          default:
4366             d[k] = ch;
4367       }
4368       j++, k++;
4369    }
4370    d[k] = '\0';
4371    return k;
4372 }
4373
4374 public char * OffsetEscapedString(char * s, int len, int offset)
4375 {
4376    char ch;
4377    int j = 0, k = 0;
4378    while(j < len && k < offset && (ch = s[j]))
4379    {
4380       if(ch == '\\') ++j;
4381       j++, k++;
4382    }
4383    return (k == offset) ? s + j : null;
4384 }
4385
4386 public Operand GetOperand(Expression exp)
4387 {
4388    Operand op { };
4389    Type type = exp.expType;
4390    if(type)
4391    {
4392       while(type.kind == classType &&
4393          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4394       {
4395          if(!type._class.registered.dataType)
4396             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4397          type = type._class.registered.dataType;
4398
4399       }
4400       if(exp.type == stringExp && op.kind == pointerType)
4401       {
4402          op.ui64 = (uint64)(uintptr)exp.string;
4403          op.kind = pointerType;
4404          op.ops = uint64Ops;
4405       }
4406       else if(exp.isConstant && exp.type == constantExp)
4407       {
4408          op.kind = type.kind;
4409          op.type = type;
4410
4411          switch(op.kind)
4412          {
4413             case _BoolType:
4414             case charType:
4415             {
4416                if(exp.constant[0] == '\'')
4417                {
4418                   op.c = exp.constant[1];
4419                   op.ops = charOps;
4420                }
4421                else if(type.isSigned)
4422                {
4423                   op.c = (char)strtol(exp.constant, null, 0);
4424                   op.ops = charOps;
4425                }
4426                else
4427                {
4428                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4429                   op.ops = ucharOps;
4430                }
4431                break;
4432             }
4433             case shortType:
4434                if(exp.constant[0] == '\'')
4435                {
4436                   op.s = exp.constant[1];
4437                   op.ops = shortOps;
4438                }
4439                else if(type.isSigned)
4440                {
4441                   op.s = (short)strtol(exp.constant, null, 0);
4442                   op.ops = shortOps;
4443                }
4444                else
4445                {
4446                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4447                   op.ops = ushortOps;
4448                }
4449                break;
4450             case intType:
4451             case longType:
4452                if(exp.constant[0] == '\'')
4453                {
4454                   op.i = exp.constant[1];
4455                   op.ops = intOps;
4456                }
4457                else if(type.isSigned)
4458                {
4459                   op.i = (int)strtol(exp.constant, null, 0);
4460                   op.ops = intOps;
4461                }
4462                else
4463                {
4464                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4465                   op.ops = uintOps;
4466                }
4467                op.kind = intType;
4468                break;
4469             case int64Type:
4470                if(type.isSigned)
4471                {
4472                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4473                   op.ops = int64Ops;
4474                }
4475                else
4476                {
4477                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4478                   op.ops = uint64Ops;
4479                }
4480                op.kind = int64Type;
4481                break;
4482             case intPtrType:
4483                if(type.isSigned)
4484                {
4485                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4486                   op.ops = int64Ops;
4487                }
4488                else
4489                {
4490                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4491                   op.ops = uint64Ops;
4492                }
4493                op.kind = int64Type;
4494                break;
4495             case intSizeType:
4496                if(type.isSigned)
4497                {
4498                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4499                   op.ops = int64Ops;
4500                }
4501                else
4502                {
4503                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4504                   op.ops = uint64Ops;
4505                }
4506                op.kind = int64Type;
4507                break;
4508             case floatType:
4509                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4510                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4511                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4512                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4513                else
4514                   op.f = (float)strtod(exp.constant, null);
4515                op.ops = floatOps;
4516                break;
4517             case doubleType:
4518                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4519                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4520                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4521                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4522                else
4523                   op.d = (double)strtod(exp.constant, null);
4524                op.ops = doubleOps;
4525                break;
4526             //case classType:    For when we have operator overloading...
4527             // Pointer additions
4528             //case functionType:
4529             case arrayType:
4530             case pointerType:
4531             case classType:
4532                op.ui64 = _strtoui64(exp.constant, null, 0);
4533                op.kind = pointerType;
4534                op.ops = uint64Ops;
4535                // op.ptrSize =
4536                break;
4537          }
4538       }
4539    }
4540    return op;
4541 }
4542
4543 static int64 GetEnumValue(Class _class, void * ptr)
4544 {
4545    int64 v = 0;
4546    switch(_class.typeSize)
4547    {
4548       case 8:
4549          if(!strcmp(_class.dataTypeString, "uint64"))
4550             v = (int64)*(uint64 *)ptr;
4551          else
4552             v = (int64)*(int64 *)ptr;
4553          break;
4554       case 4:
4555          if(!strcmp(_class.dataTypeString, "uint"))
4556             v = (int64)*(uint *)ptr;
4557          else
4558             v = (int64)*(int *)ptr;
4559          break;
4560       case 2:
4561          if(!strcmp(_class.dataTypeString, "uint16"))
4562             v = (int64)*(uint16 *)ptr;
4563          else
4564             v = (int64)*(short *)ptr;
4565          break;
4566       case 1:
4567          if(!strcmp(_class.dataTypeString, "byte"))
4568             v = (int64)*(byte *)ptr;
4569          else
4570             v = (int64)*(char *)ptr;
4571          break;
4572    }
4573    return v;
4574 }
4575
4576 static __attribute__((unused)) void UnusedFunction()
4577 {
4578    int a;
4579    a.OnGetString(0,0,0);
4580 }
4581 default:
4582 extern int __ecereVMethodID_class_OnGetString;
4583 public:
4584
4585 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4586 {
4587    DataMember dataMember;
4588    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4589    {
4590       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4591          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4592       else
4593       {
4594          Expression exp { };
4595          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4596          Type type;
4597          void * ptr = inst.data + dataMember.offset + offset;
4598          char * result = null;
4599          exp.loc = member.loc = inst.loc;
4600          ((Identifier)member.identifiers->first).loc = inst.loc;
4601
4602          if(!dataMember.dataType)
4603             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4604          type = dataMember.dataType;
4605          if(type.kind == classType)
4606          {
4607             Class _class = type._class.registered;
4608             if(_class.type == enumClass)
4609             {
4610                Class enumClass = eSystem_FindClass(privateModule, "enum");
4611                if(enumClass)
4612                {
4613                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4614                   NamedLink64 item;
4615                   for(item = e.values.first; item; item = item.next)
4616                   {
4617                      if(item.data == GetEnumValue(_class, ptr))
4618                      {
4619                         result = item.name;
4620                         break;
4621                      }
4622                   }
4623                   if(result)
4624                   {
4625                      exp.identifier = MkIdentifier(result);
4626                      exp.type = identifierExp;
4627                      exp.destType = MkClassType(_class.fullName);
4628                      ProcessExpressionType(exp);
4629                   }
4630                }
4631             }
4632             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4633             {
4634                if(!_class.dataType)
4635                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4636                type = _class.dataType;
4637             }
4638          }
4639          if(!result)
4640          {
4641             switch(type.kind)
4642             {
4643                case floatType:
4644                {
4645                   FreeExpContents(exp);
4646
4647                   exp.constant = PrintFloat(*(float*)ptr);
4648                   exp.type = constantExp;
4649                   break;
4650                }
4651                case doubleType:
4652                {
4653                   FreeExpContents(exp);
4654
4655                   exp.constant = PrintDouble(*(double*)ptr);
4656                   exp.type = constantExp;
4657                   break;
4658                }
4659                case intType:
4660                {
4661                   FreeExpContents(exp);
4662
4663                   exp.constant = PrintInt(*(int*)ptr);
4664                   exp.type = constantExp;
4665                   break;
4666                }
4667                case int64Type:
4668                {
4669                   FreeExpContents(exp);
4670
4671                   exp.constant = PrintInt64(*(int64*)ptr);
4672                   exp.type = constantExp;
4673                   break;
4674                }
4675                case intPtrType:
4676                {
4677                   FreeExpContents(exp);
4678                   // TODO: This should probably use proper type
4679                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4680                   exp.type = constantExp;
4681                   break;
4682                }
4683                case intSizeType:
4684                {
4685                   FreeExpContents(exp);
4686                   // TODO: This should probably use proper type
4687                   exp.constant = PrintInt64((int64)*(intsize*)ptr);
4688                   exp.type = constantExp;
4689                   break;
4690                }
4691                default:
4692                   Compiler_Error($"Unhandled type populating instance\n");
4693             }
4694          }
4695          ListAdd(memberList, member);
4696       }
4697
4698       if(parentDataMember.type == unionMember)
4699          break;
4700    }
4701 }
4702
4703 void PopulateInstance(Instantiation inst)
4704 {
4705    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4706    Class _class = classSym.registered;
4707    DataMember dataMember;
4708    OldList * memberList = MkList();
4709    // Added this check and ->Add to prevent memory leaks on bad code
4710    if(!inst.members)
4711       inst.members = MkListOne(MkMembersInitList(memberList));
4712    else
4713       inst.members->Add(MkMembersInitList(memberList));
4714    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4715    {
4716       if(!dataMember.isProperty)
4717       {
4718          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4719             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4720          else
4721          {
4722             Expression exp { };
4723             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4724             Type type;
4725             void * ptr = inst.data + dataMember.offset;
4726             char * result = null;
4727
4728             exp.loc = member.loc = inst.loc;
4729             ((Identifier)member.identifiers->first).loc = inst.loc;
4730
4731             if(!dataMember.dataType)
4732                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4733             type = dataMember.dataType;
4734             if(type.kind == classType)
4735             {
4736                Class _class = type._class.registered;
4737                if(_class.type == enumClass)
4738                {
4739                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4740                   if(enumClass)
4741                   {
4742                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4743                      NamedLink64 item;
4744                      for(item = e.values.first; item; item = item.next)
4745                      {
4746                         if(item.data == GetEnumValue(_class, ptr))
4747                         {
4748                            result = item.name;
4749                            break;
4750                         }
4751                      }
4752                   }
4753                   if(result)
4754                   {
4755                      exp.identifier = MkIdentifier(result);
4756                      exp.type = identifierExp;
4757                      exp.destType = MkClassType(_class.fullName);
4758                      ProcessExpressionType(exp);
4759                   }
4760                }
4761                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4762                {
4763                   if(!_class.dataType)
4764                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4765                   type = _class.dataType;
4766                }
4767             }
4768             if(!result)
4769             {
4770                switch(type.kind)
4771                {
4772                   case floatType:
4773                   {
4774                      exp.constant = PrintFloat(*(float*)ptr);
4775                      exp.type = constantExp;
4776                      break;
4777                   }
4778                   case doubleType:
4779                   {
4780                      exp.constant = PrintDouble(*(double*)ptr);
4781                      exp.type = constantExp;
4782                      break;
4783                   }
4784                   case intType:
4785                   {
4786                      exp.constant = PrintInt(*(int*)ptr);
4787                      exp.type = constantExp;
4788                      break;
4789                   }
4790                   case int64Type:
4791                   {
4792                      exp.constant = PrintInt64(*(int64*)ptr);
4793                      exp.type = constantExp;
4794                      break;
4795                   }
4796                   case intPtrType:
4797                   {
4798                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4799                      exp.type = constantExp;
4800                      break;
4801                   }
4802                   default:
4803                      Compiler_Error($"Unhandled type populating instance\n");
4804                }
4805             }
4806             ListAdd(memberList, member);
4807          }
4808       }
4809    }
4810 }
4811
4812 void ComputeInstantiation(Expression exp)
4813 {
4814    Instantiation inst = exp.instance;
4815    MembersInit members;
4816    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4817    Class _class = classSym ? classSym.registered : null;
4818    DataMember curMember = null;
4819    Class curClass = null;
4820    DataMember subMemberStack[256];
4821    int subMemberStackPos = 0;
4822    uint64 bits = 0;
4823
4824    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4825    {
4826       // Don't recompute the instantiation...
4827       // Non Simple classes will have become constants by now
4828       if(inst.data)
4829          return;
4830
4831       if(_class.type == normalClass || _class.type == noHeadClass)
4832       {
4833          inst.data = (byte *)eInstance_New(_class);
4834          if(_class.type == normalClass)
4835             ((Instance)inst.data)._refCount++;
4836       }
4837       else
4838          inst.data = new0 byte[_class.structSize];
4839    }
4840
4841    if(inst.members)
4842    {
4843       for(members = inst.members->first; members; members = members.next)
4844       {
4845          switch(members.type)
4846          {
4847             case dataMembersInit:
4848             {
4849                if(members.dataMembers)
4850                {
4851                   MemberInit member;
4852                   for(member = members.dataMembers->first; member; member = member.next)
4853                   {
4854                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4855                      bool found = false;
4856
4857                      Property prop = null;
4858                      DataMember dataMember = null;
4859                      uint dataMemberOffset;
4860
4861                      if(!ident)
4862                      {
4863                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4864                         if(curMember)
4865                         {
4866                            if(curMember.isProperty)
4867                               prop = (Property)curMember;
4868                            else
4869                            {
4870                               dataMember = curMember;
4871
4872                               // CHANGED THIS HERE
4873                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4874
4875                               // 2013/17/29 -- It seems that this was missing here!
4876                               if(_class.type == normalClass)
4877                                  dataMemberOffset += _class.base.structSize;
4878                               // dataMemberOffset = dataMember.offset;
4879                            }
4880                            found = true;
4881                         }
4882                      }
4883                      else
4884                      {
4885                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4886                         if(prop)
4887                         {
4888                            found = true;
4889                            if(prop.memberAccess == publicAccess)
4890                            {
4891                               curMember = (DataMember)prop;
4892                               curClass = prop._class;
4893                            }
4894                         }
4895                         else
4896                         {
4897                            DataMember _subMemberStack[256];
4898                            int _subMemberStackPos = 0;
4899
4900                            // FILL MEMBER STACK
4901                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4902
4903                            if(dataMember)
4904                            {
4905                               found = true;
4906                               if(dataMember.memberAccess == publicAccess)
4907                               {
4908                                  curMember = dataMember;
4909                                  curClass = dataMember._class;
4910                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
4911                                  subMemberStackPos = _subMemberStackPos;
4912                               }
4913                            }
4914                         }
4915                      }
4916
4917                      if(found && member.initializer && member.initializer.type == expInitializer)
4918                      {
4919                         Expression value = member.initializer.exp;
4920                         Type type = null;
4921                         bool deepMember = false;
4922                         if(prop)
4923                         {
4924                            type = prop.dataType;
4925                         }
4926                         else if(dataMember)
4927                         {
4928                            if(!dataMember.dataType)
4929                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4930
4931                            type = dataMember.dataType;
4932                         }
4933
4934                         if(ident && ident.next)
4935                         {
4936                            deepMember = true;
4937
4938                            // for(; ident && type; ident = ident.next)
4939                            for(ident = ident.next; ident && type; ident = ident.next)
4940                            {
4941                               if(type.kind == classType)
4942                               {
4943                                  prop = eClass_FindProperty(type._class.registered,
4944                                     ident.string, privateModule);
4945                                  if(prop)
4946                                     type = prop.dataType;
4947                                  else
4948                                  {
4949                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
4950                                        ident.string, &dataMemberOffset, privateModule, null, null);
4951                                     if(dataMember)
4952                                        type = dataMember.dataType;
4953                                  }
4954                               }
4955                               else if(type.kind == structType || type.kind == unionType)
4956                               {
4957                                  Type memberType;
4958                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
4959                                  {
4960                                     if(!strcmp(memberType.name, ident.string))
4961                                     {
4962                                        type = memberType;
4963                                        break;
4964                                     }
4965                                  }
4966                               }
4967                            }
4968                         }
4969                         if(value)
4970                         {
4971                            FreeType(value.destType);
4972                            value.destType = type;
4973                            if(type) type.refCount++;
4974                            ComputeExpression(value);
4975                         }
4976                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
4977                         {
4978                            if(type.kind == classType)
4979                            {
4980                               Class _class = type._class.registered;
4981                               if(_class && (_class.type == bitClass || _class.type == unitClass || _class.type == enumClass))
4982                               {
4983                                  if(!_class.dataType)
4984                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4985                                  type = _class.dataType;
4986                               }
4987                            }
4988
4989                            if(dataMember)
4990                            {
4991                               void * ptr = inst.data + dataMemberOffset;
4992
4993                               if(value.type == constantExp)
4994                               {
4995                                  switch(type.kind)
4996                                  {
4997                                     case intType:
4998                                     {
4999                                        GetInt(value, (int*)ptr);
5000                                        break;
5001                                     }
5002                                     case int64Type:
5003                                     {
5004                                        GetInt64(value, (int64*)ptr);
5005                                        break;
5006                                     }
5007                                     case intPtrType:
5008                                     {
5009                                        GetIntPtr(value, (intptr*)ptr);
5010                                        break;
5011                                     }
5012                                     case intSizeType:
5013                                     {
5014                                        GetIntSize(value, (intsize*)ptr);
5015                                        break;
5016                                     }
5017                                     case floatType:
5018                                     {
5019                                        GetFloat(value, (float*)ptr);
5020                                        break;
5021                                     }
5022                                     case doubleType:
5023                                     {
5024                                        GetDouble(value, (double *)ptr);
5025                                        break;
5026                                     }
5027                                  }
5028                               }
5029                               else if(value.type == instanceExp)
5030                               {
5031                                  if(type.kind == classType)
5032                                  {
5033                                     Class _class = type._class.registered;
5034                                     if(_class.type == structClass)
5035                                     {
5036                                        ComputeTypeSize(type);
5037                                        if(value.instance.data)
5038                                           memcpy(ptr, value.instance.data, type.size);
5039                                     }
5040                                  }
5041                               }
5042                            }
5043                            else if(prop && prop.Set != (void *)(intptr)1)
5044                            {
5045                               if(value.type == instanceExp && value.instance.data)
5046                               {
5047                                  if(type.kind == classType)
5048                                  {
5049                                     Class _class = type._class.registered;
5050                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5051                                     {
5052                                        void (*Set)(void *, void *) = (void *)prop.Set;
5053                                        Set(inst.data, value.instance.data);
5054                                        PopulateInstance(inst);
5055                                     }
5056                                  }
5057                               }
5058                               else if(value.type == constantExp)
5059                               {
5060                                  switch(type.kind)
5061                                  {
5062                                     case doubleType:
5063                                     {
5064                                        void (*Set)(void *, double) = (void *)prop.Set;
5065                                        Set(inst.data, strtod(value.constant, null) );
5066                                        break;
5067                                     }
5068                                     case floatType:
5069                                     {
5070                                        void (*Set)(void *, float) = (void *)prop.Set;
5071                                        Set(inst.data, (float)(strtod(value.constant, null)));
5072                                        break;
5073                                     }
5074                                     case intType:
5075                                     {
5076                                        void (*Set)(void *, int) = (void *)prop.Set;
5077                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5078                                        break;
5079                                     }
5080                                     case int64Type:
5081                                     {
5082                                        void (*Set)(void *, int64) = (void *)prop.Set;
5083                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5084                                        break;
5085                                     }
5086                                     case intPtrType:
5087                                     {
5088                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5089                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5090                                        break;
5091                                     }
5092                                     case intSizeType:
5093                                     {
5094                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5095                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5096                                        break;
5097                                     }
5098                                  }
5099                               }
5100                               else if(value.type == stringExp)
5101                               {
5102                                  char temp[1024];
5103                                  ReadString(temp, value.string);
5104                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5105                               }
5106                            }
5107                         }
5108                         else if(!deepMember && type && _class.type == unitClass)
5109                         {
5110                            if(prop)
5111                            {
5112                               // Only support converting units to units for now...
5113                               if(value.type == constantExp)
5114                               {
5115                                  if(type.kind == classType)
5116                                  {
5117                                     Class _class = type._class.registered;
5118                                     if(_class.type == unitClass)
5119                                     {
5120                                        if(!_class.dataType)
5121                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5122                                        type = _class.dataType;
5123                                     }
5124                                  }
5125                                  // TODO: Assuming same base type for units...
5126                                  switch(type.kind)
5127                                  {
5128                                     case floatType:
5129                                     {
5130                                        float fValue;
5131                                        float (*Set)(float) = (void *)prop.Set;
5132                                        GetFloat(member.initializer.exp, &fValue);
5133                                        exp.constant = PrintFloat(Set(fValue));
5134                                        exp.type = constantExp;
5135                                        break;
5136                                     }
5137                                     case doubleType:
5138                                     {
5139                                        double dValue;
5140                                        double (*Set)(double) = (void *)prop.Set;
5141                                        GetDouble(member.initializer.exp, &dValue);
5142                                        exp.constant = PrintDouble(Set(dValue));
5143                                        exp.type = constantExp;
5144                                        break;
5145                                     }
5146                                  }
5147                               }
5148                            }
5149                         }
5150                         else if(!deepMember && type && _class.type == bitClass)
5151                         {
5152                            if(prop)
5153                            {
5154                               if(value.type == instanceExp && value.instance.data)
5155                               {
5156                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5157                                  bits = Set(value.instance.data);
5158                               }
5159                               else if(value.type == constantExp)
5160                               {
5161                               }
5162                            }
5163                            else if(dataMember)
5164                            {
5165                               BitMember bitMember = (BitMember) dataMember;
5166                               Type type;
5167                               uint64 part = 0;
5168                               bits = (bits & ~bitMember.mask);
5169                               if(!bitMember.dataType)
5170                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5171                               type = bitMember.dataType;
5172                               if(type.kind == classType && type._class && type._class.registered)
5173                               {
5174                                  if(!type._class.registered.dataType)
5175                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5176                                  type = type._class.registered.dataType;
5177                               }
5178                               switch(type.kind)
5179                               {
5180                                  case _BoolType:
5181                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5182                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5183                                  case intType:
5184                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5185                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5186                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5187                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5188                               }
5189                               bits |= part << bitMember.pos;
5190                            }
5191                         }
5192                      }
5193                      else
5194                      {
5195                         if(_class && _class.type == unitClass)
5196                         {
5197                            ComputeExpression(member.initializer.exp);
5198                            exp.constant = member.initializer.exp.constant;
5199                            exp.type = constantExp;
5200
5201                            member.initializer.exp.constant = null;
5202                         }
5203                      }
5204                   }
5205                }
5206                break;
5207             }
5208          }
5209       }
5210    }
5211    if(_class && _class.type == bitClass)
5212    {
5213       exp.constant = PrintHexUInt(bits);
5214       exp.type = constantExp;
5215    }
5216    if(exp.type != instanceExp)
5217    {
5218       FreeInstance(inst);
5219    }
5220 }
5221
5222 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5223 {
5224    bool result = false;
5225    switch(kind)
5226    {
5227       case shortType:
5228          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5229             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5230          break;
5231       case intType:
5232       case longType:
5233          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5234             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5235          break;
5236       case int64Type:
5237          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5238             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5239             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5240          break;
5241       case floatType:
5242          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5243             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5244             result = GetOpFloat(op, &op.f);
5245          break;
5246       case doubleType:
5247          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5248             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5249             result = GetOpDouble(op, &op.d);
5250          break;
5251       case pointerType:
5252          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5253             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5254             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5255          break;
5256       case enumType:
5257          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5258             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5259             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5260          break;
5261       case intPtrType:
5262          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5263             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5264          break;
5265       case intSizeType:
5266          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5267             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5268          break;
5269    }
5270    return result;
5271 }
5272
5273 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5274 {
5275    if(exp.op.op == SIZEOF)
5276    {
5277       FreeExpContents(exp);
5278       exp.type = constantExp;
5279       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5280    }
5281    else
5282    {
5283       if(!exp.op.exp1)
5284       {
5285          switch(exp.op.op)
5286          {
5287             // unary arithmetic
5288             case '+':
5289             {
5290                // Provide default unary +
5291                Expression exp2 = exp.op.exp2;
5292                exp.op.exp2 = null;
5293                FreeExpContents(exp);
5294                FreeType(exp.expType);
5295                FreeType(exp.destType);
5296                *exp = *exp2;
5297                delete exp2;
5298                break;
5299             }
5300             case '-':
5301                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5302                break;
5303             // unary arithmetic increment and decrement
5304                   //OPERATOR_ALL(UNARY, ++, Inc)
5305                   //OPERATOR_ALL(UNARY, --, Dec)
5306             // unary bitwise
5307             case '~':
5308                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5309                break;
5310             // unary logical negation
5311             case '!':
5312                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5313                break;
5314          }
5315       }
5316       else
5317       {
5318          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5319          {
5320             if(Promote(op2, op1.kind, op1.type.isSigned))
5321                op2.kind = op1.kind, op2.ops = op1.ops;
5322             else if(Promote(op1, op2.kind, op2.type.isSigned))
5323                op1.kind = op2.kind, op1.ops = op2.ops;
5324          }
5325          switch(exp.op.op)
5326          {
5327             // binary arithmetic
5328             case '+':
5329                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5330                break;
5331             case '-':
5332                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5333                break;
5334             case '*':
5335                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5336                break;
5337             case '/':
5338                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5339                break;
5340             case '%':
5341                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5342                break;
5343             // binary arithmetic assignment
5344                   //OPERATOR_ALL(BINARY, =, Asign)
5345                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5346                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5347                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5348                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5349                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5350             // binary bitwise
5351             case '&':
5352                if(exp.op.exp2)
5353                {
5354                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5355                }
5356                break;
5357             case '|':
5358                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5359                break;
5360             case '^':
5361                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5362                break;
5363             case LEFT_OP:
5364                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5365                break;
5366             case RIGHT_OP:
5367                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5368                break;
5369             // binary bitwise assignment
5370                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5371                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5372                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5373                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5374                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5375             // binary logical equality
5376             case EQ_OP:
5377                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5378                break;
5379             case NE_OP:
5380                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5381                break;
5382             // binary logical
5383             case AND_OP:
5384                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5385                break;
5386             case OR_OP:
5387                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5388                break;
5389             // binary logical relational
5390             case '>':
5391                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5392                break;
5393             case '<':
5394                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5395                break;
5396             case GE_OP:
5397                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5398                break;
5399             case LE_OP:
5400                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5401                break;
5402          }
5403       }
5404    }
5405 }
5406
5407 void ComputeExpression(Expression exp)
5408 {
5409 #ifdef _DEBUG
5410    char expString[10240];
5411    expString[0] = '\0';
5412    PrintExpression(exp, expString);
5413 #endif
5414
5415    switch(exp.type)
5416    {
5417       case identifierExp:
5418       {
5419          Identifier id = exp.identifier;
5420          if(id && exp.isConstant && !inCompiler && !inPreCompiler && !inDebugger)
5421          {
5422             Class c = (exp.expType && exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
5423             if(c && c.type == enumClass)
5424             {
5425                Class enumClass = eSystem_FindClass(privateModule, "enum");
5426                if(enumClass)
5427                {
5428                   NamedLink64 value;
5429                   EnumClassData e = ACCESS_CLASSDATA(c, enumClass);
5430                   for(value = e.values.first; value; value = value.next)
5431                   {
5432                      if(!strcmp(value.name, id.string))
5433                         break;
5434                   }
5435                   if(value)
5436                   {
5437                      const String dts = c.dataTypeString;
5438                      FreeExpContents(exp);
5439                      exp.type = constantExp;
5440                      exp.constant = (dts && (!strcmp(dts, "int") || !strcmp(dts, "int64") || !strcmp(dts, "short") || !strcmp(dts, "char"))) ? PrintInt64(value.data) : PrintUInt64(value.data);
5441                   }
5442                }
5443             }
5444          }
5445          break;
5446       }
5447       case instanceExp:
5448       {
5449          ComputeInstantiation(exp);
5450          break;
5451       }
5452       /*
5453       case constantExp:
5454          break;
5455       */
5456       case opExp:
5457       {
5458          Expression exp1, exp2 = null;
5459          Operand op1 { };
5460          Operand op2 { };
5461
5462          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5463          if(exp.op.exp2)
5464          {
5465             Expression e = exp.op.exp2;
5466
5467             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5468             {
5469                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5470                {
5471                   if(e.type == extensionCompoundExp)
5472                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5473                   else
5474                      e = e.list->last;
5475                }
5476             }
5477             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5478             {
5479                if(e.type == stringExp && e.string)
5480                {
5481                   char * string = e.string;
5482                   int len = strlen(string);
5483                   char * tmp = new char[len-2+1];
5484                   len = UnescapeString(tmp, string + 1, len - 2);
5485                   delete tmp;
5486                   FreeExpContents(exp);
5487                   exp.type = constantExp;
5488                   exp.constant = PrintUInt(len + 1);
5489                }
5490                else
5491                {
5492                   Type type = e.expType;
5493                   type.refCount++;
5494                   FreeExpContents(exp);
5495                   exp.type = constantExp;
5496                   exp.constant = PrintUInt(ComputeTypeSize(type));
5497                   FreeType(type);
5498                }
5499                break;
5500             }
5501             else
5502                ComputeExpression(exp.op.exp2);
5503          }
5504          if(exp.op.exp1)
5505          {
5506             ComputeExpression(exp.op.exp1);
5507             exp1 = exp.op.exp1;
5508             exp2 = exp.op.exp2;
5509             op1 = GetOperand(exp1);
5510             if(op1.type) op1.type.refCount++;
5511             if(exp2)
5512             {
5513                op2 = GetOperand(exp2);
5514                if(op2.type) op2.type.refCount++;
5515             }
5516          }
5517          else
5518          {
5519             exp1 = exp.op.exp2;
5520             op1 = GetOperand(exp1);
5521             if(op1.type) op1.type.refCount++;
5522          }
5523
5524          CallOperator(exp, exp1, exp2, op1, op2);
5525          /*
5526          switch(exp.op.op)
5527          {
5528             // Unary operators
5529             case '&':
5530                // Also binary
5531                if(exp.op.exp1 && exp.op.exp2)
5532                {
5533                   // Binary And
5534                   if(op1.ops.BitAnd)
5535                   {
5536                      FreeExpContents(exp);
5537                      op1.ops.BitAnd(exp, op1, op2);
5538                   }
5539                }
5540                break;
5541             case '*':
5542                if(exp.op.exp1)
5543                {
5544                   if(op1.ops.Mul)
5545                   {
5546                      FreeExpContents(exp);
5547                      op1.ops.Mul(exp, op1, op2);
5548                   }
5549                }
5550                break;
5551             case '+':
5552                if(exp.op.exp1)
5553                {
5554                   if(op1.ops.Add)
5555                   {
5556                      FreeExpContents(exp);
5557                      op1.ops.Add(exp, op1, op2);
5558                   }
5559                }
5560                else
5561                {
5562                   // Provide default unary +
5563                   Expression exp2 = exp.op.exp2;
5564                   exp.op.exp2 = null;
5565                   FreeExpContents(exp);
5566                   FreeType(exp.expType);
5567                   FreeType(exp.destType);
5568
5569                   *exp = *exp2;
5570                   delete exp2;
5571                }
5572                break;
5573             case '-':
5574                if(exp.op.exp1)
5575                {
5576                   if(op1.ops.Sub)
5577                   {
5578                      FreeExpContents(exp);
5579                      op1.ops.Sub(exp, op1, op2);
5580                   }
5581                }
5582                else
5583                {
5584                   if(op1.ops.Neg)
5585                   {
5586                      FreeExpContents(exp);
5587                      op1.ops.Neg(exp, op1);
5588                   }
5589                }
5590                break;
5591             case '~':
5592                if(op1.ops.BitNot)
5593                {
5594                   FreeExpContents(exp);
5595                   op1.ops.BitNot(exp, op1);
5596                }
5597                break;
5598             case '!':
5599                if(op1.ops.Not)
5600                {
5601                   FreeExpContents(exp);
5602                   op1.ops.Not(exp, op1);
5603                }
5604                break;
5605             // Binary only operators
5606             case '/':
5607                if(op1.ops.Div)
5608                {
5609                   FreeExpContents(exp);
5610                   op1.ops.Div(exp, op1, op2);
5611                }
5612                break;
5613             case '%':
5614                if(op1.ops.Mod)
5615                {
5616                   FreeExpContents(exp);
5617                   op1.ops.Mod(exp, op1, op2);
5618                }
5619                break;
5620             case LEFT_OP:
5621                break;
5622             case RIGHT_OP:
5623                break;
5624             case '<':
5625                if(exp.op.exp1)
5626                {
5627                   if(op1.ops.Sma)
5628                   {
5629                      FreeExpContents(exp);
5630                      op1.ops.Sma(exp, op1, op2);
5631                   }
5632                }
5633                break;
5634             case '>':
5635                if(exp.op.exp1)
5636                {
5637                   if(op1.ops.Grt)
5638                   {
5639                      FreeExpContents(exp);
5640                      op1.ops.Grt(exp, op1, op2);
5641                   }
5642                }
5643                break;
5644             case LE_OP:
5645                if(exp.op.exp1)
5646                {
5647                   if(op1.ops.SmaEqu)
5648                   {
5649                      FreeExpContents(exp);
5650                      op1.ops.SmaEqu(exp, op1, op2);
5651                   }
5652                }
5653                break;
5654             case GE_OP:
5655                if(exp.op.exp1)
5656                {
5657                   if(op1.ops.GrtEqu)
5658                   {
5659                      FreeExpContents(exp);
5660                      op1.ops.GrtEqu(exp, op1, op2);
5661                   }
5662                }
5663                break;
5664             case EQ_OP:
5665                if(exp.op.exp1)
5666                {
5667                   if(op1.ops.Equ)
5668                   {
5669                      FreeExpContents(exp);
5670                      op1.ops.Equ(exp, op1, op2);
5671                   }
5672                }
5673                break;
5674             case NE_OP:
5675                if(exp.op.exp1)
5676                {
5677                   if(op1.ops.Nqu)
5678                   {
5679                      FreeExpContents(exp);
5680                      op1.ops.Nqu(exp, op1, op2);
5681                   }
5682                }
5683                break;
5684             case '|':
5685                if(op1.ops.BitOr)
5686                {
5687                   FreeExpContents(exp);
5688                   op1.ops.BitOr(exp, op1, op2);
5689                }
5690                break;
5691             case '^':
5692                if(op1.ops.BitXor)
5693                {
5694                   FreeExpContents(exp);
5695                   op1.ops.BitXor(exp, op1, op2);
5696                }
5697                break;
5698             case AND_OP:
5699                break;
5700             case OR_OP:
5701                break;
5702             case SIZEOF:
5703                FreeExpContents(exp);
5704                exp.type = constantExp;
5705                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5706                break;
5707          }
5708          */
5709          if(op1.type) FreeType(op1.type);
5710          if(op2.type) FreeType(op2.type);
5711          break;
5712       }
5713       case bracketsExp:
5714       case extensionExpressionExp:
5715       {
5716          Expression e, n;
5717          for(e = exp.list->first; e; e = n)
5718          {
5719             n = e.next;
5720             if(!n)
5721             {
5722                OldList * list = exp.list;
5723                Expression prev = exp.prev;
5724                Expression next = exp.next;
5725                ComputeExpression(e);
5726                //FreeExpContents(exp);
5727                FreeType(exp.expType);
5728                FreeType(exp.destType);
5729                *exp = *e;
5730                exp.prev = prev;
5731                exp.next = next;
5732                delete e;
5733                delete list;
5734             }
5735             else
5736             {
5737                FreeExpression(e);
5738             }
5739          }
5740          break;
5741       }
5742       /*
5743
5744       case ExpIndex:
5745       {
5746          Expression e;
5747          exp.isConstant = true;
5748
5749          ComputeExpression(exp.index.exp);
5750          if(!exp.index.exp.isConstant)
5751             exp.isConstant = false;
5752
5753          for(e = exp.index.index->first; e; e = e.next)
5754          {
5755             ComputeExpression(e);
5756             if(!e.next)
5757             {
5758                // Check if this type is int
5759             }
5760             if(!e.isConstant)
5761                exp.isConstant = false;
5762          }
5763          exp.expType = Dereference(exp.index.exp.expType);
5764          break;
5765       }
5766       */
5767       case memberExp:
5768       {
5769          Expression memberExp = exp.member.exp;
5770          Identifier memberID = exp.member.member;
5771
5772          Type type;
5773          ComputeExpression(exp.member.exp);
5774          type = exp.member.exp.expType;
5775          if(type)
5776          {
5777             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);
5778             Property prop = null;
5779             DataMember member = null;
5780             Class convertTo = null;
5781             if(type.kind == subClassType && exp.member.exp.type == classExp)
5782                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5783
5784             if(!_class)
5785             {
5786                char string[256];
5787                Symbol classSym;
5788                string[0] = '\0';
5789                PrintTypeNoConst(type, string, false, true);
5790                classSym = FindClass(string);
5791                _class = classSym ? classSym.registered : null;
5792             }
5793
5794             if(exp.member.member)
5795             {
5796                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5797                if(!prop)
5798                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5799             }
5800             if(!prop && !member && _class && exp.member.member)
5801             {
5802                Symbol classSym = FindClass(exp.member.member.string);
5803                convertTo = _class;
5804                _class = classSym ? classSym.registered : null;
5805                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5806             }
5807
5808             if(prop)
5809             {
5810                if(prop.compiled)
5811                {
5812                   Type type = prop.dataType;
5813                   // TODO: Assuming same base type for units...
5814                   if(_class.type == unitClass)
5815                   {
5816                      if(type.kind == classType)
5817                      {
5818                         Class _class = type._class.registered;
5819                         if(_class.type == unitClass)
5820                         {
5821                            if(!_class.dataType)
5822                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5823                            type = _class.dataType;
5824                         }
5825                      }
5826                      switch(type.kind)
5827                      {
5828                         case floatType:
5829                         {
5830                            float value;
5831                            float (*Get)(float) = (void *)prop.Get;
5832                            GetFloat(exp.member.exp, &value);
5833                            exp.constant = PrintFloat(Get ? Get(value) : value);
5834                            exp.type = constantExp;
5835                            break;
5836                         }
5837                         case doubleType:
5838                         {
5839                            double value;
5840                            double (*Get)(double);
5841                            GetDouble(exp.member.exp, &value);
5842
5843                            if(convertTo)
5844                               Get = (void *)prop.Set;
5845                            else
5846                               Get = (void *)prop.Get;
5847                            exp.constant = PrintDouble(Get ? Get(value) : value);
5848                            exp.type = constantExp;
5849                            break;
5850                         }
5851                      }
5852                   }
5853                   else
5854                   {
5855                      if(convertTo)
5856                      {
5857                         Expression value = exp.member.exp;
5858                         Type type;
5859                         if(!prop.dataType)
5860                            ProcessPropertyType(prop);
5861
5862                         type = prop.dataType;
5863                         if(!type)
5864                         {
5865                             // printf("Investigate this\n");
5866                         }
5867                         else if(_class.type == structClass)
5868                         {
5869                            switch(type.kind)
5870                            {
5871                               case classType:
5872                               {
5873                                  Class propertyClass = type._class.registered;
5874                                  if(propertyClass.type == structClass && value.type == instanceExp)
5875                                  {
5876                                     void (*Set)(void *, void *) = (void *)prop.Set;
5877                                     exp.instance = Instantiation { };
5878                                     exp.instance.data = new0 byte[_class.structSize];
5879                                     exp.instance._class = MkSpecifierName(_class.fullName);
5880                                     exp.instance.loc = exp.loc;
5881                                     exp.type = instanceExp;
5882                                     Set(exp.instance.data, value.instance.data);
5883                                     PopulateInstance(exp.instance);
5884                                  }
5885                                  break;
5886                               }
5887                               case intType:
5888                               {
5889                                  int intValue;
5890                                  void (*Set)(void *, int) = (void *)prop.Set;
5891
5892                                  exp.instance = Instantiation { };
5893                                  exp.instance.data = new0 byte[_class.structSize];
5894                                  exp.instance._class = MkSpecifierName(_class.fullName);
5895                                  exp.instance.loc = exp.loc;
5896                                  exp.type = instanceExp;
5897
5898                                  GetInt(value, &intValue);
5899
5900                                  Set(exp.instance.data, intValue);
5901                                  PopulateInstance(exp.instance);
5902                                  break;
5903                               }
5904                               case int64Type:
5905                               {
5906                                  int64 intValue;
5907                                  void (*Set)(void *, int64) = (void *)prop.Set;
5908
5909                                  exp.instance = Instantiation { };
5910                                  exp.instance.data = new0 byte[_class.structSize];
5911                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5912                                  exp.instance.loc = exp.loc;
5913                                  exp.type = instanceExp;
5914
5915                                  GetInt64(value, &intValue);
5916
5917                                  Set(exp.instance.data, intValue);
5918                                  PopulateInstance(exp.instance);
5919                                  break;
5920                               }
5921                               case intPtrType:
5922                               {
5923                                  // TOFIX:
5924                                  intptr intValue;
5925                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5926
5927                                  exp.instance = Instantiation { };
5928                                  exp.instance.data = new0 byte[_class.structSize];
5929                                  exp.instance._class = MkSpecifierName(_class.fullName);
5930                                  exp.instance.loc = exp.loc;
5931                                  exp.type = instanceExp;
5932
5933                                  GetIntPtr(value, &intValue);
5934
5935                                  Set(exp.instance.data, intValue);
5936                                  PopulateInstance(exp.instance);
5937                                  break;
5938                               }
5939                               case intSizeType:
5940                               {
5941                                  // TOFIX:
5942                                  intsize intValue;
5943                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5944
5945                                  exp.instance = Instantiation { };
5946                                  exp.instance.data = new0 byte[_class.structSize];
5947                                  exp.instance._class = MkSpecifierName(_class.fullName);
5948                                  exp.instance.loc = exp.loc;
5949                                  exp.type = instanceExp;
5950
5951                                  GetIntSize(value, &intValue);
5952
5953                                  Set(exp.instance.data, intValue);
5954                                  PopulateInstance(exp.instance);
5955                                  break;
5956                               }
5957                               case floatType:
5958                               {
5959                                  float floatValue;
5960                                  void (*Set)(void *, float) = (void *)prop.Set;
5961
5962                                  exp.instance = Instantiation { };
5963                                  exp.instance.data = new0 byte[_class.structSize];
5964                                  exp.instance._class = MkSpecifierName(_class.fullName);
5965                                  exp.instance.loc = exp.loc;
5966                                  exp.type = instanceExp;
5967
5968                                  GetFloat(value, &floatValue);
5969
5970                                  Set(exp.instance.data, floatValue);
5971                                  PopulateInstance(exp.instance);
5972                                  break;
5973                               }
5974                               case doubleType:
5975                               {
5976                                  double doubleValue;
5977                                  void (*Set)(void *, double) = (void *)prop.Set;
5978
5979                                  exp.instance = Instantiation { };
5980                                  exp.instance.data = new0 byte[_class.structSize];
5981                                  exp.instance._class = MkSpecifierName(_class.fullName);
5982                                  exp.instance.loc = exp.loc;
5983                                  exp.type = instanceExp;
5984
5985                                  GetDouble(value, &doubleValue);
5986
5987                                  Set(exp.instance.data, doubleValue);
5988                                  PopulateInstance(exp.instance);
5989                                  break;
5990                               }
5991                            }
5992                         }
5993                         else if(_class.type == bitClass)
5994                         {
5995                            switch(type.kind)
5996                            {
5997                               case classType:
5998                               {
5999                                  Class propertyClass = type._class.registered;
6000                                  if(propertyClass.type == structClass && value.instance.data)
6001                                  {
6002                                     unsigned int (*Set)(void *) = (void *)prop.Set;
6003                                     unsigned int bits = Set(value.instance.data);
6004                                     exp.constant = PrintHexUInt(bits);
6005                                     exp.type = constantExp;
6006                                     break;
6007                                  }
6008                                  else if(_class.type == bitClass)
6009                                  {
6010                                     unsigned int value;
6011                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
6012                                     unsigned int bits;
6013
6014                                     GetUInt(exp.member.exp, &value);
6015                                     bits = Set(value);
6016                                     exp.constant = PrintHexUInt(bits);
6017                                     exp.type = constantExp;
6018                                  }
6019                               }
6020                            }
6021                         }
6022                      }
6023                      else
6024                      {
6025                         if(_class.type == bitClass)
6026                         {
6027                            unsigned int value;
6028                            GetUInt(exp.member.exp, &value);
6029
6030                            switch(type.kind)
6031                            {
6032                               case classType:
6033                               {
6034                                  Class _class = type._class.registered;
6035                                  if(_class.type == structClass)
6036                                  {
6037                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6038
6039                                     exp.instance = Instantiation { };
6040                                     exp.instance.data = new0 byte[_class.structSize];
6041                                     exp.instance._class = MkSpecifierName(_class.fullName);
6042                                     exp.instance.loc = exp.loc;
6043                                     //exp.instance.fullSet = true;
6044                                     exp.type = instanceExp;
6045                                     Get(value, exp.instance.data);
6046                                     PopulateInstance(exp.instance);
6047                                  }
6048                                  else if(_class.type == bitClass)
6049                                  {
6050                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6051                                     uint64 bits = Get(value);
6052                                     exp.constant = PrintHexUInt64(bits);
6053                                     exp.type = constantExp;
6054                                  }
6055                                  break;
6056                               }
6057                            }
6058                         }
6059                         else if(_class.type == structClass)
6060                         {
6061                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6062                            switch(type.kind)
6063                            {
6064                               case classType:
6065                               {
6066                                  Class _class = type._class.registered;
6067                                  if(_class.type == structClass && value)
6068                                  {
6069                                     void (*Get)(void *, void *) = (void *)prop.Get;
6070
6071                                     exp.instance = Instantiation { };
6072                                     exp.instance.data = new0 byte[_class.structSize];
6073                                     exp.instance._class = MkSpecifierName(_class.fullName);
6074                                     exp.instance.loc = exp.loc;
6075                                     //exp.instance.fullSet = true;
6076                                     exp.type = instanceExp;
6077                                     Get(value, exp.instance.data);
6078                                     PopulateInstance(exp.instance);
6079                                  }
6080                                  break;
6081                               }
6082                            }
6083                         }
6084                         /*else
6085                         {
6086                            char * value = exp.member.exp.instance.data;
6087                            switch(type.kind)
6088                            {
6089                               case classType:
6090                               {
6091                                  Class _class = type._class.registered;
6092                                  if(_class.type == normalClass)
6093                                  {
6094                                     void *(*Get)(void *) = (void *)prop.Get;
6095
6096                                     exp.instance = Instantiation { };
6097                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6098                                     exp.type = instanceExp;
6099                                     exp.instance.data = Get(value, exp.instance.data);
6100                                  }
6101                                  break;
6102                               }
6103                            }
6104                         }
6105                         */
6106                      }
6107                   }
6108                }
6109                else
6110                {
6111                   exp.isConstant = false;
6112                }
6113             }
6114             else if(member)
6115             {
6116             }
6117          }
6118
6119          if(exp.type != ExpressionType::memberExp)
6120          {
6121             FreeExpression(memberExp);
6122             FreeIdentifier(memberID);
6123          }
6124          break;
6125       }
6126       case typeSizeExp:
6127       {
6128          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6129          FreeExpContents(exp);
6130          exp.constant = PrintUInt(ComputeTypeSize(type));
6131          exp.type = constantExp;
6132          FreeType(type);
6133          break;
6134       }
6135       case classSizeExp:
6136       {
6137          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6138          if(classSym && classSym.registered)
6139          {
6140             if(classSym.registered.fixed)
6141             {
6142                FreeSpecifier(exp._class);
6143                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6144                exp.type = constantExp;
6145             }
6146             else
6147             {
6148                char className[1024];
6149                strcpy(className, "__ecereClass_");
6150                FullClassNameCat(className, classSym.string, true);
6151
6152                DeclareClass(curExternal, classSym, className);
6153
6154                FreeExpContents(exp);
6155                exp.type = pointerExp;
6156                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6157                exp.member.member = MkIdentifier("structSize");
6158             }
6159          }
6160          break;
6161       }
6162       case castExp:
6163       //case constantExp:
6164       {
6165          Type type;
6166          Expression e = exp;
6167          if(exp.type == castExp)
6168          {
6169             if(exp.cast.exp)
6170                ComputeExpression(exp.cast.exp);
6171             e = exp.cast.exp;
6172          }
6173          if(e && exp.expType)
6174          {
6175             /*if(exp.destType)
6176                type = exp.destType;
6177             else*/
6178                type = exp.expType;
6179             if(type.kind == classType)
6180             {
6181                Class _class = type._class.registered;
6182                if(_class && (_class.type == unitClass || _class.type == bitClass))
6183                {
6184                   if(!_class.dataType)
6185                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6186                   type = _class.dataType;
6187                }
6188             }
6189
6190             switch(type.kind)
6191             {
6192                case _BoolType:
6193                case charType:
6194                   if(type.isSigned)
6195                   {
6196                      char value = 0;
6197                      if(GetChar(e, &value))
6198                      {
6199                         FreeExpContents(exp);
6200                         exp.constant = PrintChar(value);
6201                         exp.type = constantExp;
6202                      }
6203                   }
6204                   else
6205                   {
6206                      unsigned char value = 0;
6207                      if(GetUChar(e, &value))
6208                      {
6209                         FreeExpContents(exp);
6210                         exp.constant = PrintUChar(value);
6211                         exp.type = constantExp;
6212                      }
6213                   }
6214                   break;
6215                case shortType:
6216                   if(type.isSigned)
6217                   {
6218                      short value = 0;
6219                      if(GetShort(e, &value))
6220                      {
6221                         FreeExpContents(exp);
6222                         exp.constant = PrintShort(value);
6223                         exp.type = constantExp;
6224                      }
6225                   }
6226                   else
6227                   {
6228                      unsigned short value = 0;
6229                      if(GetUShort(e, &value))
6230                      {
6231                         FreeExpContents(exp);
6232                         exp.constant = PrintUShort(value);
6233                         exp.type = constantExp;
6234                      }
6235                   }
6236                   break;
6237                case intType:
6238                   if(type.isSigned)
6239                   {
6240                      int value = 0;
6241                      if(GetInt(e, &value))
6242                      {
6243                         FreeExpContents(exp);
6244                         exp.constant = PrintInt(value);
6245                         exp.type = constantExp;
6246                      }
6247                   }
6248                   else
6249                   {
6250                      unsigned int value = 0;
6251                      if(GetUInt(e, &value))
6252                      {
6253                         FreeExpContents(exp);
6254                         exp.constant = PrintUInt(value);
6255                         exp.type = constantExp;
6256                      }
6257                   }
6258                   break;
6259                case int64Type:
6260                   if(type.isSigned)
6261                   {
6262                      int64 value = 0;
6263                      if(GetInt64(e, &value))
6264                      {
6265                         FreeExpContents(exp);
6266                         exp.constant = PrintInt64(value);
6267                         exp.type = constantExp;
6268                      }
6269                   }
6270                   else
6271                   {
6272                      uint64 value = 0;
6273                      if(GetUInt64(e, &value))
6274                      {
6275                         FreeExpContents(exp);
6276                         exp.constant = PrintUInt64(value);
6277                         exp.type = constantExp;
6278                      }
6279                   }
6280                   break;
6281                case intPtrType:
6282                   if(type.isSigned)
6283                   {
6284                      intptr value = 0;
6285                      if(GetIntPtr(e, &value))
6286                      {
6287                         FreeExpContents(exp);
6288                         exp.constant = PrintInt64((int64)value);
6289                         exp.type = constantExp;
6290                      }
6291                   }
6292                   else
6293                   {
6294                      uintptr value = 0;
6295                      if(GetUIntPtr(e, &value))
6296                      {
6297                         FreeExpContents(exp);
6298                         exp.constant = PrintUInt64((uint64)value);
6299                         exp.type = constantExp;
6300                      }
6301                   }
6302                   break;
6303                case intSizeType:
6304                   if(type.isSigned)
6305                   {
6306                      intsize value = 0;
6307                      if(GetIntSize(e, &value))
6308                      {
6309                         FreeExpContents(exp);
6310                         exp.constant = PrintInt64((int64)value);
6311                         exp.type = constantExp;
6312                      }
6313                   }
6314                   else
6315                   {
6316                      uintsize value = 0;
6317                      if(GetUIntSize(e, &value))
6318                      {
6319                         FreeExpContents(exp);
6320                         exp.constant = PrintUInt64((uint64)value);
6321                         exp.type = constantExp;
6322                      }
6323                   }
6324                   break;
6325                case floatType:
6326                {
6327                   float value = 0;
6328                   if(GetFloat(e, &value))
6329                   {
6330                      FreeExpContents(exp);
6331                      exp.constant = PrintFloat(value);
6332                      exp.type = constantExp;
6333                   }
6334                   break;
6335                }
6336                case doubleType:
6337                {
6338                   double value = 0;
6339                   if(GetDouble(e, &value))
6340                   {
6341                      FreeExpContents(exp);
6342                      exp.constant = PrintDouble(value);
6343                      exp.type = constantExp;
6344                   }
6345                   break;
6346                }
6347             }
6348          }
6349          break;
6350       }
6351       case conditionExp:
6352       {
6353          Operand op1 { };
6354          Operand op2 { };
6355          Operand op3 { };
6356
6357          if(exp.cond.exp)
6358             // Caring only about last expression for now...
6359             ComputeExpression(exp.cond.exp->last);
6360          if(exp.cond.elseExp)
6361             ComputeExpression(exp.cond.elseExp);
6362          if(exp.cond.cond)
6363             ComputeExpression(exp.cond.cond);
6364
6365          op1 = GetOperand(exp.cond.cond);
6366          if(op1.type) op1.type.refCount++;
6367          op2 = GetOperand(exp.cond.exp->last);
6368          if(op2.type) op2.type.refCount++;
6369          op3 = GetOperand(exp.cond.elseExp);
6370          if(op3.type) op3.type.refCount++;
6371
6372          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6373          if(op1.type) FreeType(op1.type);
6374          if(op2.type) FreeType(op2.type);
6375          if(op3.type) FreeType(op3.type);
6376          break;
6377       }
6378    }
6379 }
6380
6381 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6382 {
6383    bool result = true;
6384    if(destType)
6385    {
6386       OldList converts { };
6387       Conversion convert;
6388
6389       if(destType.kind == voidType)
6390          return false;
6391
6392       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6393          result = false;
6394       if(converts.count)
6395       {
6396          // for(convert = converts.last; convert; convert = convert.prev)
6397          for(convert = converts.first; convert; convert = convert.next)
6398          {
6399             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6400             if(!empty)
6401             {
6402                Expression newExp { };
6403                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6404
6405                // TODO: Check this...
6406                *newExp = *exp;
6407                newExp.prev = null;
6408                newExp.next = null;
6409                newExp.destType = null;
6410
6411                if(convert.isGet)
6412                {
6413                   // [exp].ColorRGB
6414                   exp.type = memberExp;
6415                   exp.addedThis = true;
6416                   exp.member.exp = newExp;
6417                   FreeType(exp.member.exp.expType);
6418
6419                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6420                   exp.member.exp.expType.classObjectType = objectType;
6421                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6422                   exp.member.memberType = propertyMember;
6423                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6424                   // TESTING THIS... for (int)degrees
6425                   exp.needCast = true;
6426                   if(exp.expType) exp.expType.refCount++;
6427                   ApplyAnyObjectLogic(exp.member.exp);
6428                }
6429                else
6430                {
6431
6432                   /*if(exp.isConstant)
6433                   {
6434                      // Color { ColorRGB = [exp] };
6435                      exp.type = instanceExp;
6436                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6437                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6438                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6439                   }
6440                   else*/
6441                   {
6442                      // If not constant, don't turn it yet into an instantiation
6443                      // (Go through the deep members system first)
6444                      exp.type = memberExp;
6445                      exp.addedThis = true;
6446                      exp.member.exp = newExp;
6447
6448                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6449                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6450                         newExp.expType._class.registered.type == noHeadClass)
6451                      {
6452                         newExp.byReference = true;
6453                      }
6454
6455                      FreeType(exp.member.exp.expType);
6456                      /*exp.member.exp.expType = convert.convert.dataType;
6457                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6458                      exp.member.exp.expType = null;
6459                      if(convert.convert.dataType)
6460                      {
6461                         exp.member.exp.expType = { };
6462                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6463                         exp.member.exp.expType.refCount = 1;
6464                         exp.member.exp.expType.classObjectType = objectType;
6465                         ApplyAnyObjectLogic(exp.member.exp);
6466                      }
6467
6468                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6469                      exp.member.memberType = reverseConversionMember;
6470                      exp.expType = convert.resultType ? convert.resultType :
6471                         MkClassType(convert.convert._class.fullName);
6472                      exp.needCast = true;
6473                      if(convert.resultType) convert.resultType.refCount++;
6474                   }
6475                }
6476             }
6477             else
6478             {
6479                FreeType(exp.expType);
6480                if(convert.isGet)
6481                {
6482                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6483                   if(exp.destType.casted)
6484                      exp.needCast = true;
6485                   if(exp.expType) exp.expType.refCount++;
6486                }
6487                else
6488                {
6489                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6490                   if(exp.destType.casted)
6491                      exp.needCast = true;
6492                   if(convert.resultType)
6493                      convert.resultType.refCount++;
6494                }
6495             }
6496          }
6497          if(exp.isConstant && inCompiler)
6498             ComputeExpression(exp);
6499
6500          converts.Free(FreeConvert);
6501       }
6502
6503       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6504       {
6505          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6506       }
6507       if(!result && exp.expType && exp.destType)
6508       {
6509          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6510              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6511             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6512             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6513             result = true;
6514       }
6515    }
6516    // if(result) CheckTemplateTypes(exp);
6517    return result;
6518 }
6519
6520 void CheckTemplateTypes(Expression exp)
6521 {
6522    /*
6523    bool et = exp.expType ? exp.expType.passAsTemplate : false;
6524    bool dt = exp.destType ? exp.destType.passAsTemplate : false;
6525    */
6526    Expression nbExp = GetNonBracketsExp(exp);
6527    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6528       (nbExp == exp || nbExp.type != castExp))
6529    {
6530       Expression newExp { };
6531       Context context;
6532       TypeKind kind = exp.expType.kind;
6533       *newExp = *exp;
6534       if(exp.destType) exp.destType.refCount++;
6535       if(exp.expType)  exp.expType.refCount++;
6536       newExp.prev = null;
6537       newExp.next = null;
6538
6539       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6540       {
6541          Class c = exp.expType._class.registered;
6542          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6543          {
6544             if(!c.dataType)
6545                c.dataType = ProcessTypeString(c.dataTypeString, false);
6546             kind = c.dataType.kind;
6547          }
6548       }
6549
6550       switch(kind)
6551       {
6552          case doubleType:
6553             if(exp.destType.classObjectType)
6554             {
6555                // We need to pass the address, just pass it along (Undo what was done above)
6556                if(exp.destType) exp.destType.refCount--;
6557                if(exp.expType)  exp.expType.refCount--;
6558                delete newExp;
6559             }
6560             else
6561             {
6562                // If we're looking for value:
6563                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6564                OldList * specs;
6565                OldList * unionDefs = MkList();
6566                OldList * statements = MkList();
6567                context = PushContext();
6568                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6569                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6570                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6571                exp.type = extensionCompoundExp;
6572                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6573                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6574                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6575                exp.compound.compound.context = context;
6576                PopContext(context);
6577             }
6578             break;
6579          default:
6580             exp.type = castExp;
6581             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6582             if((exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass) || exp.expType.isPointerType)
6583                exp.cast.exp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), MkExpBrackets(MkListOne(newExp)));
6584             else
6585                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6586             exp.needCast = true;
6587             break;
6588       }
6589    }
6590    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6591    {
6592       Expression newExp { };
6593       Context context;
6594       TypeKind kind = exp.expType.kind;
6595       *newExp = *exp;
6596       if(exp.destType) exp.destType.refCount++;
6597       if(exp.expType)  exp.expType.refCount++;
6598       newExp.prev = null;
6599       newExp.next = null;
6600
6601       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6602       {
6603          Class c = exp.expType._class.registered;
6604          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6605          {
6606             if(!c.dataType)
6607                c.dataType = ProcessTypeString(c.dataTypeString, false);
6608             kind = c.dataType.kind;
6609          }
6610       }
6611
6612       switch(kind)
6613       {
6614          case doubleType:
6615             if(exp.destType.classObjectType)
6616             {
6617                // We need to pass the address, just pass it along (Undo what was done above)
6618                if(exp.destType) exp.destType.refCount--;
6619                if(exp.expType)  exp.expType.refCount--;
6620                delete newExp;
6621             }
6622             else
6623             {
6624                // If we're looking for value:
6625                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6626                OldList * specs;
6627                OldList * unionDefs = MkList();
6628                OldList * statements = MkList();
6629                context = PushContext();
6630                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6631                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6632                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6633                exp.type = extensionCompoundExp;
6634                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6635                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6636                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6637                exp.compound.compound.context = context;
6638                PopContext(context);
6639             }
6640             break;
6641          case classType:
6642          {
6643             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6644             {
6645                exp.type = bracketsExp;
6646
6647                newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6648                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6649                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6650                ProcessExpressionType(exp.list->first);
6651                break;
6652             }
6653             else
6654             {
6655                exp.type = bracketsExp;
6656                if(exp.expType.isPointerType)
6657                {
6658                   exp.needTemplateCast = 2;
6659                   newExp.needCast = true;
6660                   newExp.needTemplateCast = 2;
6661                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6662                }
6663
6664                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6665                exp.needTemplateCast = 2;
6666                newExp.needCast = true;
6667                newExp.needTemplateCast = 2;
6668                ProcessExpressionType(exp.list->first);
6669                break;
6670             }
6671          }
6672          default:
6673          {
6674             if(exp.expType.kind == templateType)
6675             {
6676                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6677                if(type)
6678                {
6679                   FreeType(exp.destType);
6680                   FreeType(exp.expType);
6681                   delete newExp;
6682                   break;
6683                }
6684             }
6685             /*if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6686             {
6687                // When was this required?    Removed to address using templated values to pass to printf()
6688                exp.type = opExp;
6689                exp.op.op = '*';
6690                exp.op.exp1 = null;
6691                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6692                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6693             }
6694             else*/
6695             {
6696                char typeString[1024];
6697                Declarator decl;
6698                OldList * specs = MkList();
6699                typeString[0] = '\0';
6700                PrintType(exp.expType, typeString, false, false);
6701                decl = SpecDeclFromString(typeString, specs, null);
6702
6703                exp.type = castExp;
6704                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6705                exp.cast.typeName = MkTypeName(specs, decl);
6706                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6707                exp.cast.exp.needCast = true;
6708                exp.needTemplateCast = 2;
6709                newExp.needTemplateCast = 2;
6710             }
6711             break;
6712          }
6713       }
6714    }
6715 }
6716 // TODO: The Symbol tree should be reorganized by namespaces
6717 // Name Space:
6718 //    - Tree of all symbols within (stored without namespace)
6719 //    - Tree of sub-namespaces
6720
6721 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6722 {
6723    int nsLen = strlen(nameSpace);
6724    Symbol symbol;
6725    // Start at the name space prefix
6726    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6727    {
6728       char * s = symbol.string;
6729       if(!strncmp(s, nameSpace, nsLen))
6730       {
6731          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6732          int c;
6733          char * namePart;
6734          for(c = strlen(s)-1; c >= 0; c--)
6735             if(s[c] == ':')
6736                break;
6737
6738          namePart = s+c+1;
6739          if(!strcmp(namePart, name))
6740          {
6741             // TODO: Error on ambiguity
6742             return symbol;
6743          }
6744       }
6745       else
6746          break;
6747    }
6748    return null;
6749 }
6750
6751 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6752 {
6753    int c;
6754    char nameSpace[1024];
6755    const char * namePart;
6756    bool gotColon = false;
6757
6758    nameSpace[0] = '\0';
6759    for(c = strlen(name)-1; c >= 0; c--)
6760       if(name[c] == ':')
6761       {
6762          gotColon = true;
6763          break;
6764       }
6765
6766    namePart = name+c+1;
6767    while(c >= 0 && name[c] == ':') c--;
6768    if(c >= 0)
6769    {
6770       // Try an exact match first
6771       Symbol symbol = (Symbol)tree.FindString(name);
6772       if(symbol)
6773          return symbol;
6774
6775       // Namespace specified
6776       memcpy(nameSpace, name, c + 1);
6777       nameSpace[c+1] = 0;
6778
6779       return ScanWithNameSpace(tree, nameSpace, namePart);
6780    }
6781    else if(gotColon)
6782    {
6783       // Looking for a global symbol, e.g. ::Sleep()
6784       Symbol symbol = (Symbol)tree.FindString(namePart);
6785       return symbol;
6786    }
6787    else
6788    {
6789       // Name only (no namespace specified)
6790       Symbol symbol = (Symbol)tree.FindString(namePart);
6791       if(symbol)
6792          return symbol;
6793       return ScanWithNameSpace(tree, "", namePart);
6794    }
6795    return null;
6796 }
6797
6798 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6799 {
6800 #ifdef _DEBUG
6801    //Time startTime = GetTime();
6802 #endif
6803    // Optimize this later? Do this before/less?
6804    Context ctx;
6805    Symbol symbol = null;
6806
6807    // First, check if the identifier is declared inside the function
6808    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6809
6810    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6811    {
6812       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6813       {
6814          symbol = null;
6815          if(thisNameSpace)
6816          {
6817             char curName[1024];
6818             strcpy(curName, thisNameSpace);
6819             strcat(curName, "::");
6820             strcat(curName, name);
6821             // Try to resolve in current namespace first
6822             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6823          }
6824          if(!symbol)
6825             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6826       }
6827       else
6828          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6829
6830       if(symbol || ctx == endContext) break;
6831    }
6832    if(inCompiler && symbol && ctx == globalContext && symbol.pointerExternal && curExternal && symbol.pointerExternal != curExternal)
6833       curExternal.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
6834 #ifdef _DEBUG
6835    //findSymbolTotalTime += GetTime() - startTime;
6836 #endif
6837    return symbol;
6838 }
6839
6840 static void GetTypeSpecs(Type type, OldList * specs)
6841 {
6842    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6843    switch(type.kind)
6844    {
6845       case classType:
6846       {
6847          if(type._class.registered)
6848          {
6849             if(!type._class.registered.dataType)
6850                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6851             GetTypeSpecs(type._class.registered.dataType, specs);
6852          }
6853          break;
6854       }
6855       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6856       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6857       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6858       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6859       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6860       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6861       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6862       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6863       case intType:
6864       default:
6865          ListAdd(specs, MkSpecifier(INT)); break;
6866    }
6867 }
6868
6869 static void PrintArraySize(Type arrayType, char * string)
6870 {
6871    char size[256];
6872    size[0] = '\0';
6873    strcat(size, "[");
6874    if(arrayType.enumClass)
6875       strcat(size, arrayType.enumClass.string);
6876    else if(arrayType.arraySizeExp)
6877       PrintExpression(arrayType.arraySizeExp, size);
6878    strcat(size, "]");
6879    strcat(string, size);
6880 }
6881
6882 // WARNING : This function expects a null terminated string since it recursively concatenate...
6883 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6884 {
6885    if(type)
6886    {
6887       if(printConst && type.constant)
6888          strcat(string, "const ");
6889       switch(type.kind)
6890       {
6891          case classType:
6892          {
6893             Symbol c = type._class;
6894             bool isObjectBaseClass = !c || !c.string || !strcmp(c.string, "class");
6895             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6896             //       look into merging with thisclass ?
6897             if(type.classObjectType == typedObject && isObjectBaseClass)
6898                strcat(string, "typed_object");
6899             else if(type.classObjectType == anyObject && isObjectBaseClass)
6900                strcat(string, "any_object");
6901             else
6902             {
6903                if(c && c.string)
6904                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6905             }
6906             if(type.byReference)
6907                strcat(string, " &");
6908             break;
6909          }
6910          case voidType: strcat(string, "void"); break;
6911          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6912          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6913          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6914          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6915          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6916          case _BoolType: strcat(string, "_Bool"); break;
6917          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6918          case floatType: strcat(string, "float"); break;
6919          case doubleType: strcat(string, "double"); break;
6920          case structType:
6921             if(type.enumName)
6922             {
6923                strcat(string, "struct ");
6924                strcat(string, type.enumName);
6925             }
6926             else if(type.typeName)
6927                strcat(string, type.typeName);
6928             else
6929             {
6930                Type member;
6931                strcat(string, "struct { ");
6932                for(member = type.members.first; member; member = member.next)
6933                {
6934                   PrintType(member, string, true, fullName);
6935                   strcat(string,"; ");
6936                }
6937                strcat(string,"}");
6938             }
6939             break;
6940          case unionType:
6941             if(type.enumName)
6942             {
6943                strcat(string, "union ");
6944                strcat(string, type.enumName);
6945             }
6946             else if(type.typeName)
6947                strcat(string, type.typeName);
6948             else
6949             {
6950                strcat(string, "union ");
6951                strcat(string,"(unnamed)");
6952             }
6953             break;
6954          case enumType:
6955             if(type.enumName)
6956             {
6957                strcat(string, "enum ");
6958                strcat(string, type.enumName);
6959             }
6960             else if(type.typeName)
6961                strcat(string, type.typeName);
6962             else
6963                strcat(string, "int"); // "enum");
6964             break;
6965          case ellipsisType:
6966             strcat(string, "...");
6967             break;
6968          case subClassType:
6969             strcat(string, "subclass(");
6970             strcat(string, type._class ? type._class.string : "int");
6971             strcat(string, ")");
6972             break;
6973          case templateType:
6974             strcat(string, type.templateParameter.identifier.string);
6975             break;
6976          case thisClassType:
6977             strcat(string, "thisclass");
6978             break;
6979          case vaListType:
6980             strcat(string, "__builtin_va_list");
6981             break;
6982       }
6983    }
6984 }
6985
6986 static void PrintName(Type type, char * string, bool fullName)
6987 {
6988    if(type.name && type.name[0])
6989    {
6990       if(fullName)
6991          strcat(string, type.name);
6992       else
6993       {
6994          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
6995          if(name) name += 2; else name = type.name;
6996          strcat(string, name);
6997       }
6998    }
6999 }
7000
7001 static void PrintAttribs(Type type, char * string)
7002 {
7003    if(type)
7004    {
7005       if(type.dllExport)   strcat(string, "dllexport ");
7006       if(type.attrStdcall) strcat(string, "stdcall ");
7007    }
7008 }
7009
7010 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
7011 {
7012    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7013    {
7014       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
7015          PrintAttribs(type, string);
7016       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
7017          strcat(string, " const");
7018       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
7019       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7020          strcat(string, " (");
7021       if(type.kind == pointerType)
7022       {
7023          if(type.type.kind == functionType || type.type.kind == methodType)
7024             PrintAttribs(type.type, string);
7025       }
7026       if(type.kind == pointerType)
7027       {
7028          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7029             strcat(string, "*");
7030          else
7031             strcat(string, " *");
7032       }
7033       if(printConst && type.constant && type.kind == pointerType)
7034          strcat(string, " const");
7035    }
7036    else
7037       PrintTypeSpecs(type, string, fullName, printConst);
7038 }
7039
7040 static void PostPrintType(Type type, char * string, bool fullName)
7041 {
7042    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7043       strcat(string, ")");
7044    if(type.kind == arrayType)
7045       PrintArraySize(type, string);
7046    else if(type.kind == functionType)
7047    {
7048       Type param;
7049       strcat(string, "(");
7050       for(param = type.params.first; param; param = param.next)
7051       {
7052          PrintType(param, string, true, fullName);
7053          if(param.next) strcat(string, ", ");
7054       }
7055       strcat(string, ")");
7056    }
7057    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7058       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7059 }
7060
7061 // *****
7062 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7063 // *****
7064 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7065 {
7066    PrePrintType(type, string, fullName, null, printConst);
7067
7068    if(type.thisClass || (printName && type.name && type.name[0]))
7069       strcat(string, " ");
7070    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7071    {
7072       Symbol _class = type.thisClass;
7073       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7074       {
7075          if(type.classObjectType == classPointer)
7076             strcat(string, "class");
7077          else
7078             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7079       }
7080       else if(_class && _class.string)
7081       {
7082          String s = _class.string;
7083          if(fullName)
7084             strcat(string, s);
7085          else
7086          {
7087             char * name = RSearchString(s, "::", strlen(s), true, false);
7088             if(name) name += 2; else name = s;
7089             strcat(string, name);
7090          }
7091       }
7092       strcat(string, "::");
7093    }
7094
7095    if(printName && type.name)
7096       PrintName(type, string, fullName);
7097    PostPrintType(type, string, fullName);
7098    if(type.bitFieldCount)
7099    {
7100       char count[100];
7101       sprintf(count, ":%d", type.bitFieldCount);
7102       strcat(string, count);
7103    }
7104 }
7105
7106 void PrintType(Type type, char * string, bool printName, bool fullName)
7107 {
7108    _PrintType(type, string, printName, fullName, true);
7109 }
7110
7111 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7112 {
7113    _PrintType(type, string, printName, fullName, false);
7114 }
7115
7116 static Type FindMember(Type type, char * string)
7117 {
7118    Type memberType;
7119    for(memberType = type.members.first; memberType; memberType = memberType.next)
7120    {
7121       if(!memberType.name)
7122       {
7123          Type subType = FindMember(memberType, string);
7124          if(subType)
7125             return subType;
7126       }
7127       else if(!strcmp(memberType.name, string))
7128          return memberType;
7129    }
7130    return null;
7131 }
7132
7133 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7134 {
7135    Type memberType;
7136    for(memberType = type.members.first; memberType; memberType = memberType.next)
7137    {
7138       if(!memberType.name)
7139       {
7140          Type subType = FindMember(memberType, string);
7141          if(subType)
7142          {
7143             *offset += memberType.offset;
7144             return subType;
7145          }
7146       }
7147       else if(!strcmp(memberType.name, string))
7148       {
7149          *offset += memberType.offset;
7150          return memberType;
7151       }
7152    }
7153    return null;
7154 }
7155
7156 public bool GetParseError() { return parseError; }
7157
7158 Expression ParseExpressionString(char * expression)
7159 {
7160    parseError = false;
7161
7162    fileInput = TempFile { };
7163    fileInput.Write(expression, 1, strlen(expression));
7164    fileInput.Seek(0, start);
7165
7166    echoOn = false;
7167    parsedExpression = null;
7168    resetScanner();
7169    expression_yyparse();
7170    delete fileInput;
7171
7172    return parsedExpression;
7173 }
7174
7175 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7176 {
7177    Identifier id = exp.identifier;
7178    Method method = null;
7179    Property prop = null;
7180    DataMember member = null;
7181    ClassProperty classProp = null;
7182
7183    if(_class && _class.type == enumClass)
7184    {
7185       NamedLink64 value = null;
7186       Class enumClass = eSystem_FindClass(privateModule, "enum");
7187       if(enumClass)
7188       {
7189          Class baseClass;
7190          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7191          {
7192             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7193             for(value = e.values.first; value; value = value.next)
7194             {
7195                if(!strcmp(value.name, id.string))
7196                   break;
7197             }
7198             if(value)
7199             {
7200                exp.isConstant = true;
7201                if(inCompiler || inPreCompiler || inDebugger)
7202                {
7203                   char constant[256];
7204                   FreeExpContents(exp);
7205
7206                   exp.type = constantExp;
7207                   if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7208                      sprintf(constant, FORMAT64D, value.data);
7209                   else
7210                      sprintf(constant, FORMAT64HEX, value.data);
7211                   exp.constant = CopyString(constant);
7212                }
7213                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7214                exp.expType = MkClassType(baseClass.fullName);
7215                break;
7216             }
7217          }
7218       }
7219       if(value)
7220          return true;
7221    }
7222    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7223    {
7224       ProcessMethodType(method);
7225       exp.expType = Type
7226       {
7227          refCount = 1;
7228          kind = methodType;
7229          method = method;
7230          // Crash here?
7231          // TOCHECK: Put it back to what it was...
7232          // methodClass = _class;
7233          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7234       };
7235       //id._class = null;
7236       return true;
7237    }
7238    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7239    {
7240       if(!prop.dataType)
7241          ProcessPropertyType(prop);
7242       exp.expType = prop.dataType;
7243       if(prop.dataType) prop.dataType.refCount++;
7244       return true;
7245    }
7246    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7247    {
7248       if(!member.dataType)
7249          member.dataType = ProcessTypeString(member.dataTypeString, false);
7250       exp.expType = member.dataType;
7251       if(member.dataType) member.dataType.refCount++;
7252       return true;
7253    }
7254    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7255    {
7256       if(!classProp.dataType)
7257          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7258
7259       if(classProp.constant)
7260       {
7261          FreeExpContents(exp);
7262
7263          exp.isConstant = true;
7264          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7265          {
7266             //char constant[256];
7267             exp.type = stringExp;
7268             exp.constant = QMkString((char *)(uintptr)classProp.Get(_class));
7269          }
7270          else
7271          {
7272             char constant[256];
7273             exp.type = constantExp;
7274             sprintf(constant, "%d", (int)classProp.Get(_class));
7275             exp.constant = CopyString(constant);
7276          }
7277       }
7278       else
7279       {
7280          // TO IMPLEMENT...
7281       }
7282
7283       exp.expType = classProp.dataType;
7284       if(classProp.dataType) classProp.dataType.refCount++;
7285       return true;
7286    }
7287    return false;
7288 }
7289
7290 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7291 {
7292    BinaryTree * tree = &nameSpace.functions;
7293    GlobalData data = (GlobalData)tree->FindString(name);
7294    NameSpace * child;
7295    if(!data)
7296    {
7297       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7298       {
7299          data = ScanGlobalData(child, name);
7300          if(data)
7301             break;
7302       }
7303    }
7304    return data;
7305 }
7306
7307 static GlobalData FindGlobalData(char * name)
7308 {
7309    int start = 0, c;
7310    NameSpace * nameSpace;
7311    nameSpace = globalData;
7312    for(c = 0; name[c]; c++)
7313    {
7314       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7315       {
7316          NameSpace * newSpace;
7317          char * spaceName = new char[c - start + 1];
7318          strncpy(spaceName, name + start, c - start);
7319          spaceName[c-start] = '\0';
7320          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7321          delete spaceName;
7322          if(!newSpace)
7323             return null;
7324          nameSpace = newSpace;
7325          if(name[c] == ':') c++;
7326          start = c+1;
7327       }
7328    }
7329    if(c - start)
7330    {
7331       return ScanGlobalData(nameSpace, name + start);
7332    }
7333    return null;
7334 }
7335
7336 static int definedExpStackPos;
7337 static void * definedExpStack[512];
7338
7339 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7340 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7341 {
7342    Expression prev = checkedExp.prev, next = checkedExp.next;
7343
7344    FreeExpContents(checkedExp);
7345    FreeType(checkedExp.expType);
7346    FreeType(checkedExp.destType);
7347
7348    *checkedExp = *newExp;
7349
7350    delete newExp;
7351
7352    checkedExp.prev = prev;
7353    checkedExp.next = next;
7354 }
7355
7356 void ApplyAnyObjectLogic(Expression e)
7357 {
7358    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7359 #ifdef _DEBUG
7360    char debugExpString[4096];
7361    debugExpString[0] = '\0';
7362    PrintExpression(e, debugExpString);
7363 #endif
7364
7365    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7366    {
7367       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7368       //ellipsisDestType = destType;
7369       if(e && e.expType)
7370       {
7371          Type type = e.expType;
7372          Class _class = null;
7373          //Type destType = e.destType;
7374
7375          if(type.kind == classType && type._class && type._class.registered)
7376          {
7377             _class = type._class.registered;
7378          }
7379          else if(type.kind == subClassType)
7380          {
7381             _class = FindClass("ecere::com::Class").registered;
7382          }
7383          else
7384          {
7385             char string[1024] = "";
7386             Symbol classSym;
7387
7388             PrintTypeNoConst(type, string, false, true);
7389             classSym = FindClass(string);
7390             if(classSym) _class = classSym.registered;
7391          }
7392
7393          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...
7394             (!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))) ||
7395             destType.byReference)))
7396          {
7397             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7398             {
7399                Expression checkedExp = e, newExp;
7400
7401                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7402                {
7403                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7404                   {
7405                      if(checkedExp.type == extensionCompoundExp)
7406                      {
7407                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7408                      }
7409                      else
7410                         checkedExp = checkedExp.list->last;
7411                   }
7412                   else if(checkedExp.type == castExp)
7413                      checkedExp = checkedExp.cast.exp;
7414                }
7415
7416                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7417                {
7418                   newExp = checkedExp.op.exp2;
7419                   checkedExp.op.exp2 = null;
7420                   FreeExpContents(checkedExp);
7421
7422                   if(e.expType && e.expType.passAsTemplate)
7423                   {
7424                      char size[100];
7425                      ComputeTypeSize(e.expType);
7426                      sprintf(size, "%d", e.expType.size);   // Potential 32/64 Bootstrap issue
7427                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7428                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7429                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7430                   }
7431
7432                   ReplaceExpContents(checkedExp, newExp);
7433                   e.byReference = true;
7434                }
7435                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7436                {
7437                   Expression checkedExp; //, newExp;
7438
7439                   {
7440                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7441                      bool hasAddress =
7442                         e.type == identifierExp ||
7443                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7444                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7445                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7446                         e.type == indexExp;
7447
7448                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7449                      {
7450                         Context context = PushContext();
7451                         Declarator decl;
7452                         OldList * specs = MkList();
7453                         char typeString[1024];
7454                         Expression newExp { };
7455
7456                         typeString[0] = '\0';
7457                         *newExp = *e;
7458
7459                         //if(e.destType) e.destType.refCount++;
7460                         // if(exp.expType) exp.expType.refCount++;
7461                         newExp.prev = null;
7462                         newExp.next = null;
7463                         newExp.expType = null;
7464
7465                         PrintTypeNoConst(e.expType, typeString, false, true);
7466                         decl = SpecDeclFromString(typeString, specs, null);
7467                         newExp.destType = ProcessType(specs, decl);
7468
7469                         curContext = context;
7470
7471                         // We need a current compound for this
7472                         if(curCompound)
7473                         {
7474                            char name[100];
7475                            OldList * stmts = MkList();
7476                            e.type = extensionCompoundExp;
7477                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7478                            if(!curCompound.compound.declarations)
7479                               curCompound.compound.declarations = MkList();
7480                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7481                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7482                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7483                            e.compound = MkCompoundStmt(null, stmts);
7484                         }
7485                         else
7486                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7487
7488                         /*
7489                         e.compound = MkCompoundStmt(
7490                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7491                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7492
7493                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7494                         */
7495
7496                         {
7497                            Type type = e.destType;
7498                            e.destType = { };
7499                            CopyTypeInto(e.destType, type);
7500                            e.destType.refCount = 1;
7501                            e.destType.classObjectType = none;
7502                            FreeType(type);
7503                         }
7504
7505                         e.compound.compound.context = context;
7506                         PopContext(context);
7507                         curContext = context.parent;
7508                      }
7509                   }
7510
7511                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7512                   checkedExp = e;
7513                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7514                   {
7515                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7516                      {
7517                         if(checkedExp.type == extensionCompoundExp)
7518                         {
7519                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7520                         }
7521                         else
7522                            checkedExp = checkedExp.list->last;
7523                      }
7524                      else if(checkedExp.type == castExp)
7525                         checkedExp = checkedExp.cast.exp;
7526                   }
7527                   {
7528                      Expression operand { };
7529                      operand = *checkedExp;
7530                      checkedExp.Clear();
7531                      checkedExp.destType = ProcessTypeString("void *", false);
7532                      checkedExp.expType = checkedExp.destType;
7533                      checkedExp.destType.refCount++;
7534
7535                      checkedExp.type = opExp;
7536                      checkedExp.op.op = '&';
7537                      checkedExp.op.exp1 = null;
7538                      checkedExp.op.exp2 = operand;
7539
7540                      //newExp = MkExpOp(null, '&', checkedExp);
7541                   }
7542                   //ReplaceExpContents(checkedExp, newExp);
7543                }
7544             }
7545          }
7546       }
7547    }
7548    {
7549       // If expression type is a simple class, make it an address
7550       // FixReference(e, true);
7551    }
7552 //#if 0
7553    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7554       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7555          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7556    {
7557       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"))
7558       {
7559          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7560       }
7561       else
7562       {
7563          Expression thisExp { };
7564
7565          *thisExp = *e;
7566          thisExp.prev = null;
7567          thisExp.next = null;
7568          e.Clear();
7569
7570          e.type = bracketsExp;
7571          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7572          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7573             ((Expression)e.list->first).byReference = true;
7574
7575          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7576          {
7577             e.expType = thisExp.expType;
7578             e.expType.refCount++;
7579          }
7580          else*/
7581          {
7582             e.expType = { };
7583             CopyTypeInto(e.expType, thisExp.expType);
7584             e.expType.byReference = false;
7585             e.expType.refCount = 1;
7586
7587             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7588                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7589             {
7590                e.expType.classObjectType = none;
7591             }
7592          }
7593       }
7594    }
7595 // TOFIX: Try this for a nice IDE crash!
7596 //#endif
7597    // The other way around
7598    else
7599 //#endif
7600    if(destType && e.expType &&
7601          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7602          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7603          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7604    {
7605       if(destType.kind == ellipsisType)
7606       {
7607          Compiler_Error($"Unspecified type\n");
7608       }
7609       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7610       {
7611          bool byReference = e.expType.byReference;
7612          Expression thisExp { };
7613          Declarator decl;
7614          OldList * specs = MkList();
7615          char typeString[1024]; // Watch buffer overruns
7616          Type type;
7617          ClassObjectType backupClassObjectType;
7618          bool backupByReference;
7619
7620          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7621             type = e.expType;
7622          else
7623             type = destType;
7624
7625          backupClassObjectType = type.classObjectType;
7626          backupByReference = type.byReference;
7627
7628          type.classObjectType = none;
7629          type.byReference = false;
7630
7631          typeString[0] = '\0';
7632          PrintType(type, typeString, false, true);
7633          decl = SpecDeclFromString(typeString, specs, null);
7634
7635          type.classObjectType = backupClassObjectType;
7636          type.byReference = backupByReference;
7637
7638          *thisExp = *e;
7639          thisExp.prev = null;
7640          thisExp.next = null;
7641          e.Clear();
7642
7643          if( ( type.kind == classType && type._class && type._class.registered &&
7644                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7645                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7646              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7647              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7648          {
7649             bool passAsTemplate = thisExp.destType.passAsTemplate;
7650             Type t;
7651
7652             destType.refCount++;
7653
7654             e.type = opExp;
7655             e.op.op = '*';
7656             e.op.exp1 = null;
7657             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7658
7659             t = { };
7660             CopyTypeInto(t, thisExp.destType);
7661             t.passAsTemplate = false;
7662             FreeType(thisExp.destType);
7663             thisExp.destType = t;
7664
7665             t = { };
7666             CopyTypeInto(t, destType);
7667             t.passAsTemplate = passAsTemplate;
7668             FreeType(destType);
7669             destType = t;
7670             destType.refCount = 0;
7671
7672             e.expType = { };
7673             CopyTypeInto(e.expType, type);
7674             if(type.passAsTemplate)
7675             {
7676                e.expType.classObjectType = none;
7677                e.expType.passAsTemplate = false;
7678             }
7679             e.expType.byReference = false;
7680             e.expType.refCount = 1;
7681          }
7682          else
7683          {
7684             e.type = castExp;
7685             e.cast.typeName = MkTypeName(specs, decl);
7686             e.cast.exp = thisExp;
7687             e.byReference = true;
7688             e.expType = type;
7689             type.refCount++;
7690          }
7691
7692          if(e.destType)
7693             FreeType(e.destType);
7694
7695          e.destType = destType;
7696          destType.refCount++;
7697       }
7698    }
7699 }
7700
7701 void ApplyLocation(Expression exp, Location loc)
7702 {
7703    exp.loc = loc;
7704    switch(exp.type)
7705    {
7706       case opExp:
7707          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7708          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7709          break;
7710       case bracketsExp:
7711          if(exp.list)
7712          {
7713             Expression e;
7714             for(e = exp.list->first; e; e = e.next)
7715                ApplyLocation(e, loc);
7716          }
7717          break;
7718       case indexExp:
7719          if(exp.index.index)
7720          {
7721             Expression e;
7722             for(e = exp.index.index->first; e; e = e.next)
7723                ApplyLocation(e, loc);
7724          }
7725          if(exp.index.exp)
7726             ApplyLocation(exp.index.exp, loc);
7727          break;
7728       case callExp:
7729          if(exp.call.arguments)
7730          {
7731             Expression arg;
7732             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7733                ApplyLocation(arg, loc);
7734          }
7735          if(exp.call.exp)
7736             ApplyLocation(exp.call.exp, loc);
7737          break;
7738       case memberExp:
7739       case pointerExp:
7740          if(exp.member.exp)
7741             ApplyLocation(exp.member.exp, loc);
7742          break;
7743       case castExp:
7744          if(exp.cast.exp)
7745             ApplyLocation(exp.cast.exp, loc);
7746          break;
7747       case conditionExp:
7748          if(exp.cond.exp)
7749          {
7750             Expression e;
7751             for(e = exp.cond.exp->first; e; e = e.next)
7752                ApplyLocation(e, loc);
7753          }
7754          if(exp.cond.cond)
7755             ApplyLocation(exp.cond.cond, loc);
7756          if(exp.cond.elseExp)
7757             ApplyLocation(exp.cond.elseExp, loc);
7758          break;
7759       case vaArgExp:
7760          if(exp.vaArg.exp)
7761             ApplyLocation(exp.vaArg.exp, loc);
7762          break;
7763       default:
7764          break;
7765    }
7766 }
7767
7768 void ProcessExpressionType(Expression exp)
7769 {
7770    bool unresolved = false;
7771    Location oldyylloc = yylloc;
7772    bool notByReference = false;
7773 #ifdef _DEBUG
7774    char debugExpString[4096];
7775    debugExpString[0] = '\0';
7776    PrintExpression(exp, debugExpString);
7777 #endif
7778    if(!exp || exp.expType)
7779       return;
7780
7781    //eSystem_Logf("%s\n", expString);
7782
7783    // Testing this here
7784    yylloc = exp.loc;
7785    switch(exp.type)
7786    {
7787       case identifierExp:
7788       {
7789          Identifier id = exp.identifier;
7790          if(!id || !topContext) return;
7791
7792          // DOING THIS LATER NOW...
7793          if(id._class && id._class.name)
7794          {
7795             id.classSym = id._class.symbol; // FindClass(id._class.name);
7796             /* TODO: Name Space Fix ups
7797             if(!id.classSym)
7798                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7799             */
7800          }
7801
7802          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7803          {
7804             exp.expType = ProcessTypeString("Module", true);
7805             break;
7806          }
7807          else */
7808          if(!strcmp(id.string, "__runtimePlatform"))
7809          {
7810             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7811             break;
7812          }
7813          else if(strstr(id.string, "__ecereClass") == id.string)
7814          {
7815             exp.expType = ProcessTypeString("ecere::com::Class", true);
7816             break;
7817          }
7818          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7819          {
7820             // Added this here as well
7821             ReplaceClassMembers(exp, thisClass);
7822             if(exp.type != identifierExp)
7823             {
7824                ProcessExpressionType(exp);
7825                break;
7826             }
7827
7828             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7829                break;
7830          }
7831          else
7832          {
7833             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7834             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7835             if(!symbol/* && exp.destType*/)
7836             {
7837                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7838                   break;
7839                else
7840                {
7841                   if(thisClass)
7842                   {
7843                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7844                      if(exp.type != identifierExp)
7845                      {
7846                         ProcessExpressionType(exp);
7847                         break;
7848                      }
7849                   }
7850                   // Static methods called from inside the _class
7851                   else if(currentClass && !id._class)
7852                   {
7853                      if(ResolveIdWithClass(exp, currentClass, true))
7854                         break;
7855                   }
7856                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7857                }
7858             }
7859
7860             // If we manage to resolve this symbol
7861             if(symbol)
7862             {
7863                Type type = symbol.type;
7864                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7865
7866                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7867                {
7868                   Context context = SetupTemplatesContext(_class);
7869                   type = ReplaceThisClassType(_class);
7870                   FinishTemplatesContext(context);
7871                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7872                }
7873
7874                FreeSpecifier(id._class);
7875                id._class = null;
7876                delete id.string;
7877                id.string = CopyString(symbol.string);
7878
7879                id.classSym = null;
7880                exp.expType = type;
7881                if(type)
7882                   type.refCount++;
7883
7884                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7885                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7886                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7887                   // Add missing cases here... enum Classes...
7888                   exp.isConstant = true;
7889
7890                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7891                if(symbol.isParam || !strcmp(id.string, "this"))
7892                {
7893                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7894                      exp.byReference = true;
7895
7896                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7897                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7898                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7899                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7900                   {
7901                      Identifier id = exp.identifier;
7902                      exp.type = bracketsExp;
7903                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7904                   }*/
7905                }
7906
7907                if(symbol.isIterator)
7908                {
7909                   if(symbol.isIterator == 3)
7910                   {
7911                      exp.type = bracketsExp;
7912                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7913                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7914                      exp.expType = null;
7915                      ProcessExpressionType(exp);
7916                   }
7917                   else if(symbol.isIterator != 4)
7918                   {
7919                      exp.type = memberExp;
7920                      exp.member.exp = MkExpIdentifier(exp.identifier);
7921                      exp.member.exp.expType = exp.expType;
7922                      /*if(symbol.isIterator == 6)
7923                         exp.member.member = MkIdentifier("key");
7924                      else*/
7925                         exp.member.member = MkIdentifier("data");
7926                      exp.expType = null;
7927                      ProcessExpressionType(exp);
7928                   }
7929                }
7930                break;
7931             }
7932             else
7933             {
7934                DefinedExpression definedExp = null;
7935                if(thisNameSpace && !(id._class && !id._class.name))
7936                {
7937                   char name[1024];
7938                   strcpy(name, thisNameSpace);
7939                   strcat(name, "::");
7940                   strcat(name, id.string);
7941                   definedExp = eSystem_FindDefine(privateModule, name);
7942                }
7943                if(!definedExp)
7944                   definedExp = eSystem_FindDefine(privateModule, id.string);
7945                if(definedExp)
7946                {
7947                   int c;
7948                   for(c = 0; c<definedExpStackPos; c++)
7949                      if(definedExpStack[c] == definedExp)
7950                         break;
7951                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7952                   {
7953                      Location backupYylloc = yylloc;
7954                      File backInput = fileInput;
7955                      definedExpStack[definedExpStackPos++] = definedExp;
7956
7957                      fileInput = TempFile { };
7958                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7959                      fileInput.Seek(0, start);
7960
7961                      echoOn = false;
7962                      parsedExpression = null;
7963                      resetScanner();
7964                      expression_yyparse();
7965                      delete fileInput;
7966                      if(backInput)
7967                         fileInput = backInput;
7968
7969                      yylloc = backupYylloc;
7970
7971                      if(parsedExpression)
7972                      {
7973                         FreeIdentifier(id);
7974                         exp.type = bracketsExp;
7975                         exp.list = MkListOne(parsedExpression);
7976                         ApplyLocation(parsedExpression, yylloc);
7977                         ProcessExpressionType(exp);
7978                         definedExpStackPos--;
7979                         return;
7980                      }
7981                      definedExpStackPos--;
7982                   }
7983                   else
7984                   {
7985                      if(inCompiler)
7986                      {
7987                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7988                      }
7989                   }
7990                }
7991                else
7992                {
7993                   GlobalData data = null;
7994                   if(thisNameSpace && !(id._class && !id._class.name))
7995                   {
7996                      char name[1024];
7997                      strcpy(name, thisNameSpace);
7998                      strcat(name, "::");
7999                      strcat(name, id.string);
8000                      data = FindGlobalData(name);
8001                   }
8002                   if(!data)
8003                      data = FindGlobalData(id.string);
8004                   if(data)
8005                   {
8006                      DeclareGlobalData(curExternal, data);
8007                      exp.expType = data.dataType;
8008                      if(data.dataType) data.dataType.refCount++;
8009
8010                      delete id.string;
8011                      id.string = CopyString(data.fullName);
8012                      FreeSpecifier(id._class);
8013                      id._class = null;
8014
8015                      break;
8016                   }
8017                   else
8018                   {
8019                      GlobalFunction function = null;
8020                      if(thisNameSpace && !(id._class && !id._class.name))
8021                      {
8022                         char name[1024];
8023                         strcpy(name, thisNameSpace);
8024                         strcat(name, "::");
8025                         strcat(name, id.string);
8026                         function = eSystem_FindFunction(privateModule, name);
8027                      }
8028                      if(!function)
8029                         function = eSystem_FindFunction(privateModule, id.string);
8030                      if(function)
8031                      {
8032                         char name[1024];
8033                         delete id.string;
8034                         id.string = CopyString(function.name);
8035                         name[0] = 0;
8036
8037                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8038                            strcpy(name, "__ecereFunction_");
8039                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8040                         if(DeclareFunction(curExternal, function, name))
8041                         {
8042                            delete id.string;
8043                            id.string = CopyString(name);
8044                         }
8045                         exp.expType = function.dataType;
8046                         if(function.dataType) function.dataType.refCount++;
8047
8048                         FreeSpecifier(id._class);
8049                         id._class = null;
8050
8051                         break;
8052                      }
8053                   }
8054                }
8055             }
8056          }
8057          unresolved = true;
8058          break;
8059       }
8060       case instanceExp:
8061       {
8062          // Class _class;
8063          // Symbol classSym;
8064
8065          if(!exp.instance._class)
8066          {
8067             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8068             {
8069                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8070             }
8071          }
8072
8073          //classSym = FindClass(exp.instance._class.fullName);
8074          //_class = classSym ? classSym.registered : null;
8075
8076          ProcessInstantiationType(exp.instance);
8077
8078          exp.isConstant = exp.instance.isConstant;
8079
8080          /*
8081          if(_class.type == unitClass && _class.base.type != systemClass)
8082          {
8083             {
8084                Type destType = exp.destType;
8085
8086                exp.destType = MkClassType(_class.base.fullName);
8087                exp.expType = MkClassType(_class.fullName);
8088                CheckExpressionType(exp, exp.destType, true);
8089
8090                exp.destType = destType;
8091             }
8092             exp.expType = MkClassType(_class.fullName);
8093          }
8094          else*/
8095          if(exp.instance._class)
8096          {
8097             exp.expType = MkClassType(exp.instance._class.name);
8098             /*if(exp.expType._class && exp.expType._class.registered &&
8099                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8100                exp.expType.byReference = true;*/
8101          }
8102          break;
8103       }
8104       case constantExp:
8105       {
8106          if(!exp.expType)
8107          {
8108             char * constant = exp.constant;
8109             Type type
8110             {
8111                refCount = 1;
8112                constant = true;
8113             };
8114             exp.expType = type;
8115
8116             if(constant[0] == '\'')
8117             {
8118                if((int)((byte *)constant)[1] > 127)
8119                {
8120                   int nb;
8121                   unichar ch = UTF8GetChar(constant + 1, &nb);
8122                   if(nb < 2) ch = constant[1];
8123                   delete constant;
8124                   exp.constant = PrintUInt(ch);
8125                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8126                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8127                   type._class = FindClass("unichar");
8128
8129                   type.isSigned = false;
8130                }
8131                else
8132                {
8133                   type.kind = charType;
8134                   type.isSigned = true;
8135                }
8136             }
8137             else
8138             {
8139                char * dot = strchr(constant, '.');
8140                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8141                char * exponent;
8142                if(isHex)
8143                {
8144                   exponent = strchr(constant, 'p');
8145                   if(!exponent) exponent = strchr(constant, 'P');
8146                }
8147                else
8148                {
8149                   exponent = strchr(constant, 'e');
8150                   if(!exponent) exponent = strchr(constant, 'E');
8151                }
8152
8153                if(dot || exponent)
8154                {
8155                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8156                      type.kind = floatType;
8157                   else
8158                      type.kind = doubleType;
8159                   type.isSigned = true;
8160                }
8161                else
8162                {
8163                   bool isSigned = constant[0] == '-';
8164                   char * endP = null;
8165                   int64 i64 = strtoll(constant, &endP, 0);
8166                   uint64 ui64 = strtoull(constant, &endP, 0);
8167                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8168                   bool forceUnsigned = endP && (!strcmp(endP, "U") || !strcmp(endP, "u") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8169                   if(isSigned)
8170                   {
8171                      if(i64 < MININT)
8172                         is64Bit = true;
8173                   }
8174                   else
8175                   {
8176                      if(ui64 > MAXINT)
8177                      {
8178                         if(ui64 > MAXDWORD)
8179                         {
8180                            is64Bit = true;
8181                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8182                               isSigned = true;
8183                         }
8184                      }
8185                      else if(constant[0] != '0' || !constant[1])
8186                         isSigned = true;
8187                   }
8188                   if(forceUnsigned)
8189                      isSigned = false;
8190                   type.kind = is64Bit ? int64Type : intType;
8191                   type.isSigned = isSigned;
8192                }
8193             }
8194             exp.isConstant = true;
8195             if(exp.destType && exp.destType.kind == doubleType)
8196                type.kind = doubleType;
8197             else if(exp.destType && exp.destType.kind == floatType)
8198                type.kind = floatType;
8199             else if(exp.destType && exp.destType.kind == int64Type)
8200                type.kind = int64Type;
8201          }
8202          break;
8203       }
8204       case stringExp:
8205       {
8206          exp.isConstant = true;      // Why wasn't this constant?
8207          exp.expType = Type
8208          {
8209             refCount = 1;
8210             kind = pointerType;
8211             type = Type
8212             {
8213                refCount = 1;
8214                kind = exp.wideString ? shortType : charType;
8215                constant = true;
8216                isSigned = exp.wideString ? false : true;
8217             }
8218          };
8219          break;
8220       }
8221       case newExp:
8222       case new0Exp:
8223          ProcessExpressionType(exp._new.size);
8224          exp.expType = Type
8225          {
8226             refCount = 1;
8227             kind = pointerType;
8228             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8229          };
8230          DeclareType(curExternal, exp.expType.type, true, false);
8231          break;
8232       case renewExp:
8233       case renew0Exp:
8234          ProcessExpressionType(exp._renew.size);
8235          ProcessExpressionType(exp._renew.exp);
8236          exp.expType = Type
8237          {
8238             refCount = 1;
8239             kind = pointerType;
8240             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8241          };
8242          DeclareType(curExternal, exp.expType.type, true, false);
8243          break;
8244       case opExp:
8245       {
8246          bool assign = false, boolResult = false, boolOps = false;
8247          Type type1 = null, type2 = null;
8248          bool useDestType = false, useSideType = false;
8249          Location oldyylloc = yylloc;
8250          bool useSideUnit = false;
8251          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8252
8253          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8254          Type dummy
8255          {
8256             count = 1;
8257             refCount = 1;
8258          };
8259
8260          switch(exp.op.op)
8261          {
8262             // Assignment Operators
8263             case '=':
8264             case MUL_ASSIGN:
8265             case DIV_ASSIGN:
8266             case MOD_ASSIGN:
8267             case ADD_ASSIGN:
8268             case SUB_ASSIGN:
8269             case LEFT_ASSIGN:
8270             case RIGHT_ASSIGN:
8271             case AND_ASSIGN:
8272             case XOR_ASSIGN:
8273             case OR_ASSIGN:
8274                assign = true;
8275                break;
8276             // boolean Operators
8277             case '!':
8278                // Expect boolean operators
8279                //boolOps = true;
8280                //boolResult = true;
8281                break;
8282             case AND_OP:
8283             case OR_OP:
8284                // Expect boolean operands
8285                boolOps = true;
8286                boolResult = true;
8287                break;
8288             // Comparisons
8289             case EQ_OP:
8290             case '<':
8291             case '>':
8292             case LE_OP:
8293             case GE_OP:
8294             case NE_OP:
8295                // Gives boolean result
8296                boolResult = true;
8297                useSideType = true;
8298                break;
8299             case '+':
8300             case '-':
8301                useSideUnit = true;
8302                useSideType = true;
8303                useDestType = true;
8304                break;
8305
8306             case LEFT_OP:
8307             case RIGHT_OP:
8308                // useSideType = true;
8309                // useDestType = true;
8310                break;
8311
8312             case '|':
8313             case '^':
8314                useSideType = true;
8315                useDestType = true;
8316                break;
8317
8318             case '/':
8319             case '%':
8320                useSideType = true;
8321                useDestType = true;
8322                break;
8323             case '&':
8324             case '*':
8325                if(exp.op.exp1)
8326                {
8327                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8328                   useSideType = true;
8329                   useDestType = true;
8330                }
8331                break;
8332
8333             /*// Implement speed etc.
8334             case '*':
8335             case '/':
8336                break;
8337             */
8338          }
8339          if(exp.op.op == '&')
8340          {
8341             // Added this here earlier for Iterator address as key
8342             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8343             {
8344                Identifier id = exp.op.exp2.identifier;
8345                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8346                if(symbol && symbol.isIterator == 2)
8347                {
8348                   exp.type = memberExp;
8349                   exp.member.exp = exp.op.exp2;
8350                   exp.member.member = MkIdentifier("key");
8351                   exp.expType = null;
8352                   exp.op.exp2.expType = symbol.type;
8353                   symbol.type.refCount++;
8354                   ProcessExpressionType(exp);
8355                   FreeType(dummy);
8356                   break;
8357                }
8358                // exp.op.exp2.usage.usageRef = true;
8359             }
8360          }
8361
8362          //dummy.kind = TypeDummy;
8363          if(exp.op.exp1)
8364          {
8365             // Added this check here to use the dest type only for units derived from the base unit
8366             // So that untyped units will use the side unit as opposed to the untyped destination unit
8367             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8368             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8369                useDestType = false;
8370
8371             if(destClass && useDestType &&
8372               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8373
8374               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8375             {
8376                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8377                exp.op.exp1.destType = exp.destType;
8378                exp.op.exp1.opDestType = true;
8379                if(exp.destType)
8380                   exp.destType.refCount++;
8381             }
8382             else if(!assign)
8383             {
8384                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8385                exp.op.exp1.destType = dummy;
8386                dummy.refCount++;
8387             }
8388
8389             // TESTING THIS HERE...
8390             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8391                ProcessExpressionType(exp.op.exp1);
8392             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8393
8394             exp.op.exp1.opDestType = false;
8395
8396             // Fix for unit and ++ / --
8397             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8398                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8399             {
8400                exp.op.exp2 = MkExpConstant("1");
8401                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8402                assign = true;
8403             }
8404
8405             if(exp.op.exp1.destType == dummy)
8406             {
8407                FreeType(dummy);
8408                exp.op.exp1.destType = null;
8409             }
8410
8411             if(exp.op.exp2)
8412             {
8413                if(!assign && exp.op.exp1.expType && (exp.op.exp1.expType.kind == charType || exp.op.exp1.expType.kind == shortType))
8414                {
8415                   Type type { kind = intType, isSigned = true, refCount = 1, signedBeforePromotion = exp.op.exp1.expType.isSigned, bitMemberSize = exp.op.exp1.expType.bitMemberSize, promotedFrom = exp.op.exp1.expType.kind };
8416                   FreeType(exp.op.exp1.expType);
8417                   exp.op.exp1.expType = type;
8418                }
8419             }
8420
8421             type1 = exp.op.exp1.expType;
8422          }
8423
8424          if(exp.op.exp2)
8425          {
8426             char expString[10240];
8427             expString[0] = '\0';
8428             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8429             {
8430                if(exp.op.exp1)
8431                {
8432                   exp.op.exp2.destType = exp.op.exp1.expType;
8433                   if(exp.op.exp1.expType)
8434                      exp.op.exp1.expType.refCount++;
8435                }
8436                else
8437                {
8438                   exp.op.exp2.destType = exp.destType;
8439                   if(!exp.op.exp1 || (exp.op.op != '&' && exp.op.op != '^'))
8440                      exp.op.exp2.opDestType = true;
8441                   if(exp.destType)
8442                      exp.destType.refCount++;
8443                }
8444
8445                if(type1) type1.refCount++;
8446                exp.expType = type1;
8447             }
8448             else if(assign)
8449             {
8450                if(inCompiler)
8451                   PrintExpression(exp.op.exp2, expString);
8452
8453                if(type1 && type1.kind == pointerType)
8454                {
8455                   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 ||
8456                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8457                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8458                   else if(exp.op.op == '=')
8459                   {
8460                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8461                      exp.op.exp2.destType = type1;
8462                      if(type1)
8463                         type1.refCount++;
8464                   }
8465                }
8466                else
8467                {
8468                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8469                   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/* ||
8470                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8471                   else
8472                   {
8473                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8474                      exp.op.exp2.destType = type1;
8475                      if(type1)
8476                         type1.refCount++;
8477                   }
8478                }
8479                if(type1) type1.refCount++;
8480                exp.expType = type1;
8481             }
8482             else if(destClass &&
8483                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8484                   (destClass.type == enumClass && useDestType)))
8485             {
8486                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8487                exp.op.exp2.destType = exp.destType;
8488                if(exp.op.op != '&' && exp.op.op != '^')
8489                   exp.op.exp2.opDestType = true;
8490                if(exp.destType)
8491                   exp.destType.refCount++;
8492             }
8493             else
8494             {
8495                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8496                exp.op.exp2.destType = dummy;
8497                dummy.refCount++;
8498             }
8499
8500             // TESTING THIS HERE... (DANGEROUS)
8501             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8502                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8503             {
8504                FreeType(exp.op.exp2.destType);
8505                exp.op.exp2.destType = type1;
8506                type1.refCount++;
8507             }
8508             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8509             // Cannot lose the cast on a sizeof
8510             if(exp.op.op == SIZEOF)
8511             {
8512                Expression e = exp.op.exp2;
8513                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8514                {
8515                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8516                   {
8517                      if(e.type == extensionCompoundExp)
8518                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8519                      else
8520                         e = e.list->last;
8521                   }
8522                }
8523                if(e.type == castExp && e.cast.exp)
8524                   e.cast.exp.needCast = true;
8525             }
8526             ProcessExpressionType(exp.op.exp2);
8527             exp.op.exp2.opDestType = false;
8528             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8529
8530             if(!assign && (exp.op.exp1 || exp.op.op == '~'))
8531             {
8532                if(exp.op.exp2.expType && (exp.op.exp2.expType.kind == charType || exp.op.exp2.expType.kind == shortType))
8533                {
8534                   Type type { kind = intType, isSigned = true, refCount = 1, signedBeforePromotion = exp.op.exp2.expType.isSigned, bitMemberSize = exp.op.exp2.expType.bitMemberSize, promotedFrom = exp.op.exp2.expType.kind };
8535                   FreeType(exp.op.exp2.expType);
8536                   exp.op.exp2.expType = type;
8537                }
8538             }
8539
8540             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8541             {
8542                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)
8543                {
8544                   if(exp.op.op != '=' && type1.type.kind == voidType)
8545                      Compiler_Error($"void *: unknown size\n");
8546                }
8547                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||
8548                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8549                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8550                               exp.op.exp2.expType._class.registered.type == structClass ||
8551                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8552                {
8553                   if(exp.op.op == ADD_ASSIGN)
8554                      Compiler_Error($"cannot add two pointers\n");
8555                }
8556                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8557                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8558                {
8559                   if(exp.op.op == ADD_ASSIGN)
8560                      Compiler_Error($"cannot add two pointers\n");
8561                }
8562                else if(inCompiler)
8563                {
8564                   char type1String[1024];
8565                   char type2String[1024];
8566                   type1String[0] = '\0';
8567                   type2String[0] = '\0';
8568
8569                   PrintType(exp.op.exp2.expType, type1String, false, true);
8570                   PrintType(type1, type2String, false, true);
8571                   ChangeCh(expString, '\n', ' ');
8572                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8573                }
8574             }
8575
8576             if(exp.op.exp2.destType == dummy)
8577             {
8578                FreeType(dummy);
8579                exp.op.exp2.destType = null;
8580             }
8581
8582             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8583             {
8584                type2 = { };
8585                type2.refCount = 1;
8586                CopyTypeInto(type2, exp.op.exp2.expType);
8587                type2.isSigned = true;
8588             }
8589             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8590             {
8591                type2 = { kind = intType };
8592                type2.refCount = 1;
8593                type2.isSigned = true;
8594             }
8595             else
8596             {
8597                type2 = exp.op.exp2.expType;
8598                if(type2) type2.refCount++;
8599             }
8600          }
8601
8602          dummy.kind = voidType;
8603
8604          if(exp.op.op == SIZEOF)
8605          {
8606             exp.expType = Type
8607             {
8608                refCount = 1;
8609                kind = intSizeType;
8610             };
8611             exp.isConstant = true;
8612          }
8613          // Get type of dereferenced pointer
8614          else if(exp.op.op == '*' && !exp.op.exp1)
8615          {
8616             exp.expType = Dereference(type2);
8617             if(type2 && type2.kind == classType)
8618                notByReference = true;
8619          }
8620          else if(exp.op.op == '&' && !exp.op.exp1)
8621             exp.expType = Reference(type2);
8622          else if(exp.op.op == LEFT_OP || exp.op.op == RIGHT_OP)
8623          {
8624             if(exp.op.exp1.expType)
8625             {
8626                exp.expType = exp.op.exp1.expType;
8627                exp.expType.refCount++;
8628             }
8629          }
8630          else if(!assign)
8631          {
8632             if(boolOps)
8633             {
8634                if(exp.op.exp1)
8635                {
8636                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8637                   exp.op.exp1.destType = MkClassType("bool");
8638                   exp.op.exp1.destType.truth = true;
8639                   if(!exp.op.exp1.expType)
8640                      ProcessExpressionType(exp.op.exp1);
8641                   else
8642                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8643                   FreeType(exp.op.exp1.expType);
8644                   exp.op.exp1.expType = MkClassType("bool");
8645                   exp.op.exp1.expType.truth = true;
8646                }
8647                if(exp.op.exp2)
8648                {
8649                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8650                   exp.op.exp2.destType = MkClassType("bool");
8651                   exp.op.exp2.destType.truth = true;
8652                   if(!exp.op.exp2.expType)
8653                      ProcessExpressionType(exp.op.exp2);
8654                   else
8655                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8656                   FreeType(exp.op.exp2.expType);
8657                   exp.op.exp2.expType = MkClassType("bool");
8658                   exp.op.exp2.expType.truth = true;
8659                }
8660             }
8661             else if(exp.op.exp1 && exp.op.exp2 &&
8662                ((useSideType /*&&
8663                      (useSideUnit ||
8664                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8665                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8666                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8667                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8668             {
8669                if(type1 && type2 &&
8670                   // If either both are class or both are not class
8671                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8672                {
8673                   // Added this check for enum subtraction to result in an int type:
8674                   if(exp.op.op == '-' &&
8675                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8676                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8677                   {
8678                      Type intType;
8679                      if(!type1._class.registered.dataType)
8680                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8681                      if(!type2._class.registered.dataType)
8682                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8683
8684                      intType = ProcessTypeString(
8685                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8686
8687                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8688                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8689                      exp.op.exp1.destType = intType;
8690                      exp.op.exp2.destType = intType;
8691                      intType.refCount++;
8692                   }
8693                   else
8694                   {
8695                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8696                      exp.op.exp2.destType = type1;
8697                      type1.refCount++;
8698                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8699                      exp.op.exp1.destType = type2;
8700                      type2.refCount++;
8701                   }
8702
8703                   // Warning here for adding Radians + Degrees with no destination type
8704                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8705                      type1._class.registered && type1._class.registered.type == unitClass &&
8706                      type2._class.registered && type2._class.registered.type == unitClass &&
8707                      type1._class.registered != type2._class.registered)
8708                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8709                         type1._class.string, type2._class.string, type1._class.string);
8710
8711                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8712                   {
8713                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8714                      if(argExp)
8715                      {
8716                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8717
8718                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8719                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8720                            exp.op.exp1)));
8721
8722                         ProcessExpressionType(exp.op.exp1);
8723
8724                         if(type2.kind != pointerType)
8725                         {
8726                            ProcessExpressionType(classExp);
8727
8728                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8729
8730                            if(!exp.op.exp2.expType)
8731                            {
8732                               if(type2)
8733                                  FreeType(type2);
8734                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8735                               type2.refCount++;
8736                            }
8737
8738                            ProcessExpressionType(exp.op.exp2);
8739                         }
8740                      }
8741                   }
8742
8743                   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)))
8744                   {
8745                      if(type1.kind != classType && type1.type.kind == voidType)
8746                         Compiler_Error($"void *: unknown size\n");
8747                      exp.expType = type1;
8748                      if(type1) type1.refCount++;
8749                   }
8750                   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)))
8751                   {
8752                      if(type2.kind != classType && type2.type.kind == voidType)
8753                         Compiler_Error($"void *: unknown size\n");
8754                      exp.expType = type2;
8755                      if(type2) type2.refCount++;
8756                   }
8757                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8758                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8759                   {
8760                      Compiler_Warning($"different levels of indirection\n");
8761                   }
8762                   else
8763                   {
8764                      bool success = false;
8765                      if(type1.kind == pointerType && type2.kind == pointerType)
8766                      {
8767                         if(exp.op.op == '+')
8768                            Compiler_Error($"cannot add two pointers\n");
8769                         else if(exp.op.op == '-')
8770                         {
8771                            // Pointer Subtraction gives integer
8772                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8773                            {
8774                               exp.expType = Type
8775                               {
8776                                  kind = intType;
8777                                  refCount = 1;
8778                               };
8779                               success = true;
8780
8781                               if(type1.type.kind == templateType)
8782                               {
8783                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8784                                  if(argExp)
8785                                  {
8786                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8787
8788                                     ProcessExpressionType(classExp);
8789
8790                                     exp.type = bracketsExp;
8791                                     exp.list = MkListOne(MkExpOp(
8792                                        MkExpBrackets(MkListOne(MkExpOp(
8793                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8794                                              , exp.op.op,
8795                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8796                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8797
8798                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8799                                     FreeType(dummy);
8800                                     return;
8801                                  }
8802                               }
8803                            }
8804                         }
8805                      }
8806
8807                      if(!success && exp.op.exp1.type == constantExp)
8808                      {
8809                         // If first expression is constant, try to match that first
8810                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8811                         {
8812                            if(exp.expType) FreeType(exp.expType);
8813                            exp.expType = exp.op.exp1.destType;
8814                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8815                            success = true;
8816                         }
8817                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8818                         {
8819                            if(exp.expType) FreeType(exp.expType);
8820                            exp.expType = exp.op.exp2.destType;
8821                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8822                            success = true;
8823                         }
8824                      }
8825                      else if(!success)
8826                      {
8827                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8828                         {
8829                            if(exp.expType) FreeType(exp.expType);
8830                            exp.expType = exp.op.exp2.destType;
8831                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8832                            success = true;
8833                         }
8834                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8835                         {
8836                            if(exp.expType) FreeType(exp.expType);
8837                            exp.expType = exp.op.exp1.destType;
8838                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8839                            success = true;
8840                         }
8841                      }
8842                      if(!success)
8843                      {
8844                         char expString1[10240];
8845                         char expString2[10240];
8846                         char type1[1024];
8847                         char type2[1024];
8848                         expString1[0] = '\0';
8849                         expString2[0] = '\0';
8850                         type1[0] = '\0';
8851                         type2[0] = '\0';
8852                         if(inCompiler)
8853                         {
8854                            PrintExpression(exp.op.exp1, expString1);
8855                            ChangeCh(expString1, '\n', ' ');
8856                            PrintExpression(exp.op.exp2, expString2);
8857                            ChangeCh(expString2, '\n', ' ');
8858                            PrintType(exp.op.exp1.expType, type1, false, true);
8859                            PrintType(exp.op.exp2.expType, type2, false, true);
8860                         }
8861
8862                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8863                      }
8864                   }
8865                }
8866                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8867                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8868                {
8869                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8870                   // Convert e.g. / 4 into / 4.0
8871                   exp.op.exp1.destType = type2._class.registered.dataType;
8872                   if(type2._class.registered.dataType)
8873                      type2._class.registered.dataType.refCount++;
8874                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8875                   exp.expType = type2;
8876                   if(type2) type2.refCount++;
8877                }
8878                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8879                {
8880                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8881                   // Convert e.g. / 4 into / 4.0
8882                   exp.op.exp2.destType = type1._class.registered.dataType;
8883                   if(type1._class.registered.dataType)
8884                      type1._class.registered.dataType.refCount++;
8885                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8886                   exp.expType = type1;
8887                   if(type1) type1.refCount++;
8888                }
8889                else if(type1)
8890                {
8891                   bool valid = false;
8892
8893                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8894                   {
8895                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8896
8897                      if(!type1._class.registered.dataType)
8898                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8899                      exp.op.exp2.destType = type1._class.registered.dataType;
8900                      exp.op.exp2.destType.refCount++;
8901
8902                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8903                      if(type2)
8904                         FreeType(type2);
8905                      type2 = exp.op.exp2.destType;
8906                      if(type2) type2.refCount++;
8907
8908                      exp.expType = type2;
8909                      type2.refCount++;
8910                   }
8911
8912                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8913                   {
8914                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8915
8916                      if(!type2._class.registered.dataType)
8917                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8918                      exp.op.exp1.destType = type2._class.registered.dataType;
8919                      exp.op.exp1.destType.refCount++;
8920
8921                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8922                      type1 = exp.op.exp1.destType;
8923                      exp.expType = type1;
8924                      type1.refCount++;
8925                   }
8926
8927                   // TESTING THIS NEW CODE
8928                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8929                   {
8930                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8931                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8932                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8933                      {
8934                         // Convert the enum to an int instead for these operators
8935                         if(op1IsEnum && exp.op.exp2.expType)
8936                         {
8937                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8938                            {
8939                               if(exp.expType) FreeType(exp.expType);
8940                               exp.expType = exp.op.exp2.expType;
8941                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8942                               valid = true;
8943                            }
8944                         }
8945                         else if(op2IsEnum && exp.op.exp1.expType)
8946                         {
8947                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8948                            {
8949                               if(exp.expType) FreeType(exp.expType);
8950                               exp.expType = exp.op.exp1.expType;
8951                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8952                               valid = true;
8953                            }
8954                         }
8955                      }
8956                      else
8957                      {
8958                         if(op1IsEnum && exp.op.exp2.expType)
8959                         {
8960                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8961                            {
8962                               if(exp.expType) FreeType(exp.expType);
8963                               exp.expType = exp.op.exp1.expType;
8964                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8965                               valid = true;
8966                            }
8967                         }
8968                         else if(op2IsEnum && exp.op.exp1.expType)
8969                         {
8970                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8971                            {
8972                               if(exp.expType) FreeType(exp.expType);
8973                               exp.expType = exp.op.exp2.expType;
8974                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8975                               valid = true;
8976                            }
8977                         }
8978                      }
8979                   }
8980
8981                   if(!valid)
8982                   {
8983                      // Added this first part of the if here to handle  5 + Degrees { 5 } with either a base unit dest or not a unit dest type
8984                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8985                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8986                      {
8987                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8988                         exp.op.exp1.destType = type2;
8989                         type2.refCount++;
8990
8991                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8992                         {
8993                            if(exp.expType) FreeType(exp.expType);
8994                            exp.expType = exp.op.exp1.destType;
8995                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8996                         }
8997                      }
8998                      else
8999                      {
9000                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9001                         exp.op.exp2.destType = type1;
9002                         type1.refCount++;
9003
9004                      /*
9005                      // Maybe this was meant to be an enum...
9006                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9007                      {
9008                         Type oldType = exp.op.exp2.expType;
9009                         exp.op.exp2.expType = null;
9010                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
9011                            FreeType(oldType);
9012                         else
9013                            exp.op.exp2.expType = oldType;
9014                      }
9015                      */
9016
9017                      /*
9018                      // TESTING THIS HERE... LATEST ADDITION
9019                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9020                      {
9021                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9022                         exp.op.exp2.destType = type2._class.registered.dataType;
9023                         if(type2._class.registered.dataType)
9024                            type2._class.registered.dataType.refCount++;
9025                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9026
9027                         //exp.expType = type2._class.registered.dataType; //type2;
9028                         //if(type2) type2.refCount++;
9029                      }
9030
9031                      // TESTING THIS HERE... LATEST ADDITION
9032                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9033                      {
9034                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9035                         exp.op.exp1.destType = type1._class.registered.dataType;
9036                         if(type1._class.registered.dataType)
9037                            type1._class.registered.dataType.refCount++;
9038                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9039                         exp.expType = type1._class.registered.dataType; //type1;
9040                         if(type1) type1.refCount++;
9041                      }
9042                      */
9043
9044                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9045                         {
9046                            if(exp.expType) FreeType(exp.expType);
9047                            exp.expType = exp.op.exp2.destType;
9048                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9049                         }
9050                         else if(type1 && type2)
9051                         {
9052                            char expString1[10240];
9053                            char expString2[10240];
9054                            char type1String[1024];
9055                            char type2String[1024];
9056                            expString1[0] = '\0';
9057                            expString2[0] = '\0';
9058                            type1String[0] = '\0';
9059                            type2String[0] = '\0';
9060                            if(inCompiler)
9061                            {
9062                               PrintExpression(exp.op.exp1, expString1);
9063                               ChangeCh(expString1, '\n', ' ');
9064                               PrintExpression(exp.op.exp2, expString2);
9065                               ChangeCh(expString2, '\n', ' ');
9066                               PrintType(exp.op.exp1.expType, type1String, false, true);
9067                               PrintType(exp.op.exp2.expType, type2String, false, true);
9068                            }
9069
9070                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9071
9072                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9073                            {
9074                               exp.expType = exp.op.exp1.expType;
9075                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9076                            }
9077                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9078                            {
9079                               exp.expType = exp.op.exp2.expType;
9080                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9081                            }
9082                         }
9083                      }
9084                   }
9085                }
9086                else if(type2)
9087                {
9088                   // Maybe this was meant to be an enum...
9089                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9090                   {
9091                      Type oldType = exp.op.exp1.expType;
9092                      exp.op.exp1.expType = null;
9093                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9094                         FreeType(oldType);
9095                      else
9096                         exp.op.exp1.expType = oldType;
9097                   }
9098
9099                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9100                   exp.op.exp1.destType = type2;
9101                   type2.refCount++;
9102                   /*
9103                   // TESTING THIS HERE... LATEST ADDITION
9104                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9105                   {
9106                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9107                      exp.op.exp1.destType = type1._class.registered.dataType;
9108                      if(type1._class.registered.dataType)
9109                         type1._class.registered.dataType.refCount++;
9110                   }
9111
9112                   // TESTING THIS HERE... LATEST ADDITION
9113                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9114                   {
9115                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9116                      exp.op.exp2.destType = type2._class.registered.dataType;
9117                      if(type2._class.registered.dataType)
9118                         type2._class.registered.dataType.refCount++;
9119                   }
9120                   */
9121
9122                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9123                   {
9124                      if(exp.expType) FreeType(exp.expType);
9125                      exp.expType = exp.op.exp1.destType;
9126                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9127                   }
9128                }
9129             }
9130             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9131             {
9132                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9133                {
9134                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9135                   // Convert e.g. / 4 into / 4.0
9136                   exp.op.exp1.destType = type2._class.registered.dataType;
9137                   if(type2._class.registered.dataType)
9138                      type2._class.registered.dataType.refCount++;
9139                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9140                }
9141                if(exp.op.op == '!')
9142                {
9143                   exp.expType = MkClassType("bool");
9144                   exp.expType.truth = true;
9145                }
9146                else
9147                {
9148                   exp.expType = type2;
9149                   if(type2) type2.refCount++;
9150                }
9151             }
9152             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9153             {
9154                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9155                {
9156                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9157                   // Convert e.g. / 4 into / 4.0
9158                   exp.op.exp2.destType = type1._class.registered.dataType;
9159                   if(type1._class.registered.dataType)
9160                      type1._class.registered.dataType.refCount++;
9161                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9162                }
9163                exp.expType = type1;
9164                if(type1) type1.refCount++;
9165             }
9166          }
9167
9168          yylloc = exp.loc;
9169          if(exp.op.exp1 && !exp.op.exp1.expType)
9170          {
9171             char expString[10000];
9172             expString[0] = '\0';
9173             if(inCompiler)
9174             {
9175                PrintExpression(exp.op.exp1, expString);
9176                ChangeCh(expString, '\n', ' ');
9177             }
9178             if(expString[0])
9179                Compiler_Error($"couldn't determine type of %s\n", expString);
9180          }
9181          if(exp.op.exp2 && !exp.op.exp2.expType)
9182          {
9183             char expString[10240];
9184             expString[0] = '\0';
9185             if(inCompiler)
9186             {
9187                PrintExpression(exp.op.exp2, expString);
9188                ChangeCh(expString, '\n', ' ');
9189             }
9190             if(expString[0])
9191                Compiler_Error($"couldn't determine type of %s\n", expString);
9192          }
9193
9194          if(boolResult)
9195          {
9196             FreeType(exp.expType);
9197             exp.expType = MkClassType("bool");
9198             exp.expType.truth = true;
9199          }
9200
9201          if(exp.op.op != SIZEOF)
9202             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9203                (!exp.op.exp2 || exp.op.exp2.isConstant);
9204
9205          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9206          {
9207             DeclareType(curExternal, exp.op.exp2.expType, true, false);
9208          }
9209
9210          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9211             Compiler_Warning($"deleting const qualified object\n");
9212
9213          yylloc = oldyylloc;
9214
9215          FreeType(dummy);
9216          if(type2)
9217             FreeType(type2);
9218          break;
9219       }
9220       case bracketsExp:
9221       case extensionExpressionExp:
9222       {
9223          Expression e;
9224          exp.isConstant = true;
9225          for(e = exp.list->first; e; e = e.next)
9226          {
9227             //bool inced = false;
9228             if(!e.next)
9229             {
9230                FreeType(e.destType);
9231                e.opDestType = exp.opDestType;
9232                e.destType = exp.destType;
9233                if(e.destType) { exp.destType.refCount++; /*e.destType.count++; inced = true;*/ }
9234             }
9235             ProcessExpressionType(e);
9236             /*if(inced)
9237                exp.destType.count--;*/
9238             if(!exp.expType && !e.next)
9239             {
9240                exp.expType = e.expType;
9241                if(e.expType) e.expType.refCount++;
9242             }
9243             if(!e.isConstant)
9244                exp.isConstant = false;
9245          }
9246
9247          // In case a cast became a member...
9248          e = exp.list->first;
9249          if(!e.next && e.type == memberExp)
9250          {
9251             // Preserve prev, next
9252             Expression next = exp.next, prev = exp.prev;
9253
9254
9255             FreeType(exp.expType);
9256             FreeType(exp.destType);
9257             delete exp.list;
9258
9259             *exp = *e;
9260
9261             exp.prev = prev;
9262             exp.next = next;
9263
9264             delete e;
9265
9266             ProcessExpressionType(exp);
9267          }
9268          break;
9269       }
9270       case indexExp:
9271       {
9272          Expression e;
9273          exp.isConstant = true;
9274
9275          ProcessExpressionType(exp.index.exp);
9276          if(!exp.index.exp.isConstant)
9277             exp.isConstant = false;
9278
9279          if(exp.index.exp.expType)
9280          {
9281             Type source = exp.index.exp.expType;
9282             if(source.kind == classType && source._class && source._class.registered)
9283             {
9284                Class _class = source._class.registered;
9285                Class c = _class.templateClass ? _class.templateClass : _class;
9286                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9287                {
9288                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9289
9290                   if(exp.index.index && exp.index.index->last)
9291                   {
9292                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9293
9294                      if(type.kind == classType) type.constant = true;
9295                      else if(type.kind == pointerType)
9296                      {
9297                         Type t = type;
9298                         while(t.kind == pointerType) t = t.type;
9299                         t.constant = true;
9300                      }
9301
9302                      ((Expression)exp.index.index->last).destType = type;
9303                   }
9304                }
9305             }
9306          }
9307
9308          for(e = exp.index.index->first; e; e = e.next)
9309          {
9310             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9311             {
9312                if(e.destType) FreeType(e.destType);
9313                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9314             }
9315             ProcessExpressionType(e);
9316             if(!e.next)
9317             {
9318                // Check if this type is int
9319             }
9320             if(!e.isConstant)
9321                exp.isConstant = false;
9322          }
9323
9324          if(!exp.expType)
9325             exp.expType = Dereference(exp.index.exp.expType);
9326          if(exp.expType)
9327             DeclareType(curExternal, exp.expType, true, false);
9328          break;
9329       }
9330       case callExp:
9331       {
9332          Expression e;
9333          Type functionType;
9334          Type methodType = null;
9335          char name[1024];
9336          name[0] = '\0';
9337
9338          if(inCompiler)
9339          {
9340             PrintExpression(exp.call.exp,  name);
9341             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9342             {
9343                //exp.call.exp.expType = null;
9344                PrintExpression(exp.call.exp,  name);
9345             }
9346          }
9347          if(exp.call.exp.type == identifierExp)
9348          {
9349             Expression idExp = exp.call.exp;
9350             Identifier id = idExp.identifier;
9351             if(!strcmp(id.string, "__builtin_frame_address"))
9352             {
9353                exp.expType = ProcessTypeString("void *", true);
9354                if(exp.call.arguments && exp.call.arguments->first)
9355                   ProcessExpressionType(exp.call.arguments->first);
9356                break;
9357             }
9358             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9359             {
9360                exp.expType = ProcessTypeString("int", true);
9361                if(exp.call.arguments && exp.call.arguments->first)
9362                   ProcessExpressionType(exp.call.arguments->first);
9363                break;
9364             }
9365             else if(!strcmp(id.string, "Max") ||
9366                !strcmp(id.string, "Min") ||
9367                !strcmp(id.string, "Sgn") ||
9368                !strcmp(id.string, "Abs"))
9369             {
9370                Expression a = null;
9371                Expression b = null;
9372                Expression tempExp1 = null, tempExp2 = null;
9373                if((!strcmp(id.string, "Max") ||
9374                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9375                {
9376                   a = exp.call.arguments->first;
9377                   b = exp.call.arguments->last;
9378                   tempExp1 = a;
9379                   tempExp2 = b;
9380                }
9381                else if(exp.call.arguments->count == 1)
9382                {
9383                   a = exp.call.arguments->first;
9384                   tempExp1 = a;
9385                }
9386
9387                if(a)
9388                {
9389                   exp.call.arguments->Clear();
9390                   idExp.identifier = null;
9391
9392                   FreeExpContents(exp);
9393
9394                   ProcessExpressionType(a);
9395                   if(b)
9396                      ProcessExpressionType(b);
9397
9398                   exp.type = bracketsExp;
9399                   exp.list = MkList();
9400
9401                   if(a.expType && (!b || b.expType))
9402                   {
9403                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9404                      {
9405                         // Use the simpleStruct name/ids for now...
9406                         if(inCompiler)
9407                         {
9408                            OldList * specs = MkList();
9409                            OldList * decls = MkList();
9410                            Declaration decl;
9411                            char temp1[1024], temp2[1024];
9412
9413                            GetTypeSpecs(a.expType, specs);
9414
9415                            if(a && !a.isConstant && a.type != identifierExp)
9416                            {
9417                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9418                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9419                               tempExp1 = QMkExpId(temp1);
9420                               tempExp1.expType = a.expType;
9421                               if(a.expType)
9422                                  a.expType.refCount++;
9423                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9424                            }
9425                            if(b && !b.isConstant && b.type != identifierExp)
9426                            {
9427                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9428                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9429                               tempExp2 = QMkExpId(temp2);
9430                               tempExp2.expType = b.expType;
9431                               if(b.expType)
9432                                  b.expType.refCount++;
9433                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9434                            }
9435
9436                            decl = MkDeclaration(specs, decls);
9437                            if(!curCompound.compound.declarations)
9438                               curCompound.compound.declarations = MkList();
9439                            curCompound.compound.declarations->Insert(null, decl);
9440                         }
9441                      }
9442                   }
9443
9444                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9445                   {
9446                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9447                      ListAdd(exp.list,
9448                         MkExpCondition(MkExpBrackets(MkListOne(
9449                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9450                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9451                      exp.expType = a.expType;
9452                      if(a.expType)
9453                         a.expType.refCount++;
9454                   }
9455                   else if(!strcmp(id.string, "Abs"))
9456                   {
9457                      ListAdd(exp.list,
9458                         MkExpCondition(MkExpBrackets(MkListOne(
9459                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9460                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9461                      exp.expType = a.expType;
9462                      if(a.expType)
9463                         a.expType.refCount++;
9464                   }
9465                   else if(!strcmp(id.string, "Sgn"))
9466                   {
9467                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9468                      ListAdd(exp.list,
9469                         MkExpCondition(MkExpBrackets(MkListOne(
9470                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9471                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9472                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9473                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9474                      exp.expType = ProcessTypeString("int", false);
9475                   }
9476
9477                   FreeExpression(tempExp1);
9478                   if(tempExp2) FreeExpression(tempExp2);
9479
9480                   FreeIdentifier(id);
9481                   break;
9482                }
9483             }
9484          }
9485
9486          {
9487             Type dummy
9488             {
9489                count = 1;
9490                refCount = 1;
9491             };
9492             if(!exp.call.exp.destType)
9493             {
9494                exp.call.exp.destType = dummy;
9495                dummy.refCount++;
9496             }
9497             ProcessExpressionType(exp.call.exp);
9498             if(exp.call.exp.destType == dummy)
9499             {
9500                FreeType(dummy);
9501                exp.call.exp.destType = null;
9502             }
9503             FreeType(dummy);
9504          }
9505
9506          // Check argument types against parameter types
9507          functionType = exp.call.exp.expType;
9508
9509          if(functionType && functionType.kind == TypeKind::methodType)
9510          {
9511             methodType = functionType;
9512             functionType = methodType.method.dataType;
9513
9514             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9515             // TOCHECK: Instead of doing this here could this be done per param?
9516             if(exp.call.exp.expType.usedClass)
9517             {
9518                char typeString[1024];
9519                typeString[0] = '\0';
9520                {
9521                   Symbol back = functionType.thisClass;
9522                   // Do not output class specifier here (thisclass was added to this)
9523                   functionType.thisClass = null;
9524                   PrintType(functionType, typeString, true, true);
9525                   functionType.thisClass = back;
9526                }
9527                if(strstr(typeString, "thisclass"))
9528                {
9529                   OldList * specs = MkList();
9530                   Declarator decl;
9531                   {
9532                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9533
9534                      decl = SpecDeclFromString(typeString, specs, null);
9535
9536                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9537                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9538                         exp.call.exp.expType.usedClass))
9539                         thisClassParams = false;
9540
9541                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9542                      {
9543                         Class backupThisClass = thisClass;
9544                         thisClass = exp.call.exp.expType.usedClass;
9545                         ProcessDeclarator(decl, true);
9546                         thisClass = backupThisClass;
9547                      }
9548
9549                      thisClassParams = true;
9550
9551                      functionType = ProcessType(specs, decl);
9552                      functionType.refCount = 0;
9553                      FinishTemplatesContext(context);
9554
9555                      // Mark parameters that were 'thisclass'
9556                      {
9557                         Type p, op;
9558                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9559                         {
9560                            //p.wasThisClass = op.kind == thisClassType;
9561                            if(op.kind == thisClassType)
9562                               p.thisClassFrom = methodType.method._class;
9563                         }
9564                      }
9565                      if(methodType.method.dataType.returnType.kind == thisClassType)
9566                      {
9567                         // functionType.returnType.wasThisClass = true;
9568                         functionType.returnType.thisClassFrom = methodType.method._class;
9569                      }
9570                   }
9571
9572                   FreeList(specs, FreeSpecifier);
9573                   FreeDeclarator(decl);
9574                 }
9575             }
9576          }
9577          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9578          {
9579             Type type = functionType.type;
9580             if(!functionType.refCount)
9581             {
9582                functionType.type = null;
9583                FreeType(functionType);
9584             }
9585             //methodType = functionType;
9586             functionType = type;
9587          }
9588          if(functionType && functionType.kind != TypeKind::functionType)
9589          {
9590             Compiler_Error($"called object %s is not a function\n", name);
9591          }
9592          else if(functionType)
9593          {
9594             bool emptyParams = false, noParams = false;
9595             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9596             Type type = functionType.params.first;
9597             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9598             int extra = 0;
9599             Location oldyylloc = yylloc;
9600
9601             if(!type) emptyParams = true;
9602
9603             // WORKING ON THIS:
9604             if(functionType.extraParam && e && functionType.thisClass)
9605             {
9606                e.destType = MkClassType(functionType.thisClass.string);
9607                e = e.next;
9608             }
9609
9610             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9611             // Fixed #141 by adding '&& !functionType.extraParam'
9612             if(!functionType.staticMethod && !functionType.extraParam)
9613             {
9614                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9615                   memberExp.member.exp.expType._class)
9616                {
9617                   type = MkClassType(memberExp.member.exp.expType._class.string);
9618                   if(e)
9619                   {
9620                      e.destType = type;
9621                      e = e.next;
9622                      type = functionType.params.first;
9623                   }
9624                   else
9625                      type.refCount = 0;
9626                }
9627                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9628                {
9629                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9630                   type.byReference = functionType.byReference;
9631                   type.typedByReference = functionType.typedByReference;
9632                   if(e)
9633                   {
9634                      // Allow manually passing a class for typed object
9635                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9636                         e = e.next;
9637                      e.destType = type;
9638                      e = e.next;
9639                      type = functionType.params.first;
9640                   }
9641                   else
9642                      type.refCount = 0;
9643                   //extra = 1;
9644                }
9645             }
9646
9647             if(type && type.kind == voidType)
9648             {
9649                noParams = true;
9650                if(!type.refCount) FreeType(type);
9651                type = null;
9652             }
9653
9654             for( ; e; e = e.next)
9655             {
9656                if(!type && !emptyParams)
9657                {
9658                   yylloc = e.loc;
9659                   if(methodType && methodType.methodClass)
9660                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9661                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9662                         noParams ? 0 : functionType.params.count);
9663                   else
9664                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9665                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9666                         noParams ? 0 : functionType.params.count);
9667                   break;
9668                }
9669
9670                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9671                {
9672                   Type templatedType = null;
9673                   Class _class = methodType.usedClass;
9674                   ClassTemplateParameter curParam = null;
9675                   int id = 0;
9676                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9677                   {
9678                      Class sClass;
9679                      for(sClass = _class; sClass; sClass = sClass.base)
9680                      {
9681                         if(sClass.templateClass) sClass = sClass.templateClass;
9682                         id = 0;
9683                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9684                         {
9685                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9686                            {
9687                               Class nextClass;
9688                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9689                               {
9690                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9691                                  id += nextClass.templateParams.count;
9692                               }
9693                               break;
9694                            }
9695                            id++;
9696                         }
9697                         if(curParam) break;
9698                      }
9699                   }
9700                   if(curParam && _class.templateArgs[id].dataTypeString)
9701                   {
9702                      bool constant = type.constant;
9703                      ClassTemplateArgument arg = _class.templateArgs[id];
9704                      {
9705                         Context context = SetupTemplatesContext(_class);
9706
9707                         /*if(!arg.dataType)
9708                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9709                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9710                         FinishTemplatesContext(context);
9711                      }
9712
9713                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9714                      else if(templatedType.kind == pointerType)
9715                      {
9716                         Type t = templatedType.type;
9717                         while(t.kind == pointerType) t = t.type;
9718                         if(constant) t.constant = constant;
9719                      }
9720
9721                      e.destType = templatedType;
9722                      if(templatedType)
9723                      {
9724                         templatedType.passAsTemplate = true;
9725                         // templatedType.refCount++;
9726                      }
9727                   }
9728                   else
9729                   {
9730                      e.destType = type;
9731                      if(type) type.refCount++;
9732                   }
9733                }
9734                else
9735                {
9736                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9737                   {
9738                      e.destType = type.prev;
9739                      e.destType.refCount++;
9740                   }
9741                   else
9742                   {
9743                      e.destType = type;
9744                      if(type) type.refCount++;
9745                   }
9746                }
9747                // Don't reach the end for the ellipsis
9748                if(type && type.kind != ellipsisType)
9749                {
9750                   Type next = type.next;
9751                   if(!type.refCount) FreeType(type);
9752                   type = next;
9753                }
9754             }
9755
9756             if(type && type.kind != ellipsisType)
9757             {
9758                if(methodType && methodType.methodClass)
9759                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9760                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9761                      functionType.params.count + extra);
9762                else
9763                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9764                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9765                      functionType.params.count + extra);
9766             }
9767             yylloc = oldyylloc;
9768             if(type && !type.refCount) FreeType(type);
9769          }
9770          else
9771          {
9772             functionType = Type
9773             {
9774                refCount = 0;
9775                kind = TypeKind::functionType;
9776             };
9777
9778             if(exp.call.exp.type == identifierExp)
9779             {
9780                char * string = exp.call.exp.identifier.string;
9781                if(inCompiler)
9782                {
9783                   Symbol symbol;
9784                   Location oldyylloc = yylloc;
9785
9786                   yylloc = exp.call.exp.identifier.loc;
9787                   if(strstr(string, "__builtin_") == string)
9788                   {
9789                      if(exp.destType)
9790                      {
9791                         functionType.returnType = exp.destType;
9792                         exp.destType.refCount++;
9793                      }
9794                   }
9795                   else
9796                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9797                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9798                   globalContext.symbols.Add((BTNode)symbol);
9799                   if(strstr(symbol.string, "::"))
9800                      globalContext.hasNameSpace = true;
9801
9802                   yylloc = oldyylloc;
9803                }
9804             }
9805             else if(exp.call.exp.type == memberExp)
9806             {
9807                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9808                   exp.call.exp.member.member.string);*/
9809             }
9810             else
9811                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9812
9813             if(!functionType.returnType)
9814             {
9815                functionType.returnType = Type
9816                {
9817                   refCount = 1;
9818                   kind = intType;
9819                };
9820             }
9821          }
9822          if(functionType && functionType.kind == TypeKind::functionType)
9823          {
9824             exp.expType = functionType.returnType;
9825
9826             if(functionType.returnType)
9827                functionType.returnType.refCount++;
9828
9829             if(!functionType.refCount)
9830                FreeType(functionType);
9831          }
9832
9833          if(exp.call.arguments)
9834          {
9835             for(e = exp.call.arguments->first; e; e = e.next)
9836                ProcessExpressionType(e);
9837          }
9838          break;
9839       }
9840       case memberExp:
9841       {
9842          Type type;
9843          Location oldyylloc = yylloc;
9844          bool thisPtr;
9845          Expression checkExp = exp.member.exp;
9846          while(checkExp)
9847          {
9848             if(checkExp.type == castExp)
9849                checkExp = checkExp.cast.exp;
9850             else if(checkExp.type == bracketsExp)
9851                checkExp = checkExp.list ? checkExp.list->first : null;
9852             else
9853                break;
9854          }
9855
9856          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9857          exp.thisPtr = thisPtr;
9858
9859          // DOING THIS LATER NOW...
9860          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9861          {
9862             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9863             /* TODO: Name Space Fix ups
9864             if(!exp.member.member.classSym)
9865                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9866             */
9867          }
9868
9869          ProcessExpressionType(exp.member.exp);
9870          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9871             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9872          {
9873             exp.isConstant = false;
9874          }
9875          else
9876             exp.isConstant = exp.member.exp.isConstant;
9877          type = exp.member.exp.expType;
9878
9879          yylloc = exp.loc;
9880
9881          if(type && (type.kind == templateType))
9882          {
9883             Class _class = thisClass ? thisClass : currentClass;
9884             ClassTemplateParameter param = null;
9885             if(_class)
9886             {
9887                for(param = _class.templateParams.first; param; param = param.next)
9888                {
9889                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9890                      break;
9891                }
9892             }
9893             if(param && param.defaultArg.member)
9894             {
9895                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9896                if(argExp)
9897                {
9898                   Expression expMember = exp.member.exp;
9899                   Declarator decl;
9900                   OldList * specs = MkList();
9901                   char thisClassTypeString[1024];
9902
9903                   FreeIdentifier(exp.member.member);
9904
9905                   ProcessExpressionType(argExp);
9906
9907                   {
9908                      char * colon = strstr(param.defaultArg.memberString, "::");
9909                      if(colon)
9910                      {
9911                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9912                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9913                      }
9914                      else
9915                         strcpy(thisClassTypeString, _class.fullName);
9916                   }
9917
9918                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9919
9920                   exp.expType = ProcessType(specs, decl);
9921                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9922                   {
9923                      Class expClass = exp.expType._class.registered;
9924                      Class cClass = null;
9925                      int paramCount = 0;
9926                      int lastParam = -1;
9927
9928                      char templateString[1024];
9929                      ClassTemplateParameter param;
9930                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9931                      for(cClass = expClass; cClass; cClass = cClass.base)
9932                      {
9933                         int p = 0;
9934                         for(param = cClass.templateParams.first; param; param = param.next)
9935                         {
9936                            int id = p;
9937                            Class sClass;
9938                            ClassTemplateArgument arg;
9939                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9940                            arg = expClass.templateArgs[id];
9941
9942                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9943                            {
9944                               ClassTemplateParameter cParam;
9945                               //int p = numParams - sClass.templateParams.count;
9946                               int p = 0;
9947                               Class nextClass;
9948                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9949
9950                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9951                               {
9952                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9953                                  {
9954                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9955                                     {
9956                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9957                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9958                                        break;
9959                                     }
9960                                  }
9961                               }
9962                            }
9963
9964                            {
9965                               char argument[256];
9966                               argument[0] = '\0';
9967                               /*if(arg.name)
9968                               {
9969                                  strcat(argument, arg.name.string);
9970                                  strcat(argument, " = ");
9971                               }*/
9972                               switch(param.type)
9973                               {
9974                                  case expression:
9975                                  {
9976                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9977                                     char expString[1024];
9978                                     OldList * specs = MkList();
9979                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9980                                     Expression exp;
9981                                     char * string = PrintHexUInt64(arg.expression.ui64);
9982                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9983                                     delete string;
9984
9985                                     ProcessExpressionType(exp);
9986                                     ComputeExpression(exp);
9987                                     expString[0] = '\0';
9988                                     PrintExpression(exp, expString);
9989                                     strcat(argument, expString);
9990                                     // delete exp;
9991                                     FreeExpression(exp);
9992                                     break;
9993                                  }
9994                                  case identifier:
9995                                  {
9996                                     strcat(argument, arg.member.name);
9997                                     break;
9998                                  }
9999                                  case TemplateParameterType::type:
10000                                  {
10001                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10002                                     {
10003                                        if(!strcmp(arg.dataTypeString, "thisclass"))
10004                                           strcat(argument, thisClassTypeString);
10005                                        else
10006                                           strcat(argument, arg.dataTypeString);
10007                                     }
10008                                     break;
10009                                  }
10010                               }
10011                               if(argument[0])
10012                               {
10013                                  if(paramCount) strcat(templateString, ", ");
10014                                  if(lastParam != p - 1)
10015                                  {
10016                                     strcat(templateString, param.name);
10017                                     strcat(templateString, " = ");
10018                                  }
10019                                  strcat(templateString, argument);
10020                                  paramCount++;
10021                                  lastParam = p;
10022                               }
10023                               p++;
10024                            }
10025                         }
10026                      }
10027                      {
10028                         int len = strlen(templateString);
10029                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10030                         templateString[len++] = '>';
10031                         templateString[len++] = '\0';
10032                      }
10033                      {
10034                         Context context = SetupTemplatesContext(_class);
10035                         FreeType(exp.expType);
10036                         exp.expType = ProcessTypeString(templateString, false);
10037                         FinishTemplatesContext(context);
10038                      }
10039                   }
10040
10041                   if(!expMember.expType.isPointerType)
10042                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10043                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10044                   exp.type = bracketsExp;
10045                   exp.list = MkListOne(MkExpOp(null, '*',
10046                   /*opExp;
10047                   exp.op.op = '*';
10048                   exp.op.exp1 = null;
10049                   exp.op.exp2 = */
10050                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10051                      MkExpBrackets(MkListOne(
10052                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10053                            expMember))),
10054                               '+',
10055                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10056                               '+',
10057                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10058
10059                            ));
10060                }
10061             }
10062             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10063                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10064             {
10065                type = ProcessTemplateParameterType(type.templateParameter);
10066             }
10067          }
10068          // TODO: *** This seems to be where we should add method support for all basic types ***
10069          if(type && (type.kind == templateType));
10070          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10071                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10072                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10073                           (type.kind == pointerType && type.type.kind == charType)))
10074          {
10075             Identifier id = exp.member.member;
10076             TypeKind typeKind = type.kind;
10077             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10078             if(typeKind == subClassType && exp.member.exp.type == classExp)
10079             {
10080                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10081                typeKind = classType;
10082             }
10083
10084             if(id)
10085             {
10086                if(typeKind == intType || typeKind == enumType)
10087                   _class = eSystem_FindClass(privateModule, "int");
10088                else if(!_class)
10089                {
10090                   if(type.kind == classType && type._class && type._class.registered)
10091                   {
10092                      _class = type._class.registered;
10093                   }
10094                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10095                   {
10096                      _class = FindClass("char *").registered;
10097                   }
10098                   else if(type.kind == pointerType)
10099                   {
10100                      _class = eSystem_FindClass(privateModule, "uintptr");
10101                      FreeType(exp.expType);
10102                      exp.expType = ProcessTypeString("uintptr", false);
10103                      exp.byReference = true;
10104                   }
10105                   else
10106                   {
10107                      char string[1024] = "";
10108                      Symbol classSym;
10109                      PrintTypeNoConst(type, string, false, true);
10110                      classSym = FindClass(string);
10111                      if(classSym) _class = classSym.registered;
10112                   }
10113                }
10114             }
10115
10116             if(_class && id)
10117             {
10118                /*bool thisPtr =
10119                   (exp.member.exp.type == identifierExp &&
10120                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10121                Property prop = null;
10122                Method method = null;
10123                DataMember member = null;
10124                Property revConvert = null;
10125                ClassProperty classProp = null;
10126
10127                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10128                   exp.member.memberType = propertyMember;
10129
10130                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10131                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10132
10133                if(typeKind != subClassType)
10134                {
10135                   // Prioritize data members over properties for "this"
10136                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10137                   {
10138                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10139                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10140                      {
10141                         prop = eClass_FindProperty(_class, id.string, privateModule);
10142                         if(prop)
10143                            member = null;
10144                      }
10145                      if(!member && !prop)
10146                         prop = eClass_FindProperty(_class, id.string, privateModule);
10147                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10148                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10149                         exp.member.thisPtr = true;
10150                   }
10151                   // Prioritize properties over data members otherwise
10152                   else
10153                   {
10154                      bool useMemberForNonConst = false;
10155                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10156                      if(!id.classSym)
10157                      {
10158                         prop = eClass_FindProperty(_class, id.string, null);
10159
10160                         useMemberForNonConst = prop && exp.destType &&
10161                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10162                               !strncmp(prop.dataTypeString, "const ", 6);
10163
10164                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10165                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10166                      }
10167
10168                      if((!prop || useMemberForNonConst) && !member)
10169                      {
10170                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10171                         if(!method)
10172                         {
10173                            prop = eClass_FindProperty(_class, id.string, privateModule);
10174
10175                            useMemberForNonConst |= prop && exp.destType &&
10176                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10177                                  !strncmp(prop.dataTypeString, "const ", 6);
10178
10179                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10180                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10181                         }
10182                      }
10183
10184                      if(member && prop)
10185                      {
10186                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10187                            prop = null;
10188                         else
10189                            member = null;
10190                      }
10191                   }
10192                }
10193                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10194                   method = eClass_FindMethod(_class, id.string, privateModule);
10195                if(!prop && !member && !method)
10196                {
10197                   if(typeKind == subClassType)
10198                   {
10199                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10200                      if(classProp)
10201                      {
10202                         exp.member.memberType = classPropertyMember;
10203                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10204                      }
10205                      else
10206                      {
10207                         // Assume this is a class_data member
10208                         char structName[1024];
10209                         Identifier id = exp.member.member;
10210                         Expression classExp = exp.member.exp;
10211                         type.refCount++;
10212
10213                         FreeType(classExp.expType);
10214                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10215
10216                         strcpy(structName, "__ecereClassData_");
10217                         FullClassNameCat(structName, type._class.string, false);
10218                         exp.type = pointerExp;
10219                         exp.member.member = id;
10220
10221                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10222                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10223                               MkExpBrackets(MkListOne(MkExpOp(
10224                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10225                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10226                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10227                                  )));
10228
10229                         FreeType(type);
10230
10231                         ProcessExpressionType(exp);
10232                         return;
10233                      }
10234                   }
10235                   else
10236                   {
10237                      // Check for reverse conversion
10238                      // (Convert in an instantiation later, so that we can use
10239                      //  deep properties system)
10240                      Symbol classSym = FindClass(id.string);
10241                      if(classSym)
10242                      {
10243                         Class convertClass = classSym.registered;
10244                         if(convertClass)
10245                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10246                      }
10247                   }
10248                }
10249
10250                //if(!exp.member.exp.destType)
10251                if(exp.member.exp.destType)
10252                   FreeType(exp.member.exp.destType);
10253                {
10254                   if(method && !method._class.symbol)
10255                      method._class.symbol = FindClass(method._class.fullName);
10256                   if(prop && !prop._class.symbol)
10257                      prop._class.symbol = FindClass(prop._class.fullName);
10258
10259                   exp.member.exp.destType = Type
10260                   {
10261                      refCount = 1;
10262                      kind = classType;
10263                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10264                      // wasThisClass = type ? type.wasThisClass : false;
10265                      thisClassFrom = type ? type.thisClassFrom : null;
10266                   };
10267                }
10268
10269                if(prop)
10270                {
10271                   exp.member.memberType = propertyMember;
10272                   if(!prop.dataType)
10273                      ProcessPropertyType(prop);
10274                   exp.expType = prop.dataType;
10275                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10276                   {
10277                      Type type { };
10278                      CopyTypeInto(type, exp.expType);
10279                      type.refCount = 1;
10280                      type.constant = true;
10281                      exp.expType = type;
10282                   }
10283                   else if(prop.dataType)
10284                      prop.dataType.refCount++;
10285                }
10286                else if(member)
10287                {
10288                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10289                   {
10290                      FreeExpContents(exp);
10291                      exp.type = identifierExp;
10292                      exp.identifier = MkIdentifier("class");
10293                      ProcessExpressionType(exp);
10294                      return;
10295                   }
10296
10297                   exp.member.memberType = dataMember;
10298                   DeclareStruct(curExternal, _class.fullName, false, true);
10299                   if(member._class != _class)
10300                      DeclareStruct(curExternal, member._class.fullName, false, true);
10301
10302                   if(!member.dataType)
10303                   {
10304                      Context context = SetupTemplatesContext(_class);
10305                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10306                      FinishTemplatesContext(context);
10307                   }
10308                   if(exp.member.exp.expType.kind == classType && exp.member.exp.expType._class && exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == bitClass)
10309                      member.dataType.bitMemberSize = ((BitMember)member).size;
10310                   exp.expType = member.dataType;
10311                   if(member.dataType) member.dataType.refCount++;
10312                }
10313                else if(revConvert)
10314                {
10315                   exp.member.memberType = reverseConversionMember;
10316                   exp.expType = MkClassType(revConvert._class.fullName);
10317                }
10318                else if(method)
10319                {
10320                   //if(inCompiler)
10321                   {
10322                      /*if(id._class)
10323                      {
10324                         exp.type = identifierExp;
10325                         exp.identifier = exp.member.member;
10326                      }
10327                      else*/
10328                         exp.member.memberType = methodMember;
10329                   }
10330                   if(!method.dataType)
10331                      ProcessMethodType(method);
10332                   exp.expType = Type
10333                   {
10334                      refCount = 1;
10335                      kind = methodType;
10336                      method = method;
10337                   };
10338
10339                   // Tricky spot here... To use instance versus class virtual table
10340                   // Put it back to what it was... What did we break?
10341
10342                   // Had to put it back for overriding Main of Thread global instance
10343
10344                   //exp.expType.methodClass = _class;
10345                   exp.expType.methodClass = (id && id._class) ? _class : null;
10346
10347                   // Need the actual class used for templated classes
10348                   exp.expType.usedClass = _class;
10349                }
10350                else if(!classProp)
10351                {
10352                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10353                   {
10354                      FreeExpContents(exp);
10355                      exp.type = identifierExp;
10356                      exp.identifier = MkIdentifier("class");
10357                      FreeType(exp.expType);
10358                      exp.expType = MkClassType("ecere::com::Class");
10359                      return;
10360                   }
10361                   yylloc = exp.member.member.loc;
10362                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10363                   if(inCompiler)
10364                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10365                }
10366
10367                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10368                {
10369                   Class tClass;
10370
10371                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10372                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10373
10374                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10375                   {
10376                      int id = 0;
10377                      ClassTemplateParameter curParam = null;
10378                      Class sClass;
10379
10380                      for(sClass = tClass; sClass; sClass = sClass.base)
10381                      {
10382                         id = 0;
10383                         if(sClass.templateClass) sClass = sClass.templateClass;
10384                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10385                         {
10386                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10387                            {
10388                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10389                                  id += sClass.templateParams.count;
10390                               break;
10391                            }
10392                            id++;
10393                         }
10394                         if(curParam) break;
10395                      }
10396
10397                      if(curParam && tClass.templateArgs[id].dataTypeString)
10398                      {
10399                         ClassTemplateArgument arg = tClass.templateArgs[id];
10400                         Context context = SetupTemplatesContext(tClass);
10401                         bool constant = exp.expType.constant;
10402                         bool passAsTemplate = false;
10403                         Class thisClassFrom = null;
10404                         Type t = ProcessTypeString(exp.expType.templateParameter.dataTypeString, false);
10405                         if(t && t.kind == classType && t._class)
10406                            thisClassFrom = t._class.registered;
10407                         else
10408                            // Mark that 'thisClassFrom' was set to something
10409                            thisClassFrom = eSystem_FindClass(GetPrivateModule(), "class");
10410
10411                         FreeType(t);
10412
10413                         passAsTemplate = tClass.templateClass && (exp.expType.kind != templateType ||
10414                            (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType)));
10415
10416                         /*if(!arg.dataType)
10417                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10418                         FreeType(exp.expType);
10419
10420                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10421                         exp.expType.thisClassFrom = thisClassFrom;
10422                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10423                         else if(exp.expType.kind == pointerType)
10424                         {
10425                            Type t = exp.expType.type;
10426                            while(t.kind == pointerType) t = t.type;
10427                            if(constant) t.constant = constant;
10428                         }
10429                         if(exp.expType)
10430                         {
10431                            if(exp.expType.kind == thisClassType)
10432                            {
10433                               FreeType(exp.expType);
10434                               exp.expType = ReplaceThisClassType(_class);
10435                            }
10436
10437                            if(passAsTemplate)
10438                               exp.expType.passAsTemplate = true;
10439                            //exp.expType.refCount++;
10440                            if(!exp.destType)
10441                            {
10442                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10443                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10444                               else if(exp.destType.kind == pointerType)
10445                               {
10446                                  Type t = exp.destType.type;
10447                                  while(t.kind == pointerType) t = t.type;
10448                                  if(constant) t.constant = constant;
10449                               }
10450
10451                               //exp.destType.refCount++;
10452
10453                               if(exp.destType.kind == thisClassType)
10454                               {
10455                                  FreeType(exp.destType);
10456                                  exp.destType = ReplaceThisClassType(_class);
10457                               }
10458                            }
10459                         }
10460                         FinishTemplatesContext(context);
10461                      }
10462                   }
10463                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10464                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10465                   {
10466                      int id = 0;
10467                      ClassTemplateParameter curParam = null;
10468                      Class sClass;
10469
10470                      for(sClass = tClass; sClass; sClass = sClass.base)
10471                      {
10472                         id = 0;
10473                         if(sClass.templateClass) sClass = sClass.templateClass;
10474                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10475                         {
10476                            if(curParam.type == TemplateParameterType::type &&
10477                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10478                            {
10479                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10480                                  id += sClass.templateParams.count;
10481                               break;
10482                            }
10483                            id++;
10484                         }
10485                         if(curParam) break;
10486                      }
10487
10488                      if(curParam)
10489                      {
10490                         ClassTemplateArgument arg = tClass.templateArgs[id];
10491                         Context context = SetupTemplatesContext(tClass);
10492                         Type basicType;
10493                         /*if(!arg.dataType)
10494                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10495
10496                         basicType = ProcessTypeString(arg.dataTypeString, false);
10497                         if(basicType)
10498                         {
10499                            if(basicType.kind == thisClassType)
10500                            {
10501                               FreeType(basicType);
10502                               basicType = ReplaceThisClassType(_class);
10503                            }
10504
10505                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10506                            if(tClass.templateClass)
10507                               basicType.passAsTemplate = true;
10508                            */
10509
10510                            FreeType(exp.expType);
10511
10512                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10513                            //exp.expType.refCount++;
10514                            if(!exp.destType)
10515                            {
10516                               exp.destType = exp.expType;
10517                               exp.destType.refCount++;
10518                            }
10519
10520                            {
10521                               Expression newExp { };
10522                               OldList * specs = MkList();
10523                               Declarator decl;
10524                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10525                               *newExp = *exp;
10526                               if(exp.destType) exp.destType.refCount++;
10527                               if(exp.expType)  exp.expType.refCount++;
10528                               exp.type = castExp;
10529                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10530                               exp.cast.exp = newExp;
10531                               //FreeType(exp.expType);
10532                               //exp.expType = null;
10533                               //ProcessExpressionType(sourceExp);
10534                            }
10535                         }
10536                         FinishTemplatesContext(context);
10537                      }
10538                   }
10539                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10540                   {
10541                      Class expClass = exp.expType._class.registered;
10542                      if(expClass)
10543                      {
10544                         Class cClass = null;
10545                         int p = 0;
10546                         int paramCount = 0;
10547                         int lastParam = -1;
10548                         char templateString[1024];
10549                         ClassTemplateParameter param;
10550                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10551                         while(cClass != expClass)
10552                         {
10553                            Class sClass;
10554                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10555                            cClass = sClass;
10556
10557                            for(param = cClass.templateParams.first; param; param = param.next)
10558                            {
10559                               Class cClassCur = null;
10560                               int cp = 0;
10561                               ClassTemplateParameter paramCur = null;
10562                               ClassTemplateArgument arg;
10563                               while(cClassCur != tClass && !paramCur)
10564                               {
10565                                  Class sClassCur;
10566                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10567                                  cClassCur = sClassCur;
10568
10569                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10570                                  {
10571                                     if(!strcmp(paramCur.name, param.name))
10572                                     {
10573
10574                                        break;
10575                                     }
10576                                     cp++;
10577                                  }
10578                               }
10579                               if(paramCur && paramCur.type == TemplateParameterType::type)
10580                                  arg = tClass.templateArgs[cp];
10581                               else
10582                                  arg = expClass.templateArgs[p];
10583
10584                               {
10585                                  char argument[256];
10586                                  argument[0] = '\0';
10587                                  /*if(arg.name)
10588                                  {
10589                                     strcat(argument, arg.name.string);
10590                                     strcat(argument, " = ");
10591                                  }*/
10592                                  switch(param.type)
10593                                  {
10594                                     case expression:
10595                                     {
10596                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10597                                        char expString[1024];
10598                                        OldList * specs = MkList();
10599                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10600                                        Expression exp;
10601                                        char * string = PrintHexUInt64(arg.expression.ui64);
10602                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10603                                        delete string;
10604
10605                                        ProcessExpressionType(exp);
10606                                        ComputeExpression(exp);
10607                                        expString[0] = '\0';
10608                                        PrintExpression(exp, expString);
10609                                        strcat(argument, expString);
10610                                        // delete exp;
10611                                        FreeExpression(exp);
10612                                        break;
10613                                     }
10614                                     case identifier:
10615                                     {
10616                                        strcat(argument, arg.member.name);
10617                                        break;
10618                                     }
10619                                     case TemplateParameterType::type:
10620                                     {
10621                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10622                                           strcat(argument, arg.dataTypeString);
10623                                        break;
10624                                     }
10625                                  }
10626                                  if(argument[0])
10627                                  {
10628                                     if(paramCount) strcat(templateString, ", ");
10629                                     if(lastParam != p - 1)
10630                                     {
10631                                        strcat(templateString, param.name);
10632                                        strcat(templateString, " = ");
10633                                     }
10634                                     strcat(templateString, argument);
10635                                     paramCount++;
10636                                     lastParam = p;
10637                                  }
10638                               }
10639                               p++;
10640                            }
10641                         }
10642                         {
10643                            int len = strlen(templateString);
10644                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10645                            templateString[len++] = '>';
10646                            templateString[len++] = '\0';
10647                         }
10648
10649                         FreeType(exp.expType);
10650                         {
10651                            Context context = SetupTemplatesContext(tClass);
10652                            exp.expType = ProcessTypeString(templateString, false);
10653                            FinishTemplatesContext(context);
10654                         }
10655                      }
10656                   }
10657                }
10658             }
10659             else
10660                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10661          }
10662          else if(type && (type.kind == structType || type.kind == unionType))
10663          {
10664             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10665             if(memberType)
10666             {
10667                exp.expType = memberType;
10668                if(memberType)
10669                   memberType.refCount++;
10670             }
10671          }
10672          else
10673          {
10674             char expString[10240];
10675             expString[0] = '\0';
10676             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10677             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10678          }
10679
10680          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10681          {
10682             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10683             {
10684                Identifier id = exp.member.member;
10685                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10686                if(_class)
10687                {
10688                   FreeType(exp.expType);
10689                   exp.expType = ReplaceThisClassType(_class);
10690                }
10691             }
10692          }
10693          yylloc = oldyylloc;
10694          break;
10695       }
10696       // Convert x->y into (*x).y
10697       case pointerExp:
10698       {
10699          Type destType = exp.destType;
10700
10701          // DOING THIS LATER NOW...
10702          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10703          {
10704             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10705             /* TODO: Name Space Fix ups
10706             if(!exp.member.member.classSym)
10707                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10708             */
10709          }
10710
10711          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10712          exp.type = memberExp;
10713          if(destType)
10714             destType.count++;
10715          ProcessExpressionType(exp);
10716          if(destType)
10717             destType.count--;
10718          break;
10719       }
10720       case classSizeExp:
10721       {
10722          //ComputeExpression(exp);
10723
10724          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10725          if(classSym && classSym.registered)
10726          {
10727             if(classSym.registered.type == noHeadClass || (classSym.registered.fixed && classSym.registered.structSize))
10728             {
10729                char name[1024];
10730                Class b = classSym.registered;
10731                name[0] = '\0';
10732                DeclareStruct(curExternal, classSym.string, false, true);
10733                FreeSpecifier(exp._class);
10734                FullClassNameCat(name, classSym.string, false);
10735
10736                if(b.offset == 0)
10737                {
10738                   exp.type = typeSizeExp;
10739                   exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10740                }
10741                else
10742                {
10743                   Expression e;
10744                   exp.type = opExp;
10745                   if(b.structSize == b.offset)
10746                      exp.op.exp1 = MkExpConstant("0");
10747                   else
10748                      exp.op.exp1 = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10749                   exp.op.op = '+';
10750                   e = exp;
10751                   while(b.offset != 0)
10752                   {
10753                      Symbol sym;
10754                      Expression typeSize;
10755
10756                      b = b.base;
10757                      sym = FindClass(b.fullName);
10758
10759                      name[0] = '\0';
10760                      DeclareStruct(curExternal, sym.string, false, true);
10761                      FullClassNameCat(name, sym.string, false);
10762
10763                      if(b.structSize == b.offset)
10764                         typeSize = MkExpConstant("0");
10765                      else
10766                         typeSize = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10767                      e.op.exp2 = b.offset ? MkExpOp(typeSize, '+', null) : typeSize;
10768                      e = e.op.exp2;
10769                   }
10770                }
10771             }
10772             else
10773             {
10774                if(classSym.registered.fixed && !classSym.registered.structSize)
10775                {
10776                   FreeSpecifier(exp._class);
10777                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10778                   exp.type = constantExp;
10779                }
10780                else
10781                {
10782                   char className[1024];
10783                   strcpy(className, "__ecereClass_");
10784                   FullClassNameCat(className, classSym.string, true);
10785
10786                   DeclareClass(curExternal, classSym, className);
10787
10788                   FreeExpContents(exp);
10789                   exp.type = pointerExp;
10790                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10791                   exp.member.member = MkIdentifier("structSize");
10792                }
10793             }
10794          }
10795
10796          exp.expType = Type
10797          {
10798             refCount = 1;
10799             kind = intSizeType;
10800          };
10801          // exp.isConstant = true;
10802          break;
10803       }
10804       case typeSizeExp:
10805       {
10806          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10807
10808          exp.expType = Type
10809          {
10810             refCount = 1;
10811             kind = intSizeType;
10812          };
10813          exp.isConstant = true;
10814
10815          DeclareType(curExternal, type, true, false);
10816          FreeType(type);
10817          break;
10818       }
10819       case castExp:
10820       {
10821          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10822          type.count = 1;
10823          FreeType(exp.cast.exp.destType);
10824          exp.cast.exp.destType = type;
10825          type.refCount++;
10826          type.casted = true;
10827          ProcessExpressionType(exp.cast.exp);
10828          type.casted = false;
10829          type.count = 0;
10830          exp.expType = type;
10831          //type.refCount++;
10832
10833          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10834          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10835          {
10836             void * prev = exp.prev, * next = exp.next;
10837             Type expType = exp.cast.exp.destType;
10838             Expression castExp = exp.cast.exp;
10839             Type destType = exp.destType;
10840
10841             if(expType) expType.refCount++;
10842
10843             //FreeType(exp.destType);
10844             FreeType(exp.expType);
10845             FreeTypeName(exp.cast.typeName);
10846
10847             *exp = *castExp;
10848             FreeType(exp.expType);
10849             FreeType(exp.destType);
10850
10851             exp.expType = expType;
10852             exp.destType = destType;
10853
10854             delete castExp;
10855
10856             exp.prev = prev;
10857             exp.next = next;
10858
10859          }
10860          else
10861          {
10862             exp.isConstant = exp.cast.exp.isConstant;
10863          }
10864          //FreeType(type);
10865          break;
10866       }
10867       case extensionInitializerExp:
10868       {
10869          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10870          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10871          // ProcessInitializer(exp.initializer.initializer, type);
10872          exp.expType = type;
10873          break;
10874       }
10875       case vaArgExp:
10876       {
10877          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10878          ProcessExpressionType(exp.vaArg.exp);
10879          exp.expType = type;
10880          break;
10881       }
10882       case conditionExp:
10883       {
10884          Expression e;
10885          Type t = exp.destType;
10886          if(t && !exp.destType.casted)
10887          {
10888             t = { };
10889             CopyTypeInto(t, exp.destType);
10890             t.count = 0;
10891          }
10892          else if(t)
10893             t.refCount++;
10894
10895          exp.isConstant = true;
10896
10897          FreeType(exp.cond.cond.destType);
10898          exp.cond.cond.destType = MkClassType("bool");
10899          exp.cond.cond.destType.truth = true;
10900          ProcessExpressionType(exp.cond.cond);
10901          if(!exp.cond.cond.isConstant)
10902             exp.isConstant = false;
10903          for(e = exp.cond.exp->first; e; e = e.next)
10904          {
10905             if(!e.next)
10906             {
10907                FreeType(e.destType);
10908                e.destType = t;
10909                if(e.destType) e.destType.refCount++;
10910             }
10911             ProcessExpressionType(e);
10912             if(!e.next)
10913             {
10914                exp.expType = e.expType;
10915                if(e.expType) e.expType.refCount++;
10916             }
10917             if(!e.isConstant)
10918                exp.isConstant = false;
10919          }
10920
10921          FreeType(exp.cond.elseExp.destType);
10922          // Added this check if we failed to find an expType
10923          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10924
10925          // Reversed it...
10926          exp.cond.elseExp.destType = t ? t : exp.expType;
10927
10928          if(exp.cond.elseExp.destType)
10929             exp.cond.elseExp.destType.refCount++;
10930          ProcessExpressionType(exp.cond.elseExp);
10931
10932          // FIXED THIS: Was done before calling process on elseExp
10933          if(!exp.cond.elseExp.isConstant)
10934             exp.isConstant = false;
10935
10936          FreeType(t);
10937          break;
10938       }
10939       case extensionCompoundExp:
10940       {
10941          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10942          {
10943             Statement last = exp.compound.compound.statements->last;
10944             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10945             {
10946                ((Expression)last.expressions->last).destType = exp.destType;
10947                if(exp.destType)
10948                   exp.destType.refCount++;
10949             }
10950             ProcessStatement(exp.compound);
10951             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10952             if(exp.expType)
10953                exp.expType.refCount++;
10954          }
10955          break;
10956       }
10957       case classExp:
10958       {
10959          Specifier spec = exp._classExp.specifiers->first;
10960          if(spec && spec.type == nameSpecifier)
10961          {
10962             exp.expType = MkClassType(spec.name);
10963             exp.expType.kind = subClassType;
10964             exp.byReference = true;
10965          }
10966          else
10967          {
10968             exp.expType = MkClassType("ecere::com::Class");
10969             exp.byReference = true;
10970          }
10971          break;
10972       }
10973       case classDataExp:
10974       {
10975          Class _class = thisClass ? thisClass : currentClass;
10976          if(_class)
10977          {
10978             Identifier id = exp.classData.id;
10979             char structName[1024];
10980             Expression classExp;
10981             strcpy(structName, "__ecereClassData_");
10982             FullClassNameCat(structName, _class.fullName, false);
10983             exp.type = pointerExp;
10984             exp.member.member = id;
10985             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10986                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10987             else
10988                classExp = MkExpIdentifier(MkIdentifier("class"));
10989
10990             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10991                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10992                   MkExpBrackets(MkListOne(MkExpOp(
10993                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10994                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10995                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10996                      )));
10997
10998             ProcessExpressionType(exp);
10999             return;
11000          }
11001          break;
11002       }
11003       case arrayExp:
11004       {
11005          Type type = null;
11006          const char * typeString = null;
11007          char typeStringBuf[1024];
11008          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
11009             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
11010          {
11011             Class templateClass = exp.destType._class.registered;
11012             typeString = templateClass.templateArgs[2].dataTypeString;
11013          }
11014          else if(exp.list)
11015          {
11016             // Guess type from expressions in the array
11017             Expression e;
11018             for(e = exp.list->first; e; e = e.next)
11019             {
11020                ProcessExpressionType(e);
11021                if(e.expType)
11022                {
11023                   if(!type) { type = e.expType; type.refCount++; }
11024                   else
11025                   {
11026                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11027                      if(!MatchTypeExpression(e, type, null, false, true))
11028                      {
11029                         FreeType(type);
11030                         type = e.expType;
11031                         e.expType = null;
11032
11033                         e = exp.list->first;
11034                         ProcessExpressionType(e);
11035                         if(e.expType)
11036                         {
11037                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
11038                            if(!MatchTypeExpression(e, type, null, false, true))
11039                            {
11040                               FreeType(e.expType);
11041                               e.expType = null;
11042                               FreeType(type);
11043                               type = null;
11044                               break;
11045                            }
11046                         }
11047                      }
11048                   }
11049                   if(e.expType)
11050                   {
11051                      FreeType(e.expType);
11052                      e.expType = null;
11053                   }
11054                }
11055             }
11056             if(type)
11057             {
11058                typeStringBuf[0] = '\0';
11059                PrintTypeNoConst(type, typeStringBuf, false, true);
11060                typeString = typeStringBuf;
11061                FreeType(type);
11062                type = null;
11063             }
11064          }
11065          if(typeString)
11066          {
11067             /*
11068             (Container)& (struct BuiltInContainer)
11069             {
11070                ._vTbl = class(BuiltInContainer)._vTbl,
11071                ._class = class(BuiltInContainer),
11072                .refCount = 0,
11073                .data = (int[]){ 1, 7, 3, 4, 5 },
11074                .count = 5,
11075                .type = class(int),
11076             }
11077             */
11078             char templateString[1024];
11079             OldList * initializers = MkList();
11080             OldList * structInitializers = MkList();
11081             OldList * specs = MkList();
11082             Expression expExt;
11083             Declarator decl = SpecDeclFromString(typeString, specs, null);
11084             sprintf(templateString, "Container<%s>", typeString);
11085
11086             if(exp.list)
11087             {
11088                Expression e;
11089                type = ProcessTypeString(typeString, false);
11090                while((e = exp.list->first))
11091                {
11092                   exp.list->Remove(e);
11093                   e.destType = type;
11094                   type.refCount++;
11095                   ProcessExpressionType(e);
11096                   ListAdd(initializers, MkInitializerAssignment(e));
11097                }
11098                FreeType(type);
11099                delete exp.list;
11100             }
11101
11102             DeclareStruct(curExternal, "ecere::com::BuiltInContainer", false, true);
11103
11104             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11105                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11106             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11107                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11108             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11109                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11110             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11111                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11112                MkInitializerList(initializers))));
11113                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11114             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11115                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11116             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11117                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11118             exp.expType = ProcessTypeString(templateString, false);
11119             exp.type = bracketsExp;
11120             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11121                MkExpOp(null, '&',
11122                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11123                   MkInitializerList(structInitializers)))));
11124             ProcessExpressionType(expExt);
11125          }
11126          else
11127          {
11128             exp.expType = ProcessTypeString("Container", false);
11129             Compiler_Error($"Couldn't determine type of array elements\n");
11130          }
11131          break;
11132       }
11133    }
11134
11135    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11136    {
11137       FreeType(exp.expType);
11138       exp.expType = ReplaceThisClassType(thisClass);
11139    }
11140
11141    // Resolve structures here
11142    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11143    {
11144       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11145       // TODO: Fix members reference...
11146       if(symbol)
11147       {
11148          if(exp.expType.kind != enumType)
11149          {
11150             Type member;
11151             String enumName = CopyString(exp.expType.enumName);
11152
11153             // Fixed a memory leak on self-referencing C structs typedefs
11154             // by instantiating a new type rather than simply copying members
11155             // into exp.expType
11156             FreeType(exp.expType);
11157             exp.expType = Type { };
11158             exp.expType.kind = symbol.type.kind;
11159             exp.expType.refCount++;
11160             exp.expType.enumName = enumName;
11161
11162             exp.expType.members = symbol.type.members;
11163             for(member = symbol.type.members.first; member; member = member.next)
11164                member.refCount++;
11165          }
11166          else
11167          {
11168             NamedLink64 member;
11169             for(member = symbol.type.members.first; member; member = member.next)
11170             {
11171                NamedLink64 value { name = CopyString(member.name) };
11172                exp.expType.members.Add(value);
11173             }
11174          }
11175       }
11176    }
11177
11178    // Trying to do this here before conversion properties kick in and this becomes a new expression... (Fixing Class c; const char * a = c;)
11179    // Mark nohead classes as by reference, unless we're casting them to an integral type
11180    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11181       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11182          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11183           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11184    {
11185       exp.byReference = true;
11186    }
11187
11188    yylloc = exp.loc;
11189    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11190    else if(exp.destType && !exp.destType.keepCast)
11191    {
11192       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11193          exp.needTemplateCast = 1;
11194
11195       if(exp.destType.kind == voidType);
11196       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11197       {
11198          // Warn for casting unrelated types to/from struct classes
11199          bool invalidCast = false;
11200          if(inCompiler && exp.destType.count && exp.expType)
11201          {
11202             Class c1 = (exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
11203             Class c2 = (exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
11204             if(c1 && c1.type != structClass) c1 = null;
11205             if(c2 && c2.type != structClass) c2 = null;
11206             if((c1 && !exp.expType.byReference && !c2 && !exp.destType.isPointerType) || (c2 && !exp.destType.byReference && !c1 && !exp.expType.isPointerType))
11207                invalidCast = true;
11208          }
11209          if(!exp.destType.count || unresolved || invalidCast)
11210          {
11211             if(!exp.expType)
11212             {
11213                yylloc = exp.loc;
11214                if(exp.destType.kind != ellipsisType)
11215                {
11216                   char type2[1024];
11217                   type2[0] = '\0';
11218                   if(inCompiler)
11219                   {
11220                      char expString[10240];
11221                      expString[0] = '\0';
11222
11223                      PrintType(exp.destType, type2, false, true);
11224
11225                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11226                      if(unresolved)
11227                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11228                      else if(exp.type != dummyExp)
11229                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11230                   }
11231                }
11232                else
11233                {
11234                   char expString[10240] ;
11235                   expString[0] = '\0';
11236                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11237
11238                   if(unresolved)
11239                      Compiler_Error($"unresolved identifier %s\n", expString);
11240                   else if(exp.type != dummyExp)
11241                      Compiler_Error($"couldn't determine type of %s\n", expString);
11242                }
11243             }
11244             else
11245             {
11246                char type1[1024];
11247                char type2[1024];
11248                type1[0] = '\0';
11249                type2[0] = '\0';
11250                if(inCompiler)
11251                {
11252                   PrintType(exp.expType, type1, false, true);
11253                   PrintType(exp.destType, type2, false, true);
11254                }
11255
11256                //CheckExpressionType(exp, exp.destType, false);
11257
11258                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11259                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11260                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11261                else
11262                {
11263                   Expression nbExp = GetNonBracketsExp(exp);
11264                   bool skipWarning = false;
11265                   TypeKind kind = exp.destType.kind;
11266                   if(nbExp.type == conditionExp && nbExp.destType && !nbExp.destType.casted && nbExp.destType.kind == exp.destType.kind)
11267                      // The if/else operands have already been checked / warned about
11268                      skipWarning = true;
11269                   if((kind == charType || kind == shortType) && exp.destType.isSigned == exp.expType.signedBeforePromotion && nbExp.type == opExp && nbExp.op.exp1 && nbExp.op.exp2)
11270                   {
11271                      int op = nbExp.op.op;
11272                      Expression nbExp1, nbExp2;
11273                      TypeKind from;
11274
11275                      switch(op)
11276                      {
11277                         case '%': case '/':
11278                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11279                            from = nbExp1.expType.promotedFrom;
11280                            // Division and Modulo will not take more room than type before promotion
11281                            if(from == charType || (kind == shortType && from == shortType))
11282                               skipWarning = true;
11283                            break;
11284                         // Left shift
11285                         case LEFT_OP: case RIGHT_OP:
11286                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11287                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11288                            from = nbExp1.expType.promotedFrom;
11289                            // Right shift will not take more room than type before promotion
11290                            if(op == RIGHT_OP && (from == charType || (kind == shortType && from == shortType)))
11291                               skipWarning = true;
11292                            else if(nbExp2.isConstant && nbExp2.type == constantExp && (nbExp.op.op == RIGHT_OP || nbExp1.expType.bitMemberSize))
11293                            {
11294                               int n = (int)strtol(nbExp2.constant, null, 0);
11295                               int s = from == charType ? 8 : 16;
11296                               // Left shifting a bit member constrained in size may still fit in type before promotion
11297                               if(nbExp1.expType.bitMemberSize && nbExp1.expType.bitMemberSize < s)
11298                                  s = nbExp1.expType.bitMemberSize;
11299
11300                               // If right shifted enough things will fit in smaller type
11301                               if(nbExp.op.op == RIGHT_OP)
11302                                  s -= n;
11303                               else
11304                                  s += n;
11305                               if(s <= (kind == charType ? 8 : 16))
11306                                  skipWarning = true;
11307                            }
11308                            break;
11309                         case '-':
11310                            if(!exp.destType.isSigned)
11311                            {
11312                               nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11313                               nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11314                               from = nbExp2.expType.promotedFrom;
11315                               // Max value of unsigned type before promotion minus the same will always fit
11316                               if((from == charType || from == shortType) && nbExp1.isConstant && nbExp1.type == constantExp)
11317                               {
11318                                  int n = (int)strtol(nbExp1.constant, null, 0);
11319                                  if(n == (from == charType ? 255 : 65535))
11320                                     skipWarning = true;
11321                               }
11322                            }
11323                            break;
11324                         case '|':
11325                         {
11326                            TypeKind kind1, kind2;
11327                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11328                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11329                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11330                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11331                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) &&
11332                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11333                               skipWarning = true;
11334                            break;
11335                         }
11336                         case '&':
11337                         {
11338                            TypeKind kind1, kind2;
11339                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11340                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11341                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11342                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11343                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) ||
11344                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11345                               skipWarning = true;
11346                            break;
11347                         }
11348                      }
11349                   }
11350
11351                   if(!skipWarning)
11352                   {
11353                      char expString[10240];
11354                      expString[0] = '\0';
11355                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11356
11357 #ifdef _DEBUG
11358                      CheckExpressionType(exp, exp.destType, false, true);
11359 #endif
11360
11361                      // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11362                      if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11363                                         !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11364                                         !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11365                                         !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11366                      {
11367                         if(invalidCast)
11368                            Compiler_Error($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11369                         else
11370                            Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11371                      }
11372                   }
11373
11374                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11375                   if(!inCompiler)
11376                   {
11377                      FreeType(exp.expType);
11378                      exp.destType.refCount++;
11379                      exp.expType = exp.destType;
11380                   }
11381                }
11382             }
11383          }
11384       }
11385       // Cast function pointers to void * as eC already checked compatibility
11386       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11387               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11388       {
11389          Expression nbExp = GetNonBracketsExp(exp);
11390          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11391          {
11392             Expression e = MoveExpContents(exp);
11393             exp.cast.exp = MkExpBrackets(MkListOne(e));
11394             exp.type = castExp;
11395             exp.cast.exp.destType = exp.destType;
11396             if(exp.destType) exp.destType.refCount++;
11397             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11398          }
11399       }
11400    }
11401    else if(unresolved)
11402    {
11403       if(exp.identifier._class && exp.identifier._class.name)
11404          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11405       else if(exp.identifier.string && exp.identifier.string[0])
11406          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11407    }
11408    else if(!exp.expType && exp.type != dummyExp)
11409    {
11410       char expString[10240];
11411       expString[0] = '\0';
11412       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11413       Compiler_Error($"couldn't determine type of %s\n", expString);
11414    }
11415
11416    // Let's try to support any_object & typed_object here:
11417    if(inCompiler)
11418       ApplyAnyObjectLogic(exp);
11419
11420    // Mark nohead classes as by reference, unless we're casting them to an integral type
11421    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11422       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11423          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11424           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11425    {
11426       exp.byReference = true;
11427    }
11428    yylloc = oldyylloc;
11429 }
11430
11431 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11432 {
11433    // THIS CODE WILL FIND NEXT MEMBER...
11434    if(*curMember)
11435    {
11436       *curMember = (*curMember).next;
11437
11438       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11439       {
11440          *curMember = subMemberStack[--(*subMemberStackPos)];
11441          *curMember = (*curMember).next;
11442       }
11443
11444       // SKIP ALL PROPERTIES HERE...
11445       while((*curMember) && (*curMember).isProperty)
11446          *curMember = (*curMember).next;
11447
11448       if(subMemberStackPos)
11449       {
11450          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11451          {
11452             subMemberStack[(*subMemberStackPos)++] = *curMember;
11453
11454             *curMember = (*curMember).members.first;
11455             while(*curMember && (*curMember).isProperty)
11456                *curMember = (*curMember).next;
11457          }
11458       }
11459    }
11460    while(!*curMember)
11461    {
11462       if(!*curMember)
11463       {
11464          if(subMemberStackPos && *subMemberStackPos)
11465          {
11466             *curMember = subMemberStack[--(*subMemberStackPos)];
11467             *curMember = (*curMember).next;
11468          }
11469          else
11470          {
11471             Class lastCurClass = *curClass;
11472
11473             if(*curClass == _class) break;     // REACHED THE END
11474
11475             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11476             *curMember = (*curClass).membersAndProperties.first;
11477          }
11478
11479          while((*curMember) && (*curMember).isProperty)
11480             *curMember = (*curMember).next;
11481          if(subMemberStackPos)
11482          {
11483             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11484             {
11485                subMemberStack[(*subMemberStackPos)++] = *curMember;
11486
11487                *curMember = (*curMember).members.first;
11488                while(*curMember && (*curMember).isProperty)
11489                   *curMember = (*curMember).next;
11490             }
11491          }
11492       }
11493    }
11494 }
11495
11496
11497 static void ProcessInitializer(Initializer init, Type type)
11498 {
11499    switch(init.type)
11500    {
11501       case expInitializer:
11502          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11503          {
11504             // TESTING THIS FOR SHUTTING = 0 WARNING
11505             if(init.exp && !init.exp.destType)
11506             {
11507                FreeType(init.exp.destType);
11508                init.exp.destType = type;
11509                if(type) type.refCount++;
11510             }
11511             if(init.exp)
11512             {
11513                ProcessExpressionType(init.exp);
11514                init.isConstant = init.exp.isConstant;
11515             }
11516             break;
11517          }
11518          else
11519          {
11520             Expression exp = init.exp;
11521             Instantiation inst = exp.instance;
11522             MembersInit members;
11523
11524             init.type = listInitializer;
11525             init.list = MkList();
11526
11527             if(inst.members)
11528             {
11529                for(members = inst.members->first; members; members = members.next)
11530                {
11531                   if(members.type == dataMembersInit)
11532                   {
11533                      MemberInit member;
11534                      for(member = members.dataMembers->first; member; member = member.next)
11535                      {
11536                         ListAdd(init.list, member.initializer);
11537                         member.initializer = null;
11538                      }
11539                   }
11540                   // Discard all MembersInitMethod
11541                }
11542             }
11543             FreeExpression(exp);
11544          }
11545       case listInitializer:
11546       {
11547          Initializer i;
11548          Type initializerType = null;
11549          Class curClass = null;
11550          DataMember curMember = null;
11551          DataMember subMemberStack[256];
11552          int subMemberStackPos = 0;
11553
11554          if(type && type.kind == arrayType)
11555             initializerType = Dereference(type);
11556          else if(type && (type.kind == structType || type.kind == unionType))
11557             initializerType = type.members.first;
11558
11559          for(i = init.list->first; i; i = i.next)
11560          {
11561             if(type && type.kind == classType && type._class && type._class.registered)
11562             {
11563                // 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)
11564                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11565                // TODO: Generate error on initializing a private data member this way from another module...
11566                if(curMember)
11567                {
11568                   if(!curMember.dataType)
11569                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11570                   initializerType = curMember.dataType;
11571                }
11572             }
11573             ProcessInitializer(i, initializerType);
11574             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11575                initializerType = initializerType.next;
11576             if(!i.isConstant)
11577                init.isConstant = false;
11578          }
11579
11580          if(type && type.kind == arrayType)
11581             FreeType(initializerType);
11582
11583          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11584          {
11585             Compiler_Error($"Assigning list initializer to non list\n");
11586          }
11587          break;
11588       }
11589    }
11590 }
11591
11592 static void ProcessSpecifier(Specifier spec, bool declareStruct, bool warnClasses)
11593 {
11594    switch(spec.type)
11595    {
11596       case baseSpecifier:
11597       {
11598          if(spec.specifier == THISCLASS)
11599          {
11600             if(thisClass)
11601             {
11602                spec.type = nameSpecifier;
11603                spec.name = ReplaceThisClass(thisClass);
11604                spec.symbol = FindClass(spec.name);
11605                ProcessSpecifier(spec, declareStruct, false);
11606             }
11607          }
11608          break;
11609       }
11610       case nameSpecifier:
11611       {
11612          Symbol symbol = FindType(curContext, spec.name);
11613          if(symbol)
11614             DeclareType(curExternal, symbol.type, true, true);
11615          else if(spec.symbol /*&& declareStruct*/)
11616          {
11617             Class c = spec.symbol.registered;
11618             if(warnClasses && !c)
11619                Compiler_Warning("Undeclared class %s\n", spec.name);
11620             DeclareStruct(curExternal, spec.name, c && c.type == noHeadClass, declareStruct && c && c.type == structClass);
11621          }
11622          break;
11623       }
11624       case enumSpecifier:
11625       {
11626          Enumerator e;
11627          if(spec.list)
11628          {
11629             for(e = spec.list->first; e; e = e.next)
11630             {
11631                if(e.exp)
11632                   ProcessExpressionType(e.exp);
11633             }
11634          }
11635          // Fall through for IDE type processing
11636          if(inCompiler)
11637             break;
11638       }
11639       case structSpecifier:
11640       case unionSpecifier:
11641       {
11642          if(spec.definitions)
11643          {
11644             //ClassDef def;
11645             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11646             //if(symbol)
11647                ProcessClass(spec.definitions, symbol);
11648             /*else
11649             {
11650                for(def = spec.definitions->first; def; def = def.next)
11651                {
11652                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11653                      ProcessDeclaration(def.decl);
11654                }
11655             }*/
11656          }
11657          break;
11658       }
11659       /*
11660       case classSpecifier:
11661       {
11662          Symbol classSym = FindClass(spec.name);
11663          if(classSym && classSym.registered && classSym.registered.type == structClass)
11664             DeclareStruct(spec.name, false, true);
11665          break;
11666       }
11667       */
11668    }
11669 }
11670
11671
11672 static void ProcessDeclarator(Declarator decl, bool isFunction)
11673 {
11674    switch(decl.type)
11675    {
11676       case identifierDeclarator:
11677          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11678          {
11679             FreeSpecifier(decl.identifier._class);
11680             decl.identifier._class = null;
11681          }
11682          break;
11683       case arrayDeclarator:
11684          if(decl.array.exp)
11685             ProcessExpressionType(decl.array.exp);
11686       case structDeclarator:
11687       case bracketsDeclarator:
11688       case functionDeclarator:
11689       case pointerDeclarator:
11690       case extendedDeclarator:
11691       case extendedDeclaratorEnd:
11692       {
11693          Identifier id = null;
11694          Specifier classSpec = null;
11695          if(decl.type == functionDeclarator)
11696          {
11697             id = GetDeclId(decl);
11698             if(id && id._class)
11699             {
11700                classSpec = id._class;
11701                id._class = null;
11702             }
11703          }
11704          if(decl.declarator)
11705             ProcessDeclarator(decl.declarator, isFunction);
11706          if(decl.type == functionDeclarator)
11707          {
11708             if(classSpec)
11709             {
11710                TypeName param
11711                {
11712                   qualifiers = MkListOne(classSpec);
11713                   declarator = null;
11714                };
11715                if(!decl.function.parameters)
11716                   decl.function.parameters = MkList();
11717                decl.function.parameters->Insert(null, param);
11718             }
11719             if(decl.function.parameters)
11720             {
11721                TypeName param;
11722
11723                for(param = decl.function.parameters->first; param; param = param.next)
11724                {
11725                   if(param.qualifiers)
11726                   {
11727                      Specifier spec;
11728                      for(spec = param.qualifiers->first; spec; spec = spec.next)
11729                      {
11730                         if(spec.type == baseSpecifier)
11731                         {
11732                            if(spec.specifier == TYPED_OBJECT)
11733                            {
11734                               Declarator d = param.declarator;
11735                               TypeName newParam
11736                               {
11737                                  qualifiers = MkListOne(MkSpecifier(VOID));
11738                                  declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11739                               };
11740                               if(!d || d.type != pointerDeclarator)
11741                                  newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11742
11743                               FreeList(param.qualifiers, FreeSpecifier);
11744
11745                               param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11746                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11747
11748                               DeclareStruct(curExternal, "ecere::com::Class", false, true);
11749
11750                               decl.function.parameters->Insert(param, newParam);
11751                               param = newParam;
11752                               break;
11753                            }
11754                            else if(spec.specifier == ANY_OBJECT)
11755                            {
11756                               Declarator d = param.declarator;
11757
11758                               FreeList(param.qualifiers, FreeSpecifier);
11759
11760                               param.qualifiers = MkListOne(MkSpecifier(VOID));
11761                               if(!d || d.type != pointerDeclarator)
11762                                  param.qualifiers->Insert(null, MkSpecifier(CONST));
11763                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11764                               break;
11765                            }
11766                            else if(spec.specifier == THISCLASS)
11767                            {
11768                               if(thisClass)
11769                               {
11770                                  spec.type = nameSpecifier;
11771                                  spec.name = ReplaceThisClass(thisClass);
11772                                  spec.symbol = FindClass(spec.name);
11773                                  ProcessSpecifier(spec, false, false);
11774                               }
11775                               break;
11776                            }
11777                         }
11778                         else if(spec.type == nameSpecifier)
11779                         {
11780                            ProcessSpecifier(spec, isFunction, true);
11781                         }
11782                         else if((spec.type == structSpecifier || spec.type == unionSpecifier) && !spec.definitions && spec.id && spec.id.string)
11783                         {
11784                            Declarator d = param.declarator;
11785                            if(!d || d.type != pointerDeclarator)
11786                               DeclareStruct(curExternal, spec.id.string, false, true);
11787                         }
11788                      }
11789                   }
11790
11791                   if(param.declarator)
11792                      ProcessDeclarator(param.declarator, false);
11793                }
11794             }
11795          }
11796          break;
11797       }
11798    }
11799 }
11800
11801 static void ProcessDeclaration(Declaration decl, bool warnClasses)
11802 {
11803    yylloc = decl.loc;
11804    switch(decl.type)
11805    {
11806       case initDeclaration:
11807       {
11808          bool declareStruct = false;
11809          /*
11810          lineNum = decl.pos.line;
11811          column = decl.pos.col;
11812          */
11813
11814          if(decl.declarators)
11815          {
11816             InitDeclarator d;
11817
11818             for(d = decl.declarators->first; d; d = d.next)
11819             {
11820                Type type, subType;
11821                ProcessDeclarator(d.declarator, false);
11822
11823                type = ProcessType(decl.specifiers, d.declarator);
11824
11825                if(d.initializer)
11826                {
11827                   ProcessInitializer(d.initializer, type);
11828
11829                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11830
11831                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11832                      d.initializer.exp.type == instanceExp)
11833                   {
11834                      if(type.kind == classType && type._class ==
11835                         d.initializer.exp.expType._class)
11836                      {
11837                         Instantiation inst = d.initializer.exp.instance;
11838                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11839
11840                         d.initializer.exp.instance = null;
11841                         if(decl.specifiers)
11842                            FreeList(decl.specifiers, FreeSpecifier);
11843                         FreeList(decl.declarators, FreeInitDeclarator);
11844
11845                         d = null;
11846
11847                         decl.type = instDeclaration;
11848                         decl.inst = inst;
11849                      }
11850                   }
11851                }
11852                for(subType = type; subType;)
11853                {
11854                   if(subType.kind == classType)
11855                   {
11856                      declareStruct = true;
11857                      break;
11858                   }
11859                   else if(subType.kind == pointerType)
11860                      break;
11861                   else if(subType.kind == arrayType)
11862                      subType = subType.arrayType;
11863                   else
11864                      break;
11865                }
11866
11867                FreeType(type);
11868                if(!d) break;
11869             }
11870          }
11871
11872          if(decl.specifiers)
11873          {
11874             Specifier s;
11875             for(s = decl.specifiers->first; s; s = s.next)
11876             {
11877                ProcessSpecifier(s, declareStruct, true);
11878             }
11879          }
11880          break;
11881       }
11882       case instDeclaration:
11883       {
11884          ProcessInstantiationType(decl.inst);
11885          break;
11886       }
11887       case structDeclaration:
11888       {
11889          Specifier spec;
11890          Declarator d;
11891          bool declareStruct = false;
11892
11893          if(decl.declarators)
11894          {
11895             for(d = decl.declarators->first; d; d = d.next)
11896             {
11897                Type type = ProcessType(decl.specifiers, d.declarator);
11898                Type subType;
11899                ProcessDeclarator(d, false);
11900                for(subType = type; subType;)
11901                {
11902                   if(subType.kind == classType)
11903                   {
11904                      declareStruct = true;
11905                      break;
11906                   }
11907                   else if(subType.kind == pointerType)
11908                      break;
11909                   else if(subType.kind == arrayType)
11910                      subType = subType.arrayType;
11911                   else
11912                      break;
11913                }
11914                FreeType(type);
11915             }
11916          }
11917          if(decl.specifiers)
11918          {
11919             for(spec = decl.specifiers->first; spec; spec = spec.next)
11920                ProcessSpecifier(spec, declareStruct, warnClasses);
11921          }
11922          break;
11923       }
11924    }
11925 }
11926
11927 static FunctionDefinition curFunction;
11928
11929 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11930 {
11931    char propName[1024], propNameM[1024];
11932    char getName[1024], setName[1024];
11933    OldList * args;
11934
11935    DeclareProperty(curExternal, prop, setName, getName);
11936
11937    // eInstance_FireWatchers(object, prop);
11938    strcpy(propName, "__ecereProp_");
11939    FullClassNameCat(propName, prop._class.fullName, false);
11940    strcat(propName, "_");
11941    FullClassNameCat(propName, prop.name, true);
11942
11943    strcpy(propNameM, "__ecerePropM_");
11944    FullClassNameCat(propNameM, prop._class.fullName, false);
11945    strcat(propNameM, "_");
11946    FullClassNameCat(propNameM, prop.name, true);
11947
11948    if(prop.isWatchable)
11949    {
11950       args = MkList();
11951       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11952       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11953       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11954
11955       args = MkList();
11956       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11957       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11958       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11959
11960       DeclareFunctionUtil(curExternal, "eInstance_FireWatchers");
11961    }
11962
11963    {
11964       args = MkList();
11965       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11966       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11967       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11968
11969       args = MkList();
11970       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11971       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11972       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11973
11974       DeclareFunctionUtil(curExternal, "eInstance_FireSelfWatchers");
11975    }
11976
11977    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11978       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11979       curFunction.propSet.fireWatchersDone = true;
11980 }
11981
11982 static void ProcessStatement(Statement stmt)
11983 {
11984    yylloc = stmt.loc;
11985    /*
11986    lineNum = stmt.pos.line;
11987    column = stmt.pos.col;
11988    */
11989    switch(stmt.type)
11990    {
11991       case labeledStmt:
11992          ProcessStatement(stmt.labeled.stmt);
11993          break;
11994       case caseStmt:
11995          // This expression should be constant...
11996          if(stmt.caseStmt.exp)
11997          {
11998             FreeType(stmt.caseStmt.exp.destType);
11999             stmt.caseStmt.exp.destType = curSwitchType;
12000             if(curSwitchType) curSwitchType.refCount++;
12001             ProcessExpressionType(stmt.caseStmt.exp);
12002             ComputeExpression(stmt.caseStmt.exp);
12003          }
12004          if(stmt.caseStmt.stmt)
12005             ProcessStatement(stmt.caseStmt.stmt);
12006          break;
12007       case compoundStmt:
12008       {
12009          if(stmt.compound.context)
12010          {
12011             Declaration decl;
12012             Statement s;
12013
12014             Statement prevCompound = curCompound;
12015             Context prevContext = curContext;
12016
12017             if(!stmt.compound.isSwitch)
12018                curCompound = stmt;
12019             curContext = stmt.compound.context;
12020
12021             if(stmt.compound.declarations)
12022             {
12023                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
12024                   ProcessDeclaration(decl, true);
12025             }
12026             if(stmt.compound.statements)
12027             {
12028                for(s = stmt.compound.statements->first; s; s = s.next)
12029                   ProcessStatement(s);
12030             }
12031
12032             curContext = prevContext;
12033             curCompound = prevCompound;
12034          }
12035          break;
12036       }
12037       case expressionStmt:
12038       {
12039          Expression exp;
12040          if(stmt.expressions)
12041          {
12042             for(exp = stmt.expressions->first; exp; exp = exp.next)
12043                ProcessExpressionType(exp);
12044          }
12045          break;
12046       }
12047       case ifStmt:
12048       {
12049          Expression exp;
12050
12051          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
12052          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
12053          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
12054          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
12055          {
12056             ProcessExpressionType(exp);
12057          }
12058          if(stmt.ifStmt.stmt)
12059             ProcessStatement(stmt.ifStmt.stmt);
12060          if(stmt.ifStmt.elseStmt)
12061             ProcessStatement(stmt.ifStmt.elseStmt);
12062          break;
12063       }
12064       case switchStmt:
12065       {
12066          Type oldSwitchType = curSwitchType;
12067          if(stmt.switchStmt.exp)
12068          {
12069             Expression exp;
12070             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
12071             {
12072                if(!exp.next)
12073                {
12074                   /*
12075                   Type destType
12076                   {
12077                      kind = intType;
12078                      refCount = 1;
12079                   };
12080                   e.exp.destType = destType;
12081                   */
12082
12083                   ProcessExpressionType(exp);
12084                }
12085                if(!exp.next)
12086                   curSwitchType = exp.expType;
12087             }
12088          }
12089          ProcessStatement(stmt.switchStmt.stmt);
12090          curSwitchType = oldSwitchType;
12091          break;
12092       }
12093       case whileStmt:
12094       {
12095          if(stmt.whileStmt.exp)
12096          {
12097             Expression exp;
12098
12099             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
12100             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
12101             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
12102             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
12103             {
12104                ProcessExpressionType(exp);
12105             }
12106          }
12107          if(stmt.whileStmt.stmt)
12108             ProcessStatement(stmt.whileStmt.stmt);
12109          break;
12110       }
12111       case doWhileStmt:
12112       {
12113          if(stmt.doWhile.exp)
12114          {
12115             Expression exp;
12116
12117             if(stmt.doWhile.exp->last)
12118             {
12119                FreeType(((Expression)stmt.doWhile.exp->last).destType);
12120                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
12121                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
12122             }
12123             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
12124             {
12125                ProcessExpressionType(exp);
12126             }
12127          }
12128          if(stmt.doWhile.stmt)
12129             ProcessStatement(stmt.doWhile.stmt);
12130          break;
12131       }
12132       case forStmt:
12133       {
12134          Expression exp;
12135          if(stmt.forStmt.init)
12136             ProcessStatement(stmt.forStmt.init);
12137
12138          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
12139          {
12140             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
12141             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
12142             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
12143          }
12144
12145          if(stmt.forStmt.check)
12146             ProcessStatement(stmt.forStmt.check);
12147          if(stmt.forStmt.increment)
12148          {
12149             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
12150                ProcessExpressionType(exp);
12151          }
12152
12153          if(stmt.forStmt.stmt)
12154             ProcessStatement(stmt.forStmt.stmt);
12155          break;
12156       }
12157       case forEachStmt:
12158       {
12159          Identifier id = stmt.forEachStmt.id;
12160          OldList * exp = stmt.forEachStmt.exp;
12161          OldList * filter = stmt.forEachStmt.filter;
12162          Statement block = stmt.forEachStmt.stmt;
12163          char iteratorType[1024];
12164          Type source;
12165          Expression e;
12166          bool isBuiltin = exp && exp->last &&
12167             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12168               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12169          Expression arrayExp;
12170          const char * typeString = null;
12171          int builtinCount = 0;
12172
12173          for(e = exp ? exp->first : null; e; e = e.next)
12174          {
12175             if(!e.next)
12176             {
12177                FreeType(e.destType);
12178                e.destType = ProcessTypeString("Container", false);
12179             }
12180             if(!isBuiltin || e.next)
12181                ProcessExpressionType(e);
12182          }
12183
12184          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12185          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12186             eClass_IsDerived(source._class.registered, containerClass)))
12187          {
12188             Class _class = source ? source._class.registered : null;
12189             Symbol symbol;
12190             Expression expIt = null;
12191             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12192             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12193             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12194             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12195
12196             if(inCompiler)
12197             {
12198                stmt.type = compoundStmt;
12199
12200                stmt.compound.context = Context { };
12201                stmt.compound.context.parent = curContext;
12202                curContext = stmt.compound.context;
12203             }
12204
12205             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12206             {
12207                Class mapClass = eSystem_FindClass(privateModule, "Map");
12208                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12209                isCustomAVLTree = true;
12210                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12211                   isAVLTree = true;
12212                else */if(eClass_IsDerived(source._class.registered, mapClass))
12213                   isMap = true;
12214             }
12215             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12216             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12217             {
12218                Class listClass = eSystem_FindClass(privateModule, "List");
12219                isLinkList = true;
12220                isList = eClass_IsDerived(source._class.registered, listClass);
12221             }
12222
12223             if(inCompiler && isArray)
12224             {
12225                Declarator decl;
12226                OldList * specs = MkList();
12227                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12228                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12229                stmt.compound.declarations = MkListOne(
12230                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12231                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12232                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12233                      MkInitializerAssignment(MkExpBrackets(exp))))));
12234             }
12235             else if(isBuiltin)
12236             {
12237                Type type = null;
12238                char typeStringBuf[1024];
12239
12240                // TODO: Merge this code?
12241                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12242                if(((Expression)exp->last).type == castExp)
12243                {
12244                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12245                   if(typeName)
12246                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12247                }
12248
12249                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12250                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12251                   arrayExp.destType._class.registered.templateArgs)
12252                {
12253                   Class templateClass = arrayExp.destType._class.registered;
12254                   typeString = templateClass.templateArgs[2].dataTypeString;
12255                }
12256                else if(arrayExp.list)
12257                {
12258                   // Guess type from expressions in the array
12259                   Expression e;
12260                   for(e = arrayExp.list->first; e; e = e.next)
12261                   {
12262                      ProcessExpressionType(e);
12263                      if(e.expType)
12264                      {
12265                         if(!type) { type = e.expType; type.refCount++; }
12266                         else
12267                         {
12268                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12269                            if(!MatchTypeExpression(e, type, null, false, true))
12270                            {
12271                               FreeType(type);
12272                               type = e.expType;
12273                               e.expType = null;
12274
12275                               e = arrayExp.list->first;
12276                               ProcessExpressionType(e);
12277                               if(e.expType)
12278                               {
12279                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12280                                  if(!MatchTypeExpression(e, type, null, false, true))
12281                                  {
12282                                     FreeType(e.expType);
12283                                     e.expType = null;
12284                                     FreeType(type);
12285                                     type = null;
12286                                     break;
12287                                  }
12288                               }
12289                            }
12290                         }
12291                         if(e.expType)
12292                         {
12293                            FreeType(e.expType);
12294                            e.expType = null;
12295                         }
12296                      }
12297                   }
12298                   if(type)
12299                   {
12300                      typeStringBuf[0] = '\0';
12301                      PrintType(type, typeStringBuf, false, true);
12302                      typeString = typeStringBuf;
12303                      FreeType(type);
12304                   }
12305                }
12306                if(typeString)
12307                {
12308                   if(inCompiler)
12309                   {
12310                      OldList * initializers = MkList();
12311                      Declarator decl;
12312                      OldList * specs = MkList();
12313                      if(arrayExp.list)
12314                      {
12315                         Expression e;
12316
12317                         builtinCount = arrayExp.list->count;
12318                         type = ProcessTypeString(typeString, false);
12319                         while((e = arrayExp.list->first))
12320                         {
12321                            arrayExp.list->Remove(e);
12322                            e.destType = type;
12323                            type.refCount++;
12324                            ProcessExpressionType(e);
12325                            if(inCompiler)
12326                               ListAdd(initializers, MkInitializerAssignment(e));
12327                         }
12328                         FreeType(type);
12329                         delete arrayExp.list;
12330                      }
12331                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12332
12333                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12334                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12335
12336                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12337                         PlugDeclarator(
12338                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12339                            ), MkInitializerList(initializers)))));
12340                      FreeList(exp, FreeExpression);
12341                   }
12342                   else if(arrayExp.list)
12343                   {
12344                      Expression e;
12345                      type = ProcessTypeString(typeString, false);
12346                      for(e = arrayExp.list->first; e; e = e.next)
12347                      {
12348                         e.destType = type;
12349                         type.refCount++;
12350                         ProcessExpressionType(e);
12351                      }
12352                      FreeType(type);
12353                   }
12354                }
12355                else
12356                {
12357                   arrayExp.expType = ProcessTypeString("Container", false);
12358                   Compiler_Error($"Couldn't determine type of array elements\n");
12359                }
12360
12361                /*
12362                Declarator decl;
12363                OldList * specs = MkList();
12364
12365                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12366                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12367                stmt.compound.declarations = MkListOne(
12368                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12369                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12370                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12371                      MkInitializerAssignment(MkExpBrackets(exp))))));
12372                */
12373             }
12374             else if(inCompiler && isLinkList && !isList)
12375             {
12376                Declarator decl;
12377                OldList * specs = MkList();
12378                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12379                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12380                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12381                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12382                      MkInitializerAssignment(MkExpBrackets(exp))))));
12383             }
12384             /*else if(isCustomAVLTree)
12385             {
12386                Declarator decl;
12387                OldList * specs = MkList();
12388                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12389                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12390                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12391                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12392                      MkInitializerAssignment(MkExpBrackets(exp))))));
12393             }*/
12394             else if(inCompiler && _class.templateArgs)
12395             {
12396                if(isMap)
12397                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12398                else
12399                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12400
12401                stmt.compound.declarations = MkListOne(
12402                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12403                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12404                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12405             }
12406             if(inCompiler)
12407             {
12408                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12409
12410                if(block)
12411                {
12412                   // Reparent sub-contexts in this statement
12413                   switch(block.type)
12414                   {
12415                      case compoundStmt:
12416                         if(block.compound.context)
12417                            block.compound.context.parent = stmt.compound.context;
12418                         break;
12419                      case ifStmt:
12420                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12421                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12422                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12423                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12424                         break;
12425                      case switchStmt:
12426                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12427                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12428                         break;
12429                      case whileStmt:
12430                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12431                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12432                         break;
12433                      case doWhileStmt:
12434                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12435                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12436                         break;
12437                      case forStmt:
12438                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12439                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12440                         break;
12441                      case forEachStmt:
12442                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12443                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12444                         break;
12445                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12446                      case labeledStmt:
12447                      case caseStmt
12448                      case expressionStmt:
12449                      case gotoStmt:
12450                      case continueStmt:
12451                      case breakStmt
12452                      case returnStmt:
12453                      case asmStmt:
12454                      case badDeclarationStmt:
12455                      case fireWatchersStmt:
12456                      case stopWatchingStmt:
12457                      case watchStmt:
12458                      */
12459                   }
12460                }
12461
12462                if(filter)
12463                {
12464                   block = MkIfStmt(filter, block, null);
12465                }
12466                if(isArray)
12467                {
12468                   stmt.compound.statements = MkListOne(MkForStmt(
12469                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12470                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12471                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12472                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12473                      block));
12474                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12475                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12476                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12477                }
12478                else if(isBuiltin)
12479                {
12480                   char count[128];
12481                   //OldList * specs = MkList();
12482                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12483
12484                   sprintf(count, "%d", builtinCount);
12485
12486                   stmt.compound.statements = MkListOne(MkForStmt(
12487                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12488                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12489                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12490                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12491                      block));
12492
12493                   /*
12494                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12495                   stmt.compound.statements = MkListOne(MkForStmt(
12496                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12497                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12498                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12499                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12500                      block));
12501                  */
12502                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12503                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12504                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12505                }
12506                else if(isLinkList && !isList)
12507                {
12508                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12509                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12510                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12511                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12512                   {
12513                      stmt.compound.statements = MkListOne(MkForStmt(
12514                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12515                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12516                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12517                         block));
12518                   }
12519                   else
12520                   {
12521                      OldList * specs = MkList();
12522                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12523                      stmt.compound.statements = MkListOne(MkForStmt(
12524                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12525                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12526                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12527                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12528                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12529                         block));
12530                   }
12531                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12532                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12533                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12534                }
12535                /*else if(isCustomAVLTree)
12536                {
12537                   stmt.compound.statements = MkListOne(MkForStmt(
12538                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12539                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12540                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12541                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12542                      block));
12543
12544                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12545                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12546                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12547                }*/
12548                else
12549                {
12550                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12551                      MkIdentifier("Next")), null)), block));
12552                }
12553                ProcessExpressionType(expIt);
12554                if(stmt.compound.declarations->first)
12555                   ProcessDeclaration(stmt.compound.declarations->first, true);
12556
12557                if(symbol)
12558                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12559
12560                ProcessStatement(stmt);
12561             }
12562             else
12563                ProcessStatement(stmt.forEachStmt.stmt);
12564             if(inCompiler)
12565                curContext = stmt.compound.context.parent;
12566             break;
12567          }
12568          else
12569          {
12570             Compiler_Error($"Expression is not a container\n");
12571          }
12572          break;
12573       }
12574       case gotoStmt:
12575          break;
12576       case continueStmt:
12577          break;
12578       case breakStmt:
12579          break;
12580       case returnStmt:
12581       {
12582          Expression exp;
12583          if(stmt.expressions)
12584          {
12585             for(exp = stmt.expressions->first; exp; exp = exp.next)
12586             {
12587                if(!exp.next)
12588                {
12589                   if(curFunction && !curFunction.type)
12590                      curFunction.type = ProcessType(
12591                         curFunction.specifiers, curFunction.declarator);
12592                   FreeType(exp.destType);
12593                   // TODO: current property if not compiling
12594                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12595                   if(exp.destType) exp.destType.refCount++;
12596                }
12597                ProcessExpressionType(exp);
12598             }
12599          }
12600          break;
12601       }
12602       case badDeclarationStmt:
12603       {
12604          ProcessDeclaration(stmt.decl, true);
12605          break;
12606       }
12607       case asmStmt:
12608       {
12609          AsmField field;
12610          if(stmt.asmStmt.inputFields)
12611          {
12612             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12613                if(field.expression)
12614                   ProcessExpressionType(field.expression);
12615          }
12616          if(stmt.asmStmt.outputFields)
12617          {
12618             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12619                if(field.expression)
12620                   ProcessExpressionType(field.expression);
12621          }
12622          if(stmt.asmStmt.clobberedFields)
12623          {
12624             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12625             {
12626                if(field.expression)
12627                   ProcessExpressionType(field.expression);
12628             }
12629          }
12630          break;
12631       }
12632       case watchStmt:
12633       {
12634          PropertyWatch propWatch;
12635          OldList * watches = stmt._watch.watches;
12636          Expression object = stmt._watch.object;
12637          Expression watcher = stmt._watch.watcher;
12638          if(watcher)
12639             ProcessExpressionType(watcher);
12640          if(object)
12641             ProcessExpressionType(object);
12642
12643          if(inCompiler)
12644          {
12645             if(watcher || thisClass)
12646             {
12647                External external = curExternal;
12648                Context context = curContext;
12649
12650                stmt.type = expressionStmt;
12651                stmt.expressions = MkList();
12652
12653                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12654                {
12655                   ClassFunction func;
12656                   char watcherName[1024];
12657                   Class watcherClass = watcher ?
12658                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12659                   External createdExternal;
12660
12661                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12662                   if(propWatch.deleteWatch)
12663                      strcat(watcherName, "_delete");
12664                   else
12665                   {
12666                      Identifier propID;
12667                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12668                      {
12669                         strcat(watcherName, "_");
12670                         strcat(watcherName, propID.string);
12671                      }
12672                   }
12673
12674                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12675                   {
12676                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12677                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12678                      ProcessClassFunctionBody(func, propWatch.compound);
12679                      propWatch.compound = null;
12680
12681                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12682
12683                      FreeClassFunction(func);
12684
12685                      curExternal = createdExternal;
12686                      ProcessFunction(createdExternal.function);
12687
12688                      if(propWatch.deleteWatch)
12689                      {
12690                         OldList * args = MkList();
12691                         ListAdd(args, CopyExpression(object));
12692                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12693                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12694                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12695                      }
12696                      else
12697                      {
12698                         Class _class = object.expType._class.registered;
12699                         Identifier propID;
12700
12701                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12702                         {
12703                            char propName[1024];
12704                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12705                            if(prop)
12706                            {
12707                               char getName[1024], setName[1024];
12708                               OldList * args = MkList();
12709
12710                               DeclareProperty(createdExternal, prop, setName, getName);
12711
12712                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12713                               strcpy(propName, "__ecereProp_");
12714                               FullClassNameCat(propName, prop._class.fullName, false);
12715                               strcat(propName, "_");
12716                               FullClassNameCat(propName, prop.name, true);
12717
12718                               ListAdd(args, CopyExpression(object));
12719                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12720                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12721                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12722
12723                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12724
12725                               external.CreateUniqueEdge(createdExternal, true);
12726                            }
12727                            else
12728                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12729                         }
12730                      }
12731                   }
12732                   else
12733                      Compiler_Error($"Invalid watched object\n");
12734                }
12735
12736                curExternal = external;
12737                curContext = context;
12738
12739                if(watcher)
12740                   FreeExpression(watcher);
12741                if(object)
12742                   FreeExpression(object);
12743                FreeList(watches, FreePropertyWatch);
12744             }
12745             else
12746                Compiler_Error($"No observer specified and not inside a class\n");
12747          }
12748          else
12749          {
12750             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12751             {
12752                ProcessStatement(propWatch.compound);
12753             }
12754
12755          }
12756          break;
12757       }
12758       case fireWatchersStmt:
12759       {
12760          OldList * watches = stmt._watch.watches;
12761          Expression object = stmt._watch.object;
12762          Class _class;
12763          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12764          // printf("%X\n", watches);
12765          // printf("%X\n", stmt._watch.watches);
12766          if(object)
12767             ProcessExpressionType(object);
12768
12769          if(inCompiler)
12770          {
12771             _class = object ?
12772                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12773
12774             if(_class)
12775             {
12776                Identifier propID;
12777
12778                stmt.type = expressionStmt;
12779                stmt.expressions = MkList();
12780
12781                // Check if we're inside a property set
12782                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12783                {
12784                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12785                }
12786                else if(!watches)
12787                {
12788                   //Compiler_Error($"No property specified and not inside a property set\n");
12789                }
12790                if(watches)
12791                {
12792                   for(propID = watches->first; propID; propID = propID.next)
12793                   {
12794                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12795                      if(prop)
12796                      {
12797                         CreateFireWatcher(prop, object, stmt);
12798                      }
12799                      else
12800                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12801                   }
12802                }
12803                else
12804                {
12805                   // Fire all properties!
12806                   Property prop;
12807                   Class base;
12808                   for(base = _class; base; base = base.base)
12809                   {
12810                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12811                      {
12812                         if(prop.isProperty && prop.isWatchable)
12813                         {
12814                            CreateFireWatcher(prop, object, stmt);
12815                         }
12816                      }
12817                   }
12818                }
12819
12820                if(object)
12821                   FreeExpression(object);
12822                FreeList(watches, FreeIdentifier);
12823             }
12824             else
12825                Compiler_Error($"Invalid object specified and not inside a class\n");
12826          }
12827          break;
12828       }
12829       case stopWatchingStmt:
12830       {
12831          OldList * watches = stmt._watch.watches;
12832          Expression object = stmt._watch.object;
12833          Expression watcher = stmt._watch.watcher;
12834          Class _class;
12835          if(object)
12836             ProcessExpressionType(object);
12837          if(watcher)
12838             ProcessExpressionType(watcher);
12839          if(inCompiler)
12840          {
12841             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12842
12843             if(watcher || thisClass)
12844             {
12845                if(_class)
12846                {
12847                   Identifier propID;
12848
12849                   stmt.type = expressionStmt;
12850                   stmt.expressions = MkList();
12851
12852                   if(!watches)
12853                   {
12854                      OldList * args;
12855                      // eInstance_StopWatching(object, null, watcher);
12856                      args = MkList();
12857                      ListAdd(args, CopyExpression(object));
12858                      ListAdd(args, MkExpConstant("0"));
12859                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12860                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12861                   }
12862                   else
12863                   {
12864                      for(propID = watches->first; propID; propID = propID.next)
12865                      {
12866                         char propName[1024];
12867                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12868                         if(prop)
12869                         {
12870                            char getName[1024], setName[1024];
12871                            OldList * args = MkList();
12872
12873                            DeclareProperty(curExternal, prop, setName, getName);
12874
12875                            // eInstance_StopWatching(object, prop, watcher);
12876                            strcpy(propName, "__ecereProp_");
12877                            FullClassNameCat(propName, prop._class.fullName, false);
12878                            strcat(propName, "_");
12879                            FullClassNameCat(propName, prop.name, true);
12880
12881                            ListAdd(args, CopyExpression(object));
12882                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12883                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12884                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12885                         }
12886                         else
12887                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12888                      }
12889                   }
12890
12891                   if(object)
12892                      FreeExpression(object);
12893                   if(watcher)
12894                      FreeExpression(watcher);
12895                   FreeList(watches, FreeIdentifier);
12896                }
12897                else
12898                   Compiler_Error($"Invalid object specified and not inside a class\n");
12899             }
12900             else
12901                Compiler_Error($"No observer specified and not inside a class\n");
12902          }
12903          break;
12904       }
12905    }
12906 }
12907
12908 static void ProcessFunction(FunctionDefinition function)
12909 {
12910    Identifier id = GetDeclId(function.declarator);
12911    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12912    Type type = symbol ? symbol.type : null;
12913    Class oldThisClass = thisClass;
12914    Context oldTopContext = topContext;
12915
12916    yylloc = function.loc;
12917    // Process thisClass
12918
12919    if(type && type.thisClass)
12920    {
12921       Symbol classSym = type.thisClass;
12922       Class _class = type.thisClass.registered;
12923       char className[1024];
12924       char structName[1024];
12925       Declarator funcDecl;
12926       Symbol thisSymbol;
12927
12928       bool typedObject = false;
12929
12930       if(_class && !_class.base)
12931       {
12932          _class = currentClass;
12933          if(_class && !_class.symbol)
12934             _class.symbol = FindClass(_class.fullName);
12935          classSym = _class ? _class.symbol : null;
12936          typedObject = true;
12937       }
12938
12939       thisClass = _class;
12940
12941       if(inCompiler && _class)
12942       {
12943          if(type.kind == functionType)
12944          {
12945             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12946             {
12947                //TypeName param = symbol.type.params.first;
12948                Type param = symbol.type.params.first;
12949                symbol.type.params.Remove(param);
12950                //FreeTypeName(param);
12951                FreeType(param);
12952             }
12953             if(type.classObjectType != classPointer)
12954             {
12955                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12956                symbol.type.staticMethod = true;
12957                symbol.type.thisClass = null;
12958
12959                // HIGH DANGER: VERIFYING THIS...
12960                symbol.type.extraParam = false;
12961             }
12962          }
12963
12964          strcpy(className, "__ecereClass_");
12965          FullClassNameCat(className, _class.fullName, true);
12966
12967          structName[0] = 0;
12968          FullClassNameCat(structName, _class.fullName, false);
12969
12970          // [class] this
12971          funcDecl = GetFuncDecl(function.declarator);
12972          if(funcDecl)
12973          {
12974             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12975             {
12976                TypeName param = funcDecl.function.parameters->first;
12977                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12978                {
12979                   funcDecl.function.parameters->Remove(param);
12980                   FreeTypeName(param);
12981                }
12982             }
12983
12984             if(!function.propertyNoThis)
12985             {
12986                TypeName thisParam = null;
12987
12988                if(type.classObjectType != classPointer)
12989                {
12990                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12991                   if(!funcDecl.function.parameters)
12992                      funcDecl.function.parameters = MkList();
12993                   funcDecl.function.parameters->Insert(null, thisParam);
12994                }
12995
12996                if(typedObject)
12997                {
12998                   if(type.classObjectType != classPointer)
12999                   {
13000                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
13001                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
13002                   }
13003
13004                   thisParam = TypeName
13005                   {
13006                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
13007                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
13008                   };
13009                   DeclareStruct(curExternal, "ecere::com::Class", false, true);
13010                   funcDecl.function.parameters->Insert(null, thisParam);
13011                }
13012             }
13013          }
13014
13015          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13016          {
13017             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13018             funcDecl = GetFuncDecl(initDecl.declarator);
13019             if(funcDecl)
13020             {
13021                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
13022                {
13023                   TypeName param = funcDecl.function.parameters->first;
13024                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
13025                   {
13026                      funcDecl.function.parameters->Remove(param);
13027                      FreeTypeName(param);
13028                   }
13029                }
13030
13031                if(type.classObjectType != classPointer)
13032                {
13033                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
13034                   {
13035                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
13036
13037                      if(!funcDecl.function.parameters)
13038                         funcDecl.function.parameters = MkList();
13039                      funcDecl.function.parameters->Insert(null, thisParam);
13040                   }
13041                }
13042             }
13043          }
13044       }
13045
13046       // Add this to the context
13047       if(function.body)
13048       {
13049          if(type.classObjectType != classPointer)
13050          {
13051             thisSymbol = Symbol
13052             {
13053                string = CopyString("this");
13054                type = classSym ? MkClassType(classSym.string) : null;
13055             };
13056             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
13057
13058             if(typedObject && thisSymbol.type)
13059             {
13060                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
13061                thisSymbol.type.byReference = type.byReference;
13062                thisSymbol.type.typedByReference = type.byReference;
13063             }
13064          }
13065       }
13066
13067       // Pointer to class data
13068       if(inCompiler && _class && _class.type == normalClass && type.classObjectType != classPointer)
13069       {
13070          DataMember member = null;
13071          {
13072             Class base;
13073             for(base = _class; base && base.type != systemClass; base = base.next)
13074             {
13075                for(member = base.membersAndProperties.first; member; member = member.next)
13076                   if(!member.isProperty)
13077                      break;
13078                if(member)
13079                   break;
13080             }
13081          }
13082          for(member = _class.membersAndProperties.first; member; member = member.next)
13083             if(!member.isProperty)
13084                break;
13085          if(member)
13086          {
13087             char pointerName[1024];
13088
13089             Declaration decl;
13090             Initializer initializer;
13091             Expression exp, bytePtr;
13092
13093             strcpy(pointerName, "__ecerePointer_");
13094             FullClassNameCat(pointerName, _class.fullName, false);
13095             {
13096                char className[1024];
13097                strcpy(className, "__ecereClass_");
13098                FullClassNameCat(className, classSym.string, true);
13099
13100                DeclareClass(curExternal, classSym, className);
13101             }
13102
13103             // ((byte *) this)
13104             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
13105
13106             if(_class.fixed)
13107             {
13108                Expression e;
13109                if(_class.offset && _class.offset == (_class.base.type == noHeadClass ? _class.base.memberOffset : _class.base.structSize))
13110                {
13111                   e = MkExpClassSize(MkSpecifierName(_class.base.fullName));
13112                   ProcessExpressionType(e);
13113                }
13114                else
13115                {
13116                   char string[256];
13117                   sprintf(string, "%d", _class.offset);  // Need Bootstrap Fix
13118                   e = MkExpConstant(string);
13119                }
13120                exp = QBrackets(MkExpOp(bytePtr, '+', e));
13121             }
13122             else
13123             {
13124                // ([bytePtr] + [className]->offset)
13125                exp = QBrackets(MkExpOp(bytePtr, '+',
13126                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
13127             }
13128
13129             // (this ? [exp] : 0)
13130             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
13131             exp.expType = Type
13132             {
13133                refCount = 1;
13134                kind = pointerType;
13135                type = Type { refCount = 1, kind = voidType };
13136             };
13137
13138             if(function.body)
13139             {
13140                yylloc = function.body.loc;
13141                // ([structName] *) [exp]
13142                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13143                initializer = MkInitializerAssignment(
13144                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13145
13146                // [structName] * [pointerName] = [initializer];
13147                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13148
13149                {
13150                   Context prevContext = curContext;
13151                   OldList * list;
13152                   curContext = function.body.compound.context;
13153
13154                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13155                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13156                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13157
13158                   curContext = prevContext;
13159                }
13160
13161                // WHY?
13162                decl.symbol = null;
13163
13164                if(!function.body.compound.declarations)
13165                   function.body.compound.declarations = MkList();
13166                function.body.compound.declarations->Insert(null, decl);
13167             }
13168          }
13169       }
13170
13171
13172       // Loop through the function and replace undeclared identifiers
13173       // which are a member of the class (methods, properties or data)
13174       // by "this.[member]"
13175    }
13176    else
13177       thisClass = null;
13178
13179    if(id)
13180    {
13181       FreeSpecifier(id._class);
13182       id._class = null;
13183
13184       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13185       {
13186          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13187          id = GetDeclId(initDecl.declarator);
13188
13189          FreeSpecifier(id._class);
13190          id._class = null;
13191       }
13192    }
13193    if(function.body)
13194       topContext = function.body.compound.context;
13195    {
13196       FunctionDefinition oldFunction = curFunction;
13197       curFunction = function;
13198       if(function.body)
13199          ProcessStatement(function.body);
13200
13201       // If this is a property set and no firewatchers has been done yet, add one here
13202       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13203       {
13204          Statement prevCompound = curCompound;
13205          Context prevContext = curContext;
13206
13207          Statement fireWatchers = MkFireWatchersStmt(null, null);
13208          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13209          ListAdd(function.body.compound.statements, fireWatchers);
13210
13211          curCompound = function.body;
13212          curContext = function.body.compound.context;
13213
13214          ProcessStatement(fireWatchers);
13215
13216          curContext = prevContext;
13217          curCompound = prevCompound;
13218
13219       }
13220
13221       curFunction = oldFunction;
13222    }
13223
13224    if(function.declarator)
13225    {
13226       ProcessDeclarator(function.declarator, true);
13227    }
13228
13229    topContext = oldTopContext;
13230    thisClass = oldThisClass;
13231 }
13232
13233 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13234 static void ProcessClass(OldList definitions, Symbol symbol)
13235 {
13236    ClassDef def;
13237    External external = curExternal;
13238    Class regClass = symbol ? symbol.registered : null;
13239
13240    // Process all functions
13241    for(def = definitions.first; def; def = def.next)
13242    {
13243       if(def.type == functionClassDef)
13244       {
13245          if(def.function.declarator)
13246             curExternal = def.function.declarator.symbol.pointerExternal;
13247          else
13248             curExternal = external;
13249
13250          ProcessFunction((FunctionDefinition)def.function);
13251       }
13252       else if(def.type == declarationClassDef)
13253       {
13254          if(def.decl.type == instDeclaration)
13255          {
13256             thisClass = regClass;
13257             ProcessInstantiationType(def.decl.inst);
13258             thisClass = null;
13259          }
13260          // Testing this
13261          else
13262          {
13263             Class backThisClass = thisClass;
13264             if(regClass) thisClass = regClass;
13265             ProcessDeclaration(def.decl, symbol ? true : false);
13266             thisClass = backThisClass;
13267          }
13268       }
13269       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13270       {
13271          MemberInit defProperty;
13272
13273          // Add this to the context
13274          Symbol thisSymbol = Symbol
13275          {
13276             string = CopyString("this");
13277             type = regClass ? MkClassType(regClass.fullName) : null;
13278          };
13279          globalContext.symbols.Add((BTNode)thisSymbol);
13280
13281          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13282          {
13283             thisClass = regClass;
13284             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13285             thisClass = null;
13286          }
13287
13288          globalContext.symbols.Remove((BTNode)thisSymbol);
13289          FreeSymbol(thisSymbol);
13290       }
13291       else if(def.type == propertyClassDef && def.propertyDef)
13292       {
13293          PropertyDef prop = def.propertyDef;
13294
13295          // Add this to the context
13296          thisClass = regClass;
13297          if(prop.setStmt)
13298          {
13299             if(regClass)
13300             {
13301                Symbol thisSymbol
13302                {
13303                   string = CopyString("this");
13304                   type = MkClassType(regClass.fullName);
13305                };
13306                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13307             }
13308
13309             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13310             ProcessStatement(prop.setStmt);
13311          }
13312          if(prop.getStmt)
13313          {
13314             if(regClass)
13315             {
13316                Symbol thisSymbol
13317                {
13318                   string = CopyString("this");
13319                   type = MkClassType(regClass.fullName);
13320                };
13321                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13322             }
13323
13324             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13325             ProcessStatement(prop.getStmt);
13326          }
13327          if(prop.issetStmt)
13328          {
13329             if(regClass)
13330             {
13331                Symbol thisSymbol
13332                {
13333                   string = CopyString("this");
13334                   type = MkClassType(regClass.fullName);
13335                };
13336                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13337             }
13338
13339             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13340             ProcessStatement(prop.issetStmt);
13341          }
13342
13343          thisClass = null;
13344       }
13345       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13346       {
13347          PropertyWatch propertyWatch = def.propertyWatch;
13348
13349          thisClass = regClass;
13350          if(propertyWatch.compound)
13351          {
13352             Symbol thisSymbol
13353             {
13354                string = CopyString("this");
13355                type = regClass ? MkClassType(regClass.fullName) : null;
13356             };
13357
13358             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13359
13360             curExternal = null;
13361             ProcessStatement(propertyWatch.compound);
13362          }
13363          thisClass = null;
13364       }
13365    }
13366 }
13367
13368 void DeclareFunctionUtil(External neededBy, const String s)
13369 {
13370    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13371    if(function)
13372    {
13373       char name[1024];
13374       name[0] = 0;
13375       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13376          strcpy(name, "__ecereFunction_");
13377       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13378       DeclareFunction(neededBy, function, name);
13379    }
13380    else if(neededBy)
13381       FindSymbol(s, globalContext, globalContext, false, false);
13382 }
13383
13384 bool reachedPass15;
13385
13386 void ComputeDataTypes()
13387 {
13388    External external;
13389
13390    currentClass = null;
13391
13392    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13393
13394    DeclareStruct(null, "ecere::com::Class", false, true);
13395    DeclareStruct(null, "ecere::com::Instance", false, true);
13396    DeclareStruct(null, "ecere::com::Property", false, true);
13397    DeclareStruct(null, "ecere::com::DataMember", false, true);
13398    DeclareStruct(null, "ecere::com::Method", false, true);
13399    DeclareStruct(null, "ecere::com::SerialBuffer", false, true);
13400    DeclareStruct(null, "ecere::com::ClassTemplateArgument", false, true);
13401
13402    DeclareFunctionUtil(null, "eSystem_New");
13403    DeclareFunctionUtil(null, "eSystem_New0");
13404    DeclareFunctionUtil(null, "eSystem_Renew");
13405    DeclareFunctionUtil(null, "eSystem_Renew0");
13406    DeclareFunctionUtil(null, "eSystem_Delete");
13407    DeclareFunctionUtil(null, "eClass_GetProperty");
13408    DeclareFunctionUtil(null, "eClass_SetProperty");
13409    DeclareFunctionUtil(null, "eInstance_FireSelfWatchers");
13410    DeclareFunctionUtil(null, "eInstance_SetMethod");
13411    DeclareFunctionUtil(null, "eInstance_IncRef");
13412    DeclareFunctionUtil(null, "eInstance_StopWatching");
13413    DeclareFunctionUtil(null, "eInstance_Watch");
13414    DeclareFunctionUtil(null, "eInstance_FireWatchers");
13415    reachedPass15 = true;
13416
13417    for(external = ast->first; external; external = external.next)
13418    {
13419       afterExternal = curExternal = external;
13420       if(external.type == functionExternal)
13421       {
13422          if(memoryGuard)
13423          {
13424             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13425             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13426          }
13427
13428          currentClass = external.function._class;
13429          ProcessFunction(external.function);
13430       }
13431       // There shouldn't be any _class member access here anyways...
13432       else if(external.type == declarationExternal)
13433       {
13434          if(memoryGuard && external.declaration && external.declaration.type == instDeclaration)
13435          {
13436             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13437             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13438          }
13439
13440          currentClass = null;
13441          if(external.declaration)
13442             ProcessDeclaration(external.declaration, true);
13443       }
13444       else if(external.type == classExternal)
13445       {
13446          ClassDefinition _class = external._class;
13447          currentClass = external.symbol.registered;
13448          if(memoryGuard)
13449          {
13450             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13451             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13452          }
13453          if(_class.definitions)
13454          {
13455             ProcessClass(_class.definitions, _class.symbol);
13456          }
13457          if(inCompiler)
13458          {
13459             // Free class data...
13460             ast->Remove(external);
13461             delete external;
13462          }
13463       }
13464       else if(external.type == nameSpaceExternal)
13465       {
13466          thisNameSpace = external.id.string;
13467       }
13468    }
13469    currentClass = null;
13470    thisNameSpace = null;
13471    curExternal = null;
13472 }