b39a9bb51db324b785433b5a75edfb6d4e721883
[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 = null;
7834             bool findInGlobal = false;
7835             if(!topContext.parent && exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == enumClass)
7836                findInGlobal = true;  // In global context, look at enum values first
7837             else
7838                symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7839
7840             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7841             if(!symbol/* && exp.destType*/)
7842             {
7843                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7844                   break;
7845                else
7846                {
7847                   if(thisClass)
7848                   {
7849                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7850                      if(exp.type != identifierExp)
7851                      {
7852                         ProcessExpressionType(exp);
7853                         break;
7854                      }
7855                   }
7856                   // Static methods called from inside the _class
7857                   else if(currentClass && !id._class)
7858                   {
7859                      if(ResolveIdWithClass(exp, currentClass, true))
7860                         break;
7861                   }
7862                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7863                }
7864             }
7865             if(findInGlobal)
7866                symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
7867
7868             // If we manage to resolve this symbol
7869             if(symbol)
7870             {
7871                Type type = symbol.type;
7872                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7873
7874                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7875                {
7876                   Context context = SetupTemplatesContext(_class);
7877                   type = ReplaceThisClassType(_class);
7878                   FinishTemplatesContext(context);
7879                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7880                }
7881
7882                FreeSpecifier(id._class);
7883                id._class = null;
7884                delete id.string;
7885                id.string = CopyString(symbol.string);
7886
7887                id.classSym = null;
7888                exp.expType = type;
7889                if(type)
7890                   type.refCount++;
7891
7892                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7893                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7894                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7895                   // Add missing cases here... enum Classes...
7896                   exp.isConstant = true;
7897
7898                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7899                if(symbol.isParam || !strcmp(id.string, "this"))
7900                {
7901                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7902                      exp.byReference = true;
7903
7904                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7905                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7906                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7907                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7908                   {
7909                      Identifier id = exp.identifier;
7910                      exp.type = bracketsExp;
7911                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7912                   }*/
7913                }
7914
7915                if(symbol.isIterator)
7916                {
7917                   if(symbol.isIterator == 3)
7918                   {
7919                      exp.type = bracketsExp;
7920                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7921                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7922                      exp.expType = null;
7923                      ProcessExpressionType(exp);
7924                   }
7925                   else if(symbol.isIterator != 4)
7926                   {
7927                      exp.type = memberExp;
7928                      exp.member.exp = MkExpIdentifier(exp.identifier);
7929                      exp.member.exp.expType = exp.expType;
7930                      /*if(symbol.isIterator == 6)
7931                         exp.member.member = MkIdentifier("key");
7932                      else*/
7933                         exp.member.member = MkIdentifier("data");
7934                      exp.expType = null;
7935                      ProcessExpressionType(exp);
7936                   }
7937                }
7938                break;
7939             }
7940             else
7941             {
7942                DefinedExpression definedExp = null;
7943                if(thisNameSpace && !(id._class && !id._class.name))
7944                {
7945                   char name[1024];
7946                   strcpy(name, thisNameSpace);
7947                   strcat(name, "::");
7948                   strcat(name, id.string);
7949                   definedExp = eSystem_FindDefine(privateModule, name);
7950                }
7951                if(!definedExp)
7952                   definedExp = eSystem_FindDefine(privateModule, id.string);
7953                if(definedExp)
7954                {
7955                   int c;
7956                   for(c = 0; c<definedExpStackPos; c++)
7957                      if(definedExpStack[c] == definedExp)
7958                         break;
7959                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7960                   {
7961                      Location backupYylloc = yylloc;
7962                      File backInput = fileInput;
7963                      definedExpStack[definedExpStackPos++] = definedExp;
7964
7965                      fileInput = TempFile { };
7966                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7967                      fileInput.Seek(0, start);
7968
7969                      echoOn = false;
7970                      parsedExpression = null;
7971                      resetScanner();
7972                      expression_yyparse();
7973                      delete fileInput;
7974                      if(backInput)
7975                         fileInput = backInput;
7976
7977                      yylloc = backupYylloc;
7978
7979                      if(parsedExpression)
7980                      {
7981                         FreeIdentifier(id);
7982                         exp.type = bracketsExp;
7983                         exp.list = MkListOne(parsedExpression);
7984                         ApplyLocation(parsedExpression, yylloc);
7985                         ProcessExpressionType(exp);
7986                         definedExpStackPos--;
7987                         return;
7988                      }
7989                      definedExpStackPos--;
7990                   }
7991                   else
7992                   {
7993                      if(inCompiler)
7994                      {
7995                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7996                      }
7997                   }
7998                }
7999                else
8000                {
8001                   GlobalData data = null;
8002                   if(thisNameSpace && !(id._class && !id._class.name))
8003                   {
8004                      char name[1024];
8005                      strcpy(name, thisNameSpace);
8006                      strcat(name, "::");
8007                      strcat(name, id.string);
8008                      data = FindGlobalData(name);
8009                   }
8010                   if(!data)
8011                      data = FindGlobalData(id.string);
8012                   if(data)
8013                   {
8014                      DeclareGlobalData(curExternal, data);
8015                      exp.expType = data.dataType;
8016                      if(data.dataType) data.dataType.refCount++;
8017
8018                      delete id.string;
8019                      id.string = CopyString(data.fullName);
8020                      FreeSpecifier(id._class);
8021                      id._class = null;
8022
8023                      break;
8024                   }
8025                   else
8026                   {
8027                      GlobalFunction function = null;
8028                      if(thisNameSpace && !(id._class && !id._class.name))
8029                      {
8030                         char name[1024];
8031                         strcpy(name, thisNameSpace);
8032                         strcat(name, "::");
8033                         strcat(name, id.string);
8034                         function = eSystem_FindFunction(privateModule, name);
8035                      }
8036                      if(!function)
8037                         function = eSystem_FindFunction(privateModule, id.string);
8038                      if(function)
8039                      {
8040                         char name[1024];
8041                         delete id.string;
8042                         id.string = CopyString(function.name);
8043                         name[0] = 0;
8044
8045                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8046                            strcpy(name, "__ecereFunction_");
8047                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8048                         if(DeclareFunction(curExternal, function, name))
8049                         {
8050                            delete id.string;
8051                            id.string = CopyString(name);
8052                         }
8053                         exp.expType = function.dataType;
8054                         if(function.dataType) function.dataType.refCount++;
8055
8056                         FreeSpecifier(id._class);
8057                         id._class = null;
8058
8059                         break;
8060                      }
8061                   }
8062                }
8063             }
8064          }
8065          unresolved = true;
8066          break;
8067       }
8068       case instanceExp:
8069       {
8070          // Class _class;
8071          // Symbol classSym;
8072
8073          if(!exp.instance._class)
8074          {
8075             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8076             {
8077                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8078             }
8079          }
8080
8081          //classSym = FindClass(exp.instance._class.fullName);
8082          //_class = classSym ? classSym.registered : null;
8083
8084          ProcessInstantiationType(exp.instance);
8085
8086          exp.isConstant = exp.instance.isConstant;
8087
8088          /*
8089          if(_class.type == unitClass && _class.base.type != systemClass)
8090          {
8091             {
8092                Type destType = exp.destType;
8093
8094                exp.destType = MkClassType(_class.base.fullName);
8095                exp.expType = MkClassType(_class.fullName);
8096                CheckExpressionType(exp, exp.destType, true);
8097
8098                exp.destType = destType;
8099             }
8100             exp.expType = MkClassType(_class.fullName);
8101          }
8102          else*/
8103          if(exp.instance._class)
8104          {
8105             exp.expType = MkClassType(exp.instance._class.name);
8106             /*if(exp.expType._class && exp.expType._class.registered &&
8107                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8108                exp.expType.byReference = true;*/
8109          }
8110          break;
8111       }
8112       case constantExp:
8113       {
8114          if(!exp.expType)
8115          {
8116             char * constant = exp.constant;
8117             Type type
8118             {
8119                refCount = 1;
8120                constant = true;
8121             };
8122             exp.expType = type;
8123
8124             if(constant[0] == '\'')
8125             {
8126                if((int)((byte *)constant)[1] > 127)
8127                {
8128                   int nb;
8129                   unichar ch = UTF8GetChar(constant + 1, &nb);
8130                   if(nb < 2) ch = constant[1];
8131                   delete constant;
8132                   exp.constant = PrintUInt(ch);
8133                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8134                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8135                   type._class = FindClass("unichar");
8136
8137                   type.isSigned = false;
8138                }
8139                else
8140                {
8141                   type.kind = charType;
8142                   type.isSigned = true;
8143                }
8144             }
8145             else
8146             {
8147                char * dot = strchr(constant, '.');
8148                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8149                char * exponent;
8150                if(isHex)
8151                {
8152                   exponent = strchr(constant, 'p');
8153                   if(!exponent) exponent = strchr(constant, 'P');
8154                }
8155                else
8156                {
8157                   exponent = strchr(constant, 'e');
8158                   if(!exponent) exponent = strchr(constant, 'E');
8159                }
8160
8161                if(dot || exponent)
8162                {
8163                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8164                      type.kind = floatType;
8165                   else
8166                      type.kind = doubleType;
8167                   type.isSigned = true;
8168                }
8169                else
8170                {
8171                   bool isSigned = constant[0] == '-';
8172                   char * endP = null;
8173                   int64 i64 = strtoll(constant, &endP, 0);
8174                   uint64 ui64 = strtoull(constant, &endP, 0);
8175                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8176                   bool forceUnsigned = endP && (!strcmp(endP, "U") || !strcmp(endP, "u") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8177                   if(isSigned)
8178                   {
8179                      if(i64 < MININT)
8180                         is64Bit = true;
8181                   }
8182                   else
8183                   {
8184                      if(ui64 > MAXINT)
8185                      {
8186                         if(ui64 > MAXDWORD)
8187                         {
8188                            is64Bit = true;
8189                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8190                               isSigned = true;
8191                         }
8192                      }
8193                      else if(constant[0] != '0' || !constant[1])
8194                         isSigned = true;
8195                   }
8196                   if(forceUnsigned)
8197                      isSigned = false;
8198                   type.kind = is64Bit ? int64Type : intType;
8199                   type.isSigned = isSigned;
8200                }
8201             }
8202             exp.isConstant = true;
8203             if(exp.destType && exp.destType.kind == doubleType)
8204                type.kind = doubleType;
8205             else if(exp.destType && exp.destType.kind == floatType)
8206                type.kind = floatType;
8207             else if(exp.destType && exp.destType.kind == int64Type)
8208                type.kind = int64Type;
8209          }
8210          break;
8211       }
8212       case stringExp:
8213       {
8214          exp.isConstant = true;      // Why wasn't this constant?
8215          exp.expType = Type
8216          {
8217             refCount = 1;
8218             kind = pointerType;
8219             type = Type
8220             {
8221                refCount = 1;
8222                kind = exp.wideString ? shortType : charType;
8223                constant = true;
8224                isSigned = exp.wideString ? false : true;
8225             }
8226          };
8227          break;
8228       }
8229       case newExp:
8230       case new0Exp:
8231          ProcessExpressionType(exp._new.size);
8232          exp.expType = Type
8233          {
8234             refCount = 1;
8235             kind = pointerType;
8236             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8237          };
8238          DeclareType(curExternal, exp.expType.type, true, false);
8239          break;
8240       case renewExp:
8241       case renew0Exp:
8242          ProcessExpressionType(exp._renew.size);
8243          ProcessExpressionType(exp._renew.exp);
8244          exp.expType = Type
8245          {
8246             refCount = 1;
8247             kind = pointerType;
8248             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8249          };
8250          DeclareType(curExternal, exp.expType.type, true, false);
8251          break;
8252       case opExp:
8253       {
8254          bool assign = false, boolResult = false, boolOps = false;
8255          Type type1 = null, type2 = null;
8256          bool useDestType = false, useSideType = false;
8257          Location oldyylloc = yylloc;
8258          bool useSideUnit = false;
8259          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8260
8261          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8262          Type dummy
8263          {
8264             count = 1;
8265             refCount = 1;
8266          };
8267
8268          switch(exp.op.op)
8269          {
8270             // Assignment Operators
8271             case '=':
8272             case MUL_ASSIGN:
8273             case DIV_ASSIGN:
8274             case MOD_ASSIGN:
8275             case ADD_ASSIGN:
8276             case SUB_ASSIGN:
8277             case LEFT_ASSIGN:
8278             case RIGHT_ASSIGN:
8279             case AND_ASSIGN:
8280             case XOR_ASSIGN:
8281             case OR_ASSIGN:
8282                assign = true;
8283                break;
8284             // boolean Operators
8285             case '!':
8286                // Expect boolean operators
8287                //boolOps = true;
8288                //boolResult = true;
8289                break;
8290             case AND_OP:
8291             case OR_OP:
8292                // Expect boolean operands
8293                boolOps = true;
8294                boolResult = true;
8295                break;
8296             // Comparisons
8297             case EQ_OP:
8298             case '<':
8299             case '>':
8300             case LE_OP:
8301             case GE_OP:
8302             case NE_OP:
8303                // Gives boolean result
8304                boolResult = true;
8305                useSideType = true;
8306                break;
8307             case '+':
8308             case '-':
8309                useSideUnit = true;
8310                useSideType = true;
8311                useDestType = true;
8312                break;
8313
8314             case LEFT_OP:
8315             case RIGHT_OP:
8316                // useSideType = true;
8317                // useDestType = true;
8318                break;
8319
8320             case '|':
8321             case '^':
8322                useSideType = true;
8323                useDestType = true;
8324                break;
8325
8326             case '/':
8327             case '%':
8328                useSideType = true;
8329                useDestType = true;
8330                break;
8331             case '&':
8332             case '*':
8333                if(exp.op.exp1)
8334                {
8335                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8336                   useSideType = true;
8337                   useDestType = true;
8338                }
8339                break;
8340
8341             /*// Implement speed etc.
8342             case '*':
8343             case '/':
8344                break;
8345             */
8346          }
8347          if(exp.op.op == '&')
8348          {
8349             // Added this here earlier for Iterator address as key
8350             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8351             {
8352                Identifier id = exp.op.exp2.identifier;
8353                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8354                if(symbol && symbol.isIterator == 2)
8355                {
8356                   exp.type = memberExp;
8357                   exp.member.exp = exp.op.exp2;
8358                   exp.member.member = MkIdentifier("key");
8359                   exp.expType = null;
8360                   exp.op.exp2.expType = symbol.type;
8361                   symbol.type.refCount++;
8362                   ProcessExpressionType(exp);
8363                   FreeType(dummy);
8364                   break;
8365                }
8366                // exp.op.exp2.usage.usageRef = true;
8367             }
8368          }
8369
8370          //dummy.kind = TypeDummy;
8371          if(exp.op.exp1)
8372          {
8373             // Added this check here to use the dest type only for units derived from the base unit
8374             // So that untyped units will use the side unit as opposed to the untyped destination unit
8375             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8376             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8377                useDestType = false;
8378
8379             if(destClass && useDestType &&
8380               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8381
8382               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8383             {
8384                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8385                exp.op.exp1.destType = exp.destType;
8386                exp.op.exp1.opDestType = true;
8387                if(exp.destType)
8388                   exp.destType.refCount++;
8389             }
8390             else if(!assign)
8391             {
8392                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8393                exp.op.exp1.destType = dummy;
8394                dummy.refCount++;
8395             }
8396
8397             // TESTING THIS HERE...
8398             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8399                ProcessExpressionType(exp.op.exp1);
8400             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8401
8402             exp.op.exp1.opDestType = false;
8403
8404             // Fix for unit and ++ / --
8405             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8406                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8407             {
8408                exp.op.exp2 = MkExpConstant("1");
8409                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8410                assign = true;
8411             }
8412
8413             if(exp.op.exp1.destType == dummy)
8414             {
8415                FreeType(dummy);
8416                exp.op.exp1.destType = null;
8417             }
8418
8419             if(exp.op.exp2)
8420             {
8421                if(!assign && exp.op.exp1.expType && (exp.op.exp1.expType.kind == charType || exp.op.exp1.expType.kind == shortType))
8422                {
8423                   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 };
8424                   FreeType(exp.op.exp1.expType);
8425                   exp.op.exp1.expType = type;
8426                }
8427             }
8428
8429             type1 = exp.op.exp1.expType;
8430          }
8431
8432          if(exp.op.exp2)
8433          {
8434             char expString[10240];
8435             expString[0] = '\0';
8436             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8437             {
8438                if(exp.op.exp1)
8439                {
8440                   exp.op.exp2.destType = exp.op.exp1.expType;
8441                   if(exp.op.exp1.expType)
8442                      exp.op.exp1.expType.refCount++;
8443                }
8444                else
8445                {
8446                   exp.op.exp2.destType = exp.destType;
8447                   if(!exp.op.exp1 || (exp.op.op != '&' && exp.op.op != '^'))
8448                      exp.op.exp2.opDestType = true;
8449                   if(exp.destType)
8450                      exp.destType.refCount++;
8451                }
8452
8453                if(type1) type1.refCount++;
8454                exp.expType = type1;
8455             }
8456             else if(assign)
8457             {
8458                if(inCompiler)
8459                   PrintExpression(exp.op.exp2, expString);
8460
8461                if(type1 && type1.kind == pointerType)
8462                {
8463                   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 ||
8464                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8465                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8466                   else if(exp.op.op == '=')
8467                   {
8468                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8469                      exp.op.exp2.destType = type1;
8470                      if(type1)
8471                         type1.refCount++;
8472                   }
8473                }
8474                else
8475                {
8476                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8477                   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/* ||
8478                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8479                   else
8480                   {
8481                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8482                      exp.op.exp2.destType = type1;
8483                      if(type1)
8484                         type1.refCount++;
8485                   }
8486                }
8487                if(type1) type1.refCount++;
8488                exp.expType = type1;
8489             }
8490             else if(destClass &&
8491                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8492                   (destClass.type == enumClass && useDestType)))
8493             {
8494                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8495                exp.op.exp2.destType = exp.destType;
8496                if(exp.op.op != '&' && exp.op.op != '^')
8497                   exp.op.exp2.opDestType = true;
8498                if(exp.destType)
8499                   exp.destType.refCount++;
8500             }
8501             else
8502             {
8503                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8504                exp.op.exp2.destType = dummy;
8505                dummy.refCount++;
8506             }
8507
8508             // TESTING THIS HERE... (DANGEROUS)
8509             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8510                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8511             {
8512                FreeType(exp.op.exp2.destType);
8513                exp.op.exp2.destType = type1;
8514                type1.refCount++;
8515             }
8516             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8517             // Cannot lose the cast on a sizeof
8518             if(exp.op.op == SIZEOF)
8519             {
8520                Expression e = exp.op.exp2;
8521                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8522                {
8523                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8524                   {
8525                      if(e.type == extensionCompoundExp)
8526                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8527                      else
8528                         e = e.list->last;
8529                   }
8530                }
8531                if(e.type == castExp && e.cast.exp)
8532                   e.cast.exp.needCast = true;
8533             }
8534             ProcessExpressionType(exp.op.exp2);
8535             exp.op.exp2.opDestType = false;
8536             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8537
8538             if(!assign && (exp.op.exp1 || exp.op.op == '~'))
8539             {
8540                if(exp.op.exp2.expType && (exp.op.exp2.expType.kind == charType || exp.op.exp2.expType.kind == shortType))
8541                {
8542                   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 };
8543                   FreeType(exp.op.exp2.expType);
8544                   exp.op.exp2.expType = type;
8545                }
8546             }
8547
8548             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8549             {
8550                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)
8551                {
8552                   if(exp.op.op != '=' && type1.type.kind == voidType)
8553                      Compiler_Error($"void *: unknown size\n");
8554                }
8555                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||
8556                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8557                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8558                               exp.op.exp2.expType._class.registered.type == structClass ||
8559                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8560                {
8561                   if(exp.op.op == ADD_ASSIGN)
8562                      Compiler_Error($"cannot add two pointers\n");
8563                }
8564                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8565                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8566                {
8567                   if(exp.op.op == ADD_ASSIGN)
8568                      Compiler_Error($"cannot add two pointers\n");
8569                }
8570                else if(inCompiler)
8571                {
8572                   char type1String[1024];
8573                   char type2String[1024];
8574                   type1String[0] = '\0';
8575                   type2String[0] = '\0';
8576
8577                   PrintType(exp.op.exp2.expType, type1String, false, true);
8578                   PrintType(type1, type2String, false, true);
8579                   ChangeCh(expString, '\n', ' ');
8580                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8581                }
8582             }
8583
8584             if(exp.op.exp2.destType == dummy)
8585             {
8586                FreeType(dummy);
8587                exp.op.exp2.destType = null;
8588             }
8589
8590             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8591             {
8592                type2 = { };
8593                type2.refCount = 1;
8594                CopyTypeInto(type2, exp.op.exp2.expType);
8595                type2.isSigned = true;
8596             }
8597             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8598             {
8599                type2 = { kind = intType };
8600                type2.refCount = 1;
8601                type2.isSigned = true;
8602             }
8603             else
8604             {
8605                type2 = exp.op.exp2.expType;
8606                if(type2) type2.refCount++;
8607             }
8608          }
8609
8610          dummy.kind = voidType;
8611
8612          if(exp.op.op == SIZEOF)
8613          {
8614             exp.expType = Type
8615             {
8616                refCount = 1;
8617                kind = intSizeType;
8618             };
8619             exp.isConstant = true;
8620          }
8621          // Get type of dereferenced pointer
8622          else if(exp.op.op == '*' && !exp.op.exp1)
8623          {
8624             exp.expType = Dereference(type2);
8625             if(type2 && type2.kind == classType)
8626                notByReference = true;
8627          }
8628          else if(exp.op.op == '&' && !exp.op.exp1)
8629             exp.expType = Reference(type2);
8630          else if(exp.op.op == LEFT_OP || exp.op.op == RIGHT_OP)
8631          {
8632             if(exp.op.exp1.expType)
8633             {
8634                exp.expType = exp.op.exp1.expType;
8635                exp.expType.refCount++;
8636             }
8637          }
8638          else if(!assign)
8639          {
8640             if(boolOps)
8641             {
8642                if(exp.op.exp1)
8643                {
8644                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8645                   exp.op.exp1.destType = MkClassType("bool");
8646                   exp.op.exp1.destType.truth = true;
8647                   if(!exp.op.exp1.expType)
8648                      ProcessExpressionType(exp.op.exp1);
8649                   else
8650                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8651                   FreeType(exp.op.exp1.expType);
8652                   exp.op.exp1.expType = MkClassType("bool");
8653                   exp.op.exp1.expType.truth = true;
8654                }
8655                if(exp.op.exp2)
8656                {
8657                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8658                   exp.op.exp2.destType = MkClassType("bool");
8659                   exp.op.exp2.destType.truth = true;
8660                   if(!exp.op.exp2.expType)
8661                      ProcessExpressionType(exp.op.exp2);
8662                   else
8663                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8664                   FreeType(exp.op.exp2.expType);
8665                   exp.op.exp2.expType = MkClassType("bool");
8666                   exp.op.exp2.expType.truth = true;
8667                }
8668             }
8669             else if(exp.op.exp1 && exp.op.exp2 &&
8670                ((useSideType /*&&
8671                      (useSideUnit ||
8672                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8673                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8674                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8675                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8676             {
8677                if(type1 && type2 &&
8678                   // If either both are class or both are not class
8679                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8680                {
8681                   // Added this check for enum subtraction to result in an int type:
8682                   if(exp.op.op == '-' &&
8683                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8684                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8685                   {
8686                      Type intType;
8687                      if(!type1._class.registered.dataType)
8688                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8689                      if(!type2._class.registered.dataType)
8690                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8691
8692                      intType = ProcessTypeString(
8693                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8694
8695                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8696                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8697                      exp.op.exp1.destType = intType;
8698                      exp.op.exp2.destType = intType;
8699                      intType.refCount++;
8700                   }
8701                   else
8702                   {
8703                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8704                      exp.op.exp2.destType = type1;
8705                      type1.refCount++;
8706                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8707                      exp.op.exp1.destType = type2;
8708                      type2.refCount++;
8709                   }
8710
8711                   // Warning here for adding Radians + Degrees with no destination type
8712                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8713                      type1._class.registered && type1._class.registered.type == unitClass &&
8714                      type2._class.registered && type2._class.registered.type == unitClass &&
8715                      type1._class.registered != type2._class.registered)
8716                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8717                         type1._class.string, type2._class.string, type1._class.string);
8718
8719                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8720                   {
8721                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8722                      if(argExp)
8723                      {
8724                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8725
8726                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8727                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8728                            exp.op.exp1)));
8729
8730                         ProcessExpressionType(exp.op.exp1);
8731
8732                         if(type2.kind != pointerType)
8733                         {
8734                            ProcessExpressionType(classExp);
8735
8736                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8737
8738                            if(!exp.op.exp2.expType)
8739                            {
8740                               if(type2)
8741                                  FreeType(type2);
8742                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8743                               type2.refCount++;
8744                            }
8745
8746                            ProcessExpressionType(exp.op.exp2);
8747                         }
8748                      }
8749                   }
8750
8751                   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)))
8752                   {
8753                      if(type1.kind != classType && type1.type.kind == voidType)
8754                         Compiler_Error($"void *: unknown size\n");
8755                      exp.expType = type1;
8756                      if(type1) type1.refCount++;
8757                   }
8758                   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)))
8759                   {
8760                      if(type2.kind != classType && type2.type.kind == voidType)
8761                         Compiler_Error($"void *: unknown size\n");
8762                      exp.expType = type2;
8763                      if(type2) type2.refCount++;
8764                   }
8765                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8766                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8767                   {
8768                      Compiler_Warning($"different levels of indirection\n");
8769                   }
8770                   else
8771                   {
8772                      bool success = false;
8773                      if(type1.kind == pointerType && type2.kind == pointerType)
8774                      {
8775                         if(exp.op.op == '+')
8776                            Compiler_Error($"cannot add two pointers\n");
8777                         else if(exp.op.op == '-')
8778                         {
8779                            // Pointer Subtraction gives integer
8780                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8781                            {
8782                               exp.expType = Type
8783                               {
8784                                  kind = intType;
8785                                  refCount = 1;
8786                               };
8787                               success = true;
8788
8789                               if(type1.type.kind == templateType)
8790                               {
8791                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8792                                  if(argExp)
8793                                  {
8794                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8795
8796                                     ProcessExpressionType(classExp);
8797
8798                                     exp.type = bracketsExp;
8799                                     exp.list = MkListOne(MkExpOp(
8800                                        MkExpBrackets(MkListOne(MkExpOp(
8801                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8802                                              , exp.op.op,
8803                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8804                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8805
8806                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8807                                     FreeType(dummy);
8808                                     return;
8809                                  }
8810                               }
8811                            }
8812                         }
8813                      }
8814
8815                      if(!success && exp.op.exp1.type == constantExp)
8816                      {
8817                         // If first expression is constant, try to match that first
8818                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8819                         {
8820                            if(exp.expType) FreeType(exp.expType);
8821                            exp.expType = exp.op.exp1.destType;
8822                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8823                            success = true;
8824                         }
8825                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8826                         {
8827                            if(exp.expType) FreeType(exp.expType);
8828                            exp.expType = exp.op.exp2.destType;
8829                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8830                            success = true;
8831                         }
8832                      }
8833                      else if(!success)
8834                      {
8835                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8836                         {
8837                            if(exp.expType) FreeType(exp.expType);
8838                            exp.expType = exp.op.exp2.destType;
8839                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8840                            success = true;
8841                         }
8842                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8843                         {
8844                            if(exp.expType) FreeType(exp.expType);
8845                            exp.expType = exp.op.exp1.destType;
8846                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8847                            success = true;
8848                         }
8849                      }
8850                      if(!success)
8851                      {
8852                         char expString1[10240];
8853                         char expString2[10240];
8854                         char type1[1024];
8855                         char type2[1024];
8856                         expString1[0] = '\0';
8857                         expString2[0] = '\0';
8858                         type1[0] = '\0';
8859                         type2[0] = '\0';
8860                         if(inCompiler)
8861                         {
8862                            PrintExpression(exp.op.exp1, expString1);
8863                            ChangeCh(expString1, '\n', ' ');
8864                            PrintExpression(exp.op.exp2, expString2);
8865                            ChangeCh(expString2, '\n', ' ');
8866                            PrintType(exp.op.exp1.expType, type1, false, true);
8867                            PrintType(exp.op.exp2.expType, type2, false, true);
8868                         }
8869
8870                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8871                      }
8872                   }
8873                }
8874                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8875                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8876                {
8877                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8878                   // Convert e.g. / 4 into / 4.0
8879                   exp.op.exp1.destType = type2._class.registered.dataType;
8880                   if(type2._class.registered.dataType)
8881                      type2._class.registered.dataType.refCount++;
8882                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8883                   exp.expType = type2;
8884                   if(type2) type2.refCount++;
8885                }
8886                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8887                {
8888                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8889                   // Convert e.g. / 4 into / 4.0
8890                   exp.op.exp2.destType = type1._class.registered.dataType;
8891                   if(type1._class.registered.dataType)
8892                      type1._class.registered.dataType.refCount++;
8893                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8894                   exp.expType = type1;
8895                   if(type1) type1.refCount++;
8896                }
8897                else if(type1)
8898                {
8899                   bool valid = false;
8900
8901                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8902                   {
8903                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8904
8905                      if(!type1._class.registered.dataType)
8906                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8907                      exp.op.exp2.destType = type1._class.registered.dataType;
8908                      exp.op.exp2.destType.refCount++;
8909
8910                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8911                      if(type2)
8912                         FreeType(type2);
8913                      type2 = exp.op.exp2.destType;
8914                      if(type2) type2.refCount++;
8915
8916                      exp.expType = type2;
8917                      type2.refCount++;
8918                   }
8919
8920                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8921                   {
8922                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8923
8924                      if(!type2._class.registered.dataType)
8925                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8926                      exp.op.exp1.destType = type2._class.registered.dataType;
8927                      exp.op.exp1.destType.refCount++;
8928
8929                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8930                      type1 = exp.op.exp1.destType;
8931                      exp.expType = type1;
8932                      type1.refCount++;
8933                   }
8934
8935                   // TESTING THIS NEW CODE
8936                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8937                   {
8938                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8939                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8940                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8941                      {
8942                         // Convert the enum to an int instead for these operators
8943                         if(op1IsEnum && exp.op.exp2.expType)
8944                         {
8945                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8946                            {
8947                               if(exp.expType) FreeType(exp.expType);
8948                               exp.expType = exp.op.exp2.expType;
8949                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8950                               valid = true;
8951                            }
8952                         }
8953                         else if(op2IsEnum && exp.op.exp1.expType)
8954                         {
8955                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8956                            {
8957                               if(exp.expType) FreeType(exp.expType);
8958                               exp.expType = exp.op.exp1.expType;
8959                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8960                               valid = true;
8961                            }
8962                         }
8963                      }
8964                      else
8965                      {
8966                         if(op1IsEnum && exp.op.exp2.expType)
8967                         {
8968                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8969                            {
8970                               if(exp.expType) FreeType(exp.expType);
8971                               exp.expType = exp.op.exp1.expType;
8972                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8973                               valid = true;
8974                            }
8975                         }
8976                         else if(op2IsEnum && exp.op.exp1.expType)
8977                         {
8978                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8979                            {
8980                               if(exp.expType) FreeType(exp.expType);
8981                               exp.expType = exp.op.exp2.expType;
8982                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8983                               valid = true;
8984                            }
8985                         }
8986                      }
8987                   }
8988
8989                   if(!valid)
8990                   {
8991                      // 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
8992                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8993                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8994                      {
8995                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8996                         exp.op.exp1.destType = type2;
8997                         type2.refCount++;
8998
8999                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9000                         {
9001                            if(exp.expType) FreeType(exp.expType);
9002                            exp.expType = exp.op.exp1.destType;
9003                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9004                         }
9005                      }
9006                      else
9007                      {
9008                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9009                         exp.op.exp2.destType = type1;
9010                         type1.refCount++;
9011
9012                      /*
9013                      // Maybe this was meant to be an enum...
9014                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9015                      {
9016                         Type oldType = exp.op.exp2.expType;
9017                         exp.op.exp2.expType = null;
9018                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
9019                            FreeType(oldType);
9020                         else
9021                            exp.op.exp2.expType = oldType;
9022                      }
9023                      */
9024
9025                      /*
9026                      // TESTING THIS HERE... LATEST ADDITION
9027                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9028                      {
9029                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9030                         exp.op.exp2.destType = type2._class.registered.dataType;
9031                         if(type2._class.registered.dataType)
9032                            type2._class.registered.dataType.refCount++;
9033                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
9034
9035                         //exp.expType = type2._class.registered.dataType; //type2;
9036                         //if(type2) type2.refCount++;
9037                      }
9038
9039                      // TESTING THIS HERE... LATEST ADDITION
9040                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9041                      {
9042                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9043                         exp.op.exp1.destType = type1._class.registered.dataType;
9044                         if(type1._class.registered.dataType)
9045                            type1._class.registered.dataType.refCount++;
9046                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9047                         exp.expType = type1._class.registered.dataType; //type1;
9048                         if(type1) type1.refCount++;
9049                      }
9050                      */
9051
9052                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9053                         {
9054                            if(exp.expType) FreeType(exp.expType);
9055                            exp.expType = exp.op.exp2.destType;
9056                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9057                         }
9058                         else if(type1 && type2)
9059                         {
9060                            char expString1[10240];
9061                            char expString2[10240];
9062                            char type1String[1024];
9063                            char type2String[1024];
9064                            expString1[0] = '\0';
9065                            expString2[0] = '\0';
9066                            type1String[0] = '\0';
9067                            type2String[0] = '\0';
9068                            if(inCompiler)
9069                            {
9070                               PrintExpression(exp.op.exp1, expString1);
9071                               ChangeCh(expString1, '\n', ' ');
9072                               PrintExpression(exp.op.exp2, expString2);
9073                               ChangeCh(expString2, '\n', ' ');
9074                               PrintType(exp.op.exp1.expType, type1String, false, true);
9075                               PrintType(exp.op.exp2.expType, type2String, false, true);
9076                            }
9077
9078                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9079
9080                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9081                            {
9082                               exp.expType = exp.op.exp1.expType;
9083                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9084                            }
9085                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9086                            {
9087                               exp.expType = exp.op.exp2.expType;
9088                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9089                            }
9090                         }
9091                      }
9092                   }
9093                }
9094                else if(type2)
9095                {
9096                   // Maybe this was meant to be an enum...
9097                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9098                   {
9099                      Type oldType = exp.op.exp1.expType;
9100                      exp.op.exp1.expType = null;
9101                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9102                         FreeType(oldType);
9103                      else
9104                         exp.op.exp1.expType = oldType;
9105                   }
9106
9107                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9108                   exp.op.exp1.destType = type2;
9109                   type2.refCount++;
9110                   /*
9111                   // TESTING THIS HERE... LATEST ADDITION
9112                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9113                   {
9114                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9115                      exp.op.exp1.destType = type1._class.registered.dataType;
9116                      if(type1._class.registered.dataType)
9117                         type1._class.registered.dataType.refCount++;
9118                   }
9119
9120                   // TESTING THIS HERE... LATEST ADDITION
9121                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9122                   {
9123                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9124                      exp.op.exp2.destType = type2._class.registered.dataType;
9125                      if(type2._class.registered.dataType)
9126                         type2._class.registered.dataType.refCount++;
9127                   }
9128                   */
9129
9130                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9131                   {
9132                      if(exp.expType) FreeType(exp.expType);
9133                      exp.expType = exp.op.exp1.destType;
9134                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9135                   }
9136                }
9137             }
9138             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9139             {
9140                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9141                {
9142                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9143                   // Convert e.g. / 4 into / 4.0
9144                   exp.op.exp1.destType = type2._class.registered.dataType;
9145                   if(type2._class.registered.dataType)
9146                      type2._class.registered.dataType.refCount++;
9147                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9148                }
9149                if(exp.op.op == '!')
9150                {
9151                   exp.expType = MkClassType("bool");
9152                   exp.expType.truth = true;
9153                }
9154                else
9155                {
9156                   exp.expType = type2;
9157                   if(type2) type2.refCount++;
9158                }
9159             }
9160             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9161             {
9162                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9163                {
9164                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9165                   // Convert e.g. / 4 into / 4.0
9166                   exp.op.exp2.destType = type1._class.registered.dataType;
9167                   if(type1._class.registered.dataType)
9168                      type1._class.registered.dataType.refCount++;
9169                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9170                }
9171                exp.expType = type1;
9172                if(type1) type1.refCount++;
9173             }
9174          }
9175
9176          yylloc = exp.loc;
9177          if(exp.op.exp1 && !exp.op.exp1.expType)
9178          {
9179             char expString[10000];
9180             expString[0] = '\0';
9181             if(inCompiler)
9182             {
9183                PrintExpression(exp.op.exp1, expString);
9184                ChangeCh(expString, '\n', ' ');
9185             }
9186             if(expString[0])
9187                Compiler_Error($"couldn't determine type of %s\n", expString);
9188          }
9189          if(exp.op.exp2 && !exp.op.exp2.expType)
9190          {
9191             char expString[10240];
9192             expString[0] = '\0';
9193             if(inCompiler)
9194             {
9195                PrintExpression(exp.op.exp2, expString);
9196                ChangeCh(expString, '\n', ' ');
9197             }
9198             if(expString[0])
9199                Compiler_Error($"couldn't determine type of %s\n", expString);
9200          }
9201
9202          if(boolResult)
9203          {
9204             FreeType(exp.expType);
9205             exp.expType = MkClassType("bool");
9206             exp.expType.truth = true;
9207          }
9208
9209          if(exp.op.op != SIZEOF)
9210             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9211                (!exp.op.exp2 || exp.op.exp2.isConstant);
9212
9213          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9214          {
9215             DeclareType(curExternal, exp.op.exp2.expType, true, false);
9216          }
9217
9218          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9219             Compiler_Warning($"deleting const qualified object\n");
9220
9221          yylloc = oldyylloc;
9222
9223          FreeType(dummy);
9224          if(type2)
9225             FreeType(type2);
9226          break;
9227       }
9228       case bracketsExp:
9229       case extensionExpressionExp:
9230       {
9231          Expression e;
9232          exp.isConstant = true;
9233          for(e = exp.list->first; e; e = e.next)
9234          {
9235             //bool inced = false;
9236             if(!e.next)
9237             {
9238                FreeType(e.destType);
9239                e.opDestType = exp.opDestType;
9240                e.destType = exp.destType;
9241                if(e.destType) { exp.destType.refCount++; /*e.destType.count++; inced = true;*/ }
9242             }
9243             ProcessExpressionType(e);
9244             /*if(inced)
9245                exp.destType.count--;*/
9246             if(!exp.expType && !e.next)
9247             {
9248                exp.expType = e.expType;
9249                if(e.expType) e.expType.refCount++;
9250             }
9251             if(!e.isConstant)
9252                exp.isConstant = false;
9253          }
9254
9255          // In case a cast became a member...
9256          e = exp.list->first;
9257          if(!e.next && e.type == memberExp)
9258          {
9259             // Preserve prev, next
9260             Expression next = exp.next, prev = exp.prev;
9261
9262
9263             FreeType(exp.expType);
9264             FreeType(exp.destType);
9265             delete exp.list;
9266
9267             *exp = *e;
9268
9269             exp.prev = prev;
9270             exp.next = next;
9271
9272             delete e;
9273
9274             ProcessExpressionType(exp);
9275          }
9276          break;
9277       }
9278       case indexExp:
9279       {
9280          Expression e;
9281          exp.isConstant = true;
9282
9283          ProcessExpressionType(exp.index.exp);
9284          if(!exp.index.exp.isConstant)
9285             exp.isConstant = false;
9286
9287          if(exp.index.exp.expType)
9288          {
9289             Type source = exp.index.exp.expType;
9290             if(source.kind == classType && source._class && source._class.registered)
9291             {
9292                Class _class = source._class.registered;
9293                Class c = _class.templateClass ? _class.templateClass : _class;
9294                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9295                {
9296                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9297
9298                   if(exp.index.index && exp.index.index->last)
9299                   {
9300                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9301
9302                      if(type.kind == classType) type.constant = true;
9303                      else if(type.kind == pointerType)
9304                      {
9305                         Type t = type;
9306                         while(t.kind == pointerType) t = t.type;
9307                         t.constant = true;
9308                      }
9309
9310                      ((Expression)exp.index.index->last).destType = type;
9311                   }
9312                }
9313             }
9314          }
9315
9316          for(e = exp.index.index->first; e; e = e.next)
9317          {
9318             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9319             {
9320                if(e.destType) FreeType(e.destType);
9321                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9322             }
9323             ProcessExpressionType(e);
9324             if(!e.next)
9325             {
9326                // Check if this type is int
9327             }
9328             if(!e.isConstant)
9329                exp.isConstant = false;
9330          }
9331
9332          if(!exp.expType)
9333             exp.expType = Dereference(exp.index.exp.expType);
9334          if(exp.expType)
9335             DeclareType(curExternal, exp.expType, true, false);
9336          break;
9337       }
9338       case callExp:
9339       {
9340          Expression e;
9341          Type functionType;
9342          Type methodType = null;
9343          char name[1024];
9344          name[0] = '\0';
9345
9346          if(inCompiler)
9347          {
9348             PrintExpression(exp.call.exp,  name);
9349             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9350             {
9351                //exp.call.exp.expType = null;
9352                PrintExpression(exp.call.exp,  name);
9353             }
9354          }
9355          if(exp.call.exp.type == identifierExp)
9356          {
9357             Expression idExp = exp.call.exp;
9358             Identifier id = idExp.identifier;
9359             if(!strcmp(id.string, "__builtin_frame_address"))
9360             {
9361                exp.expType = ProcessTypeString("void *", true);
9362                if(exp.call.arguments && exp.call.arguments->first)
9363                   ProcessExpressionType(exp.call.arguments->first);
9364                break;
9365             }
9366             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9367             {
9368                exp.expType = ProcessTypeString("int", true);
9369                if(exp.call.arguments && exp.call.arguments->first)
9370                   ProcessExpressionType(exp.call.arguments->first);
9371                break;
9372             }
9373             else if(!strcmp(id.string, "Max") ||
9374                !strcmp(id.string, "Min") ||
9375                !strcmp(id.string, "Sgn") ||
9376                !strcmp(id.string, "Abs"))
9377             {
9378                Expression a = null;
9379                Expression b = null;
9380                Expression tempExp1 = null, tempExp2 = null;
9381                if((!strcmp(id.string, "Max") ||
9382                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9383                {
9384                   a = exp.call.arguments->first;
9385                   b = exp.call.arguments->last;
9386                   tempExp1 = a;
9387                   tempExp2 = b;
9388                }
9389                else if(exp.call.arguments->count == 1)
9390                {
9391                   a = exp.call.arguments->first;
9392                   tempExp1 = a;
9393                }
9394
9395                if(a)
9396                {
9397                   exp.call.arguments->Clear();
9398                   idExp.identifier = null;
9399
9400                   FreeExpContents(exp);
9401
9402                   ProcessExpressionType(a);
9403                   if(b)
9404                      ProcessExpressionType(b);
9405
9406                   exp.type = bracketsExp;
9407                   exp.list = MkList();
9408
9409                   if(a.expType && (!b || b.expType))
9410                   {
9411                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9412                      {
9413                         // Use the simpleStruct name/ids for now...
9414                         if(inCompiler)
9415                         {
9416                            OldList * specs = MkList();
9417                            OldList * decls = MkList();
9418                            Declaration decl;
9419                            char temp1[1024], temp2[1024];
9420
9421                            GetTypeSpecs(a.expType, specs);
9422
9423                            if(a && !a.isConstant && a.type != identifierExp)
9424                            {
9425                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9426                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9427                               tempExp1 = QMkExpId(temp1);
9428                               tempExp1.expType = a.expType;
9429                               if(a.expType)
9430                                  a.expType.refCount++;
9431                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9432                            }
9433                            if(b && !b.isConstant && b.type != identifierExp)
9434                            {
9435                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9436                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9437                               tempExp2 = QMkExpId(temp2);
9438                               tempExp2.expType = b.expType;
9439                               if(b.expType)
9440                                  b.expType.refCount++;
9441                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9442                            }
9443
9444                            decl = MkDeclaration(specs, decls);
9445                            if(!curCompound.compound.declarations)
9446                               curCompound.compound.declarations = MkList();
9447                            curCompound.compound.declarations->Insert(null, decl);
9448                         }
9449                      }
9450                   }
9451
9452                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9453                   {
9454                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9455                      ListAdd(exp.list,
9456                         MkExpCondition(MkExpBrackets(MkListOne(
9457                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9458                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9459                      exp.expType = a.expType;
9460                      if(a.expType)
9461                         a.expType.refCount++;
9462                   }
9463                   else if(!strcmp(id.string, "Abs"))
9464                   {
9465                      ListAdd(exp.list,
9466                         MkExpCondition(MkExpBrackets(MkListOne(
9467                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9468                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9469                      exp.expType = a.expType;
9470                      if(a.expType)
9471                         a.expType.refCount++;
9472                   }
9473                   else if(!strcmp(id.string, "Sgn"))
9474                   {
9475                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9476                      ListAdd(exp.list,
9477                         MkExpCondition(MkExpBrackets(MkListOne(
9478                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9479                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9480                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9481                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9482                      exp.expType = ProcessTypeString("int", false);
9483                   }
9484
9485                   FreeExpression(tempExp1);
9486                   if(tempExp2) FreeExpression(tempExp2);
9487
9488                   FreeIdentifier(id);
9489                   break;
9490                }
9491             }
9492          }
9493
9494          {
9495             Type dummy
9496             {
9497                count = 1;
9498                refCount = 1;
9499             };
9500             if(!exp.call.exp.destType)
9501             {
9502                exp.call.exp.destType = dummy;
9503                dummy.refCount++;
9504             }
9505             ProcessExpressionType(exp.call.exp);
9506             if(exp.call.exp.destType == dummy)
9507             {
9508                FreeType(dummy);
9509                exp.call.exp.destType = null;
9510             }
9511             FreeType(dummy);
9512          }
9513
9514          // Check argument types against parameter types
9515          functionType = exp.call.exp.expType;
9516
9517          if(functionType && functionType.kind == TypeKind::methodType)
9518          {
9519             methodType = functionType;
9520             functionType = methodType.method.dataType;
9521
9522             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9523             // TOCHECK: Instead of doing this here could this be done per param?
9524             if(exp.call.exp.expType.usedClass)
9525             {
9526                char typeString[1024];
9527                typeString[0] = '\0';
9528                {
9529                   Symbol back = functionType.thisClass;
9530                   // Do not output class specifier here (thisclass was added to this)
9531                   functionType.thisClass = null;
9532                   PrintType(functionType, typeString, true, true);
9533                   functionType.thisClass = back;
9534                }
9535                if(strstr(typeString, "thisclass"))
9536                {
9537                   OldList * specs = MkList();
9538                   Declarator decl;
9539                   {
9540                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9541
9542                      decl = SpecDeclFromString(typeString, specs, null);
9543
9544                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9545                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9546                         exp.call.exp.expType.usedClass))
9547                         thisClassParams = false;
9548
9549                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9550                      {
9551                         Class backupThisClass = thisClass;
9552                         thisClass = exp.call.exp.expType.usedClass;
9553                         ProcessDeclarator(decl, true);
9554                         thisClass = backupThisClass;
9555                      }
9556
9557                      thisClassParams = true;
9558
9559                      functionType = ProcessType(specs, decl);
9560                      functionType.refCount = 0;
9561                      FinishTemplatesContext(context);
9562
9563                      // Mark parameters that were 'thisclass'
9564                      {
9565                         Type p, op;
9566                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9567                         {
9568                            //p.wasThisClass = op.kind == thisClassType;
9569                            if(op.kind == thisClassType)
9570                               p.thisClassFrom = methodType.method._class;
9571                         }
9572                      }
9573                      if(methodType.method.dataType.returnType.kind == thisClassType)
9574                      {
9575                         // functionType.returnType.wasThisClass = true;
9576                         functionType.returnType.thisClassFrom = methodType.method._class;
9577                      }
9578                   }
9579
9580                   FreeList(specs, FreeSpecifier);
9581                   FreeDeclarator(decl);
9582                 }
9583             }
9584          }
9585          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9586          {
9587             Type type = functionType.type;
9588             if(!functionType.refCount)
9589             {
9590                functionType.type = null;
9591                FreeType(functionType);
9592             }
9593             //methodType = functionType;
9594             functionType = type;
9595          }
9596          if(functionType && functionType.kind != TypeKind::functionType)
9597          {
9598             Compiler_Error($"called object %s is not a function\n", name);
9599          }
9600          else if(functionType)
9601          {
9602             bool emptyParams = false, noParams = false;
9603             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9604             Type type = functionType.params.first;
9605             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9606             int extra = 0;
9607             Location oldyylloc = yylloc;
9608
9609             if(!type) emptyParams = true;
9610
9611             // WORKING ON THIS:
9612             if(functionType.extraParam && e && functionType.thisClass)
9613             {
9614                e.destType = MkClassType(functionType.thisClass.string);
9615                e = e.next;
9616             }
9617
9618             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9619             // Fixed #141 by adding '&& !functionType.extraParam'
9620             if(!functionType.staticMethod && !functionType.extraParam)
9621             {
9622                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9623                   memberExp.member.exp.expType._class)
9624                {
9625                   type = MkClassType(memberExp.member.exp.expType._class.string);
9626                   if(e)
9627                   {
9628                      e.destType = type;
9629                      e = e.next;
9630                      type = functionType.params.first;
9631                   }
9632                   else
9633                      type.refCount = 0;
9634                }
9635                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9636                {
9637                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9638                   type.byReference = functionType.byReference;
9639                   type.typedByReference = functionType.typedByReference;
9640                   if(e)
9641                   {
9642                      // Allow manually passing a class for typed object
9643                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9644                         e = e.next;
9645                      e.destType = type;
9646                      e = e.next;
9647                      type = functionType.params.first;
9648                   }
9649                   else
9650                      type.refCount = 0;
9651                   //extra = 1;
9652                }
9653             }
9654
9655             if(type && type.kind == voidType)
9656             {
9657                noParams = true;
9658                if(!type.refCount) FreeType(type);
9659                type = null;
9660             }
9661
9662             for( ; e; e = e.next)
9663             {
9664                if(!type && !emptyParams)
9665                {
9666                   yylloc = e.loc;
9667                   if(methodType && methodType.methodClass)
9668                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9669                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9670                         noParams ? 0 : functionType.params.count);
9671                   else
9672                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9673                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9674                         noParams ? 0 : functionType.params.count);
9675                   break;
9676                }
9677
9678                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9679                {
9680                   Type templatedType = null;
9681                   Class _class = methodType.usedClass;
9682                   ClassTemplateParameter curParam = null;
9683                   int id = 0;
9684                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9685                   {
9686                      Class sClass;
9687                      for(sClass = _class; sClass; sClass = sClass.base)
9688                      {
9689                         if(sClass.templateClass) sClass = sClass.templateClass;
9690                         id = 0;
9691                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9692                         {
9693                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9694                            {
9695                               Class nextClass;
9696                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9697                               {
9698                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9699                                  id += nextClass.templateParams.count;
9700                               }
9701                               break;
9702                            }
9703                            id++;
9704                         }
9705                         if(curParam) break;
9706                      }
9707                   }
9708                   if(curParam && _class.templateArgs[id].dataTypeString)
9709                   {
9710                      bool constant = type.constant;
9711                      ClassTemplateArgument arg = _class.templateArgs[id];
9712                      {
9713                         Context context = SetupTemplatesContext(_class);
9714
9715                         /*if(!arg.dataType)
9716                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9717                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9718                         FinishTemplatesContext(context);
9719                      }
9720
9721                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9722                      else if(templatedType.kind == pointerType)
9723                      {
9724                         Type t = templatedType.type;
9725                         while(t.kind == pointerType) t = t.type;
9726                         if(constant) t.constant = constant;
9727                      }
9728
9729                      e.destType = templatedType;
9730                      if(templatedType)
9731                      {
9732                         templatedType.passAsTemplate = true;
9733                         // templatedType.refCount++;
9734                      }
9735                   }
9736                   else
9737                   {
9738                      e.destType = type;
9739                      if(type) type.refCount++;
9740                   }
9741                }
9742                else
9743                {
9744                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9745                   {
9746                      e.destType = type.prev;
9747                      e.destType.refCount++;
9748                   }
9749                   else
9750                   {
9751                      e.destType = type;
9752                      if(type) type.refCount++;
9753                   }
9754                }
9755                // Don't reach the end for the ellipsis
9756                if(type && type.kind != ellipsisType)
9757                {
9758                   Type next = type.next;
9759                   if(!type.refCount) FreeType(type);
9760                   type = next;
9761                }
9762             }
9763
9764             if(type && type.kind != ellipsisType)
9765             {
9766                if(methodType && methodType.methodClass)
9767                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9768                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9769                      functionType.params.count + extra);
9770                else
9771                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9772                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9773                      functionType.params.count + extra);
9774             }
9775             yylloc = oldyylloc;
9776             if(type && !type.refCount) FreeType(type);
9777          }
9778          else
9779          {
9780             functionType = Type
9781             {
9782                refCount = 0;
9783                kind = TypeKind::functionType;
9784             };
9785
9786             if(exp.call.exp.type == identifierExp)
9787             {
9788                char * string = exp.call.exp.identifier.string;
9789                if(inCompiler)
9790                {
9791                   Symbol symbol;
9792                   Location oldyylloc = yylloc;
9793
9794                   yylloc = exp.call.exp.identifier.loc;
9795                   if(strstr(string, "__builtin_") == string)
9796                   {
9797                      if(exp.destType)
9798                      {
9799                         functionType.returnType = exp.destType;
9800                         exp.destType.refCount++;
9801                      }
9802                   }
9803                   else
9804                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9805                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9806                   globalContext.symbols.Add((BTNode)symbol);
9807                   if(strstr(symbol.string, "::"))
9808                      globalContext.hasNameSpace = true;
9809
9810                   yylloc = oldyylloc;
9811                }
9812             }
9813             else if(exp.call.exp.type == memberExp)
9814             {
9815                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9816                   exp.call.exp.member.member.string);*/
9817             }
9818             else
9819                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9820
9821             if(!functionType.returnType)
9822             {
9823                functionType.returnType = Type
9824                {
9825                   refCount = 1;
9826                   kind = intType;
9827                };
9828             }
9829          }
9830          if(functionType && functionType.kind == TypeKind::functionType)
9831          {
9832             exp.expType = functionType.returnType;
9833
9834             if(functionType.returnType)
9835                functionType.returnType.refCount++;
9836
9837             if(!functionType.refCount)
9838                FreeType(functionType);
9839          }
9840
9841          if(exp.call.arguments)
9842          {
9843             for(e = exp.call.arguments->first; e; e = e.next)
9844                ProcessExpressionType(e);
9845          }
9846          break;
9847       }
9848       case memberExp:
9849       {
9850          Type type;
9851          Location oldyylloc = yylloc;
9852          bool thisPtr;
9853          Expression checkExp = exp.member.exp;
9854          while(checkExp)
9855          {
9856             if(checkExp.type == castExp)
9857                checkExp = checkExp.cast.exp;
9858             else if(checkExp.type == bracketsExp)
9859                checkExp = checkExp.list ? checkExp.list->first : null;
9860             else
9861                break;
9862          }
9863
9864          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9865          exp.thisPtr = thisPtr;
9866
9867          // DOING THIS LATER NOW...
9868          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9869          {
9870             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9871             /* TODO: Name Space Fix ups
9872             if(!exp.member.member.classSym)
9873                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9874             */
9875          }
9876
9877          ProcessExpressionType(exp.member.exp);
9878          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9879             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9880          {
9881             exp.isConstant = false;
9882          }
9883          else
9884             exp.isConstant = exp.member.exp.isConstant;
9885          type = exp.member.exp.expType;
9886
9887          yylloc = exp.loc;
9888
9889          if(type && (type.kind == templateType))
9890          {
9891             Class _class = thisClass ? thisClass : currentClass;
9892             ClassTemplateParameter param = null;
9893             if(_class)
9894             {
9895                for(param = _class.templateParams.first; param; param = param.next)
9896                {
9897                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9898                      break;
9899                }
9900             }
9901             if(param && param.defaultArg.member)
9902             {
9903                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9904                if(argExp)
9905                {
9906                   Expression expMember = exp.member.exp;
9907                   Declarator decl;
9908                   OldList * specs = MkList();
9909                   char thisClassTypeString[1024];
9910
9911                   FreeIdentifier(exp.member.member);
9912
9913                   ProcessExpressionType(argExp);
9914
9915                   {
9916                      char * colon = strstr(param.defaultArg.memberString, "::");
9917                      if(colon)
9918                      {
9919                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9920                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9921                      }
9922                      else
9923                         strcpy(thisClassTypeString, _class.fullName);
9924                   }
9925
9926                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9927
9928                   exp.expType = ProcessType(specs, decl);
9929                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9930                   {
9931                      Class expClass = exp.expType._class.registered;
9932                      Class cClass = null;
9933                      int paramCount = 0;
9934                      int lastParam = -1;
9935
9936                      char templateString[1024];
9937                      ClassTemplateParameter param;
9938                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9939                      for(cClass = expClass; cClass; cClass = cClass.base)
9940                      {
9941                         int p = 0;
9942                         for(param = cClass.templateParams.first; param; param = param.next)
9943                         {
9944                            int id = p;
9945                            Class sClass;
9946                            ClassTemplateArgument arg;
9947                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9948                            arg = expClass.templateArgs[id];
9949
9950                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9951                            {
9952                               ClassTemplateParameter cParam;
9953                               //int p = numParams - sClass.templateParams.count;
9954                               int p = 0;
9955                               Class nextClass;
9956                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9957
9958                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9959                               {
9960                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9961                                  {
9962                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9963                                     {
9964                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9965                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9966                                        break;
9967                                     }
9968                                  }
9969                               }
9970                            }
9971
9972                            {
9973                               char argument[256];
9974                               argument[0] = '\0';
9975                               /*if(arg.name)
9976                               {
9977                                  strcat(argument, arg.name.string);
9978                                  strcat(argument, " = ");
9979                               }*/
9980                               switch(param.type)
9981                               {
9982                                  case expression:
9983                                  {
9984                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9985                                     char expString[1024];
9986                                     OldList * specs = MkList();
9987                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9988                                     Expression exp;
9989                                     char * string = PrintHexUInt64(arg.expression.ui64);
9990                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9991                                     delete string;
9992
9993                                     ProcessExpressionType(exp);
9994                                     ComputeExpression(exp);
9995                                     expString[0] = '\0';
9996                                     PrintExpression(exp, expString);
9997                                     strcat(argument, expString);
9998                                     // delete exp;
9999                                     FreeExpression(exp);
10000                                     break;
10001                                  }
10002                                  case identifier:
10003                                  {
10004                                     strcat(argument, arg.member.name);
10005                                     break;
10006                                  }
10007                                  case TemplateParameterType::type:
10008                                  {
10009                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10010                                     {
10011                                        if(!strcmp(arg.dataTypeString, "thisclass"))
10012                                           strcat(argument, thisClassTypeString);
10013                                        else
10014                                           strcat(argument, arg.dataTypeString);
10015                                     }
10016                                     break;
10017                                  }
10018                               }
10019                               if(argument[0])
10020                               {
10021                                  if(paramCount) strcat(templateString, ", ");
10022                                  if(lastParam != p - 1)
10023                                  {
10024                                     strcat(templateString, param.name);
10025                                     strcat(templateString, " = ");
10026                                  }
10027                                  strcat(templateString, argument);
10028                                  paramCount++;
10029                                  lastParam = p;
10030                               }
10031                               p++;
10032                            }
10033                         }
10034                      }
10035                      {
10036                         int len = strlen(templateString);
10037                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10038                         templateString[len++] = '>';
10039                         templateString[len++] = '\0';
10040                      }
10041                      {
10042                         Context context = SetupTemplatesContext(_class);
10043                         FreeType(exp.expType);
10044                         exp.expType = ProcessTypeString(templateString, false);
10045                         FinishTemplatesContext(context);
10046                      }
10047                   }
10048
10049                   if(!expMember.expType.isPointerType)
10050                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10051                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10052                   exp.type = bracketsExp;
10053                   exp.list = MkListOne(MkExpOp(null, '*',
10054                   /*opExp;
10055                   exp.op.op = '*';
10056                   exp.op.exp1 = null;
10057                   exp.op.exp2 = */
10058                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10059                      MkExpBrackets(MkListOne(
10060                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10061                            expMember))),
10062                               '+',
10063                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10064                               '+',
10065                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10066
10067                            ));
10068                }
10069             }
10070             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10071                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10072             {
10073                type = ProcessTemplateParameterType(type.templateParameter);
10074             }
10075          }
10076          // TODO: *** This seems to be where we should add method support for all basic types ***
10077          if(type && (type.kind == templateType));
10078          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10079                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10080                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10081                           (type.kind == pointerType && type.type.kind == charType)))
10082          {
10083             Identifier id = exp.member.member;
10084             TypeKind typeKind = type.kind;
10085             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10086             if(typeKind == subClassType && exp.member.exp.type == classExp)
10087             {
10088                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10089                typeKind = classType;
10090             }
10091
10092             if(id)
10093             {
10094                if(typeKind == intType || typeKind == enumType)
10095                   _class = eSystem_FindClass(privateModule, "int");
10096                else if(!_class)
10097                {
10098                   if(type.kind == classType && type._class && type._class.registered)
10099                   {
10100                      _class = type._class.registered;
10101                   }
10102                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10103                   {
10104                      _class = FindClass("char *").registered;
10105                   }
10106                   else if(type.kind == pointerType)
10107                   {
10108                      _class = eSystem_FindClass(privateModule, "uintptr");
10109                      FreeType(exp.expType);
10110                      exp.expType = ProcessTypeString("uintptr", false);
10111                      exp.byReference = true;
10112                   }
10113                   else
10114                   {
10115                      char string[1024] = "";
10116                      Symbol classSym;
10117                      PrintTypeNoConst(type, string, false, true);
10118                      classSym = FindClass(string);
10119                      if(classSym) _class = classSym.registered;
10120                   }
10121                }
10122             }
10123
10124             if(_class && id)
10125             {
10126                /*bool thisPtr =
10127                   (exp.member.exp.type == identifierExp &&
10128                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10129                Property prop = null;
10130                Method method = null;
10131                DataMember member = null;
10132                Property revConvert = null;
10133                ClassProperty classProp = null;
10134
10135                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10136                   exp.member.memberType = propertyMember;
10137
10138                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10139                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10140
10141                if(typeKind != subClassType)
10142                {
10143                   // Prioritize data members over properties for "this"
10144                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10145                   {
10146                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10147                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10148                      {
10149                         prop = eClass_FindProperty(_class, id.string, privateModule);
10150                         if(prop)
10151                            member = null;
10152                      }
10153                      if(!member && !prop)
10154                         prop = eClass_FindProperty(_class, id.string, privateModule);
10155                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10156                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10157                         exp.member.thisPtr = true;
10158                   }
10159                   // Prioritize properties over data members otherwise
10160                   else
10161                   {
10162                      bool useMemberForNonConst = false;
10163                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10164                      if(!id.classSym)
10165                      {
10166                         prop = eClass_FindProperty(_class, id.string, null);
10167
10168                         useMemberForNonConst = prop && exp.destType &&
10169                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10170                               !strncmp(prop.dataTypeString, "const ", 6);
10171
10172                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10173                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10174                      }
10175
10176                      if((!prop || useMemberForNonConst) && !member)
10177                      {
10178                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10179                         if(!method)
10180                         {
10181                            prop = eClass_FindProperty(_class, id.string, privateModule);
10182
10183                            useMemberForNonConst |= prop && exp.destType &&
10184                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10185                                  !strncmp(prop.dataTypeString, "const ", 6);
10186
10187                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10188                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10189                         }
10190                      }
10191
10192                      if(member && prop)
10193                      {
10194                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10195                            prop = null;
10196                         else
10197                            member = null;
10198                      }
10199                   }
10200                }
10201                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10202                   method = eClass_FindMethod(_class, id.string, privateModule);
10203                if(!prop && !member && !method)
10204                {
10205                   if(typeKind == subClassType)
10206                   {
10207                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10208                      if(classProp)
10209                      {
10210                         exp.member.memberType = classPropertyMember;
10211                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10212                      }
10213                      else
10214                      {
10215                         // Assume this is a class_data member
10216                         char structName[1024];
10217                         Identifier id = exp.member.member;
10218                         Expression classExp = exp.member.exp;
10219                         type.refCount++;
10220
10221                         FreeType(classExp.expType);
10222                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10223
10224                         strcpy(structName, "__ecereClassData_");
10225                         FullClassNameCat(structName, type._class.string, false);
10226                         exp.type = pointerExp;
10227                         exp.member.member = id;
10228
10229                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10230                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10231                               MkExpBrackets(MkListOne(MkExpOp(
10232                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10233                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10234                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10235                                  )));
10236
10237                         FreeType(type);
10238
10239                         ProcessExpressionType(exp);
10240                         return;
10241                      }
10242                   }
10243                   else
10244                   {
10245                      // Check for reverse conversion
10246                      // (Convert in an instantiation later, so that we can use
10247                      //  deep properties system)
10248                      Symbol classSym = FindClass(id.string);
10249                      if(classSym)
10250                      {
10251                         Class convertClass = classSym.registered;
10252                         if(convertClass)
10253                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10254                      }
10255                   }
10256                }
10257
10258                //if(!exp.member.exp.destType)
10259                if(exp.member.exp.destType)
10260                   FreeType(exp.member.exp.destType);
10261                {
10262                   if(method && !method._class.symbol)
10263                      method._class.symbol = FindClass(method._class.fullName);
10264                   if(prop && !prop._class.symbol)
10265                      prop._class.symbol = FindClass(prop._class.fullName);
10266
10267                   exp.member.exp.destType = Type
10268                   {
10269                      refCount = 1;
10270                      kind = classType;
10271                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10272                      // wasThisClass = type ? type.wasThisClass : false;
10273                      thisClassFrom = type ? type.thisClassFrom : null;
10274                   };
10275                }
10276
10277                if(prop)
10278                {
10279                   exp.member.memberType = propertyMember;
10280                   if(!prop.dataType)
10281                      ProcessPropertyType(prop);
10282                   exp.expType = prop.dataType;
10283                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10284                   {
10285                      Type type { };
10286                      CopyTypeInto(type, exp.expType);
10287                      type.refCount = 1;
10288                      type.constant = true;
10289                      exp.expType = type;
10290                   }
10291                   else if(prop.dataType)
10292                      prop.dataType.refCount++;
10293                }
10294                else if(member)
10295                {
10296                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10297                   {
10298                      FreeExpContents(exp);
10299                      exp.type = identifierExp;
10300                      exp.identifier = MkIdentifier("class");
10301                      ProcessExpressionType(exp);
10302                      return;
10303                   }
10304
10305                   exp.member.memberType = dataMember;
10306                   DeclareStruct(curExternal, _class.fullName, false, true);
10307                   if(member._class != _class)
10308                      DeclareStruct(curExternal, member._class.fullName, false, true);
10309
10310                   if(!member.dataType)
10311                   {
10312                      Context context = SetupTemplatesContext(_class);
10313                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10314                      FinishTemplatesContext(context);
10315                   }
10316                   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)
10317                      member.dataType.bitMemberSize = ((BitMember)member).size;
10318                   exp.expType = member.dataType;
10319                   if(member.dataType) member.dataType.refCount++;
10320                }
10321                else if(revConvert)
10322                {
10323                   exp.member.memberType = reverseConversionMember;
10324                   exp.expType = MkClassType(revConvert._class.fullName);
10325                }
10326                else if(method)
10327                {
10328                   //if(inCompiler)
10329                   {
10330                      /*if(id._class)
10331                      {
10332                         exp.type = identifierExp;
10333                         exp.identifier = exp.member.member;
10334                      }
10335                      else*/
10336                         exp.member.memberType = methodMember;
10337                   }
10338                   if(!method.dataType)
10339                      ProcessMethodType(method);
10340                   exp.expType = Type
10341                   {
10342                      refCount = 1;
10343                      kind = methodType;
10344                      method = method;
10345                   };
10346
10347                   // Tricky spot here... To use instance versus class virtual table
10348                   // Put it back to what it was... What did we break?
10349
10350                   // Had to put it back for overriding Main of Thread global instance
10351
10352                   //exp.expType.methodClass = _class;
10353                   exp.expType.methodClass = (id && id._class) ? _class : null;
10354
10355                   // Need the actual class used for templated classes
10356                   exp.expType.usedClass = _class;
10357                }
10358                else if(!classProp)
10359                {
10360                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10361                   {
10362                      FreeExpContents(exp);
10363                      exp.type = identifierExp;
10364                      exp.identifier = MkIdentifier("class");
10365                      FreeType(exp.expType);
10366                      exp.expType = MkClassType("ecere::com::Class");
10367                      return;
10368                   }
10369                   yylloc = exp.member.member.loc;
10370                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10371                   if(inCompiler)
10372                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10373                }
10374
10375                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10376                {
10377                   Class tClass;
10378
10379                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10380                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10381
10382                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10383                   {
10384                      int id = 0;
10385                      ClassTemplateParameter curParam = null;
10386                      Class sClass;
10387
10388                      for(sClass = tClass; sClass; sClass = sClass.base)
10389                      {
10390                         id = 0;
10391                         if(sClass.templateClass) sClass = sClass.templateClass;
10392                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10393                         {
10394                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10395                            {
10396                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10397                                  id += sClass.templateParams.count;
10398                               break;
10399                            }
10400                            id++;
10401                         }
10402                         if(curParam) break;
10403                      }
10404
10405                      if(curParam && tClass.templateArgs[id].dataTypeString)
10406                      {
10407                         ClassTemplateArgument arg = tClass.templateArgs[id];
10408                         Context context = SetupTemplatesContext(tClass);
10409                         bool constant = exp.expType.constant;
10410                         bool passAsTemplate = false;
10411                         Class thisClassFrom = null;
10412                         Type t = ProcessTypeString(exp.expType.templateParameter.dataTypeString, false);
10413                         if(t && t.kind == classType && t._class)
10414                            thisClassFrom = t._class.registered;
10415                         else
10416                            // Mark that 'thisClassFrom' was set to something
10417                            thisClassFrom = eSystem_FindClass(GetPrivateModule(), "class");
10418
10419                         FreeType(t);
10420
10421                         passAsTemplate = tClass.templateClass && (exp.expType.kind != templateType ||
10422                            (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType)));
10423
10424                         /*if(!arg.dataType)
10425                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10426                         FreeType(exp.expType);
10427
10428                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10429                         exp.expType.thisClassFrom = thisClassFrom;
10430                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10431                         else if(exp.expType.kind == pointerType)
10432                         {
10433                            Type t = exp.expType.type;
10434                            while(t.kind == pointerType) t = t.type;
10435                            if(constant) t.constant = constant;
10436                         }
10437                         if(exp.expType)
10438                         {
10439                            if(exp.expType.kind == thisClassType)
10440                            {
10441                               FreeType(exp.expType);
10442                               exp.expType = ReplaceThisClassType(_class);
10443                            }
10444
10445                            if(passAsTemplate)
10446                               exp.expType.passAsTemplate = true;
10447                            //exp.expType.refCount++;
10448                            if(!exp.destType)
10449                            {
10450                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10451                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10452                               else if(exp.destType.kind == pointerType)
10453                               {
10454                                  Type t = exp.destType.type;
10455                                  while(t.kind == pointerType) t = t.type;
10456                                  if(constant) t.constant = constant;
10457                               }
10458
10459                               //exp.destType.refCount++;
10460
10461                               if(exp.destType.kind == thisClassType)
10462                               {
10463                                  FreeType(exp.destType);
10464                                  exp.destType = ReplaceThisClassType(_class);
10465                               }
10466                            }
10467                         }
10468                         FinishTemplatesContext(context);
10469                      }
10470                   }
10471                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10472                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10473                   {
10474                      int id = 0;
10475                      ClassTemplateParameter curParam = null;
10476                      Class sClass;
10477
10478                      for(sClass = tClass; sClass; sClass = sClass.base)
10479                      {
10480                         id = 0;
10481                         if(sClass.templateClass) sClass = sClass.templateClass;
10482                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10483                         {
10484                            if(curParam.type == TemplateParameterType::type &&
10485                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10486                            {
10487                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10488                                  id += sClass.templateParams.count;
10489                               break;
10490                            }
10491                            id++;
10492                         }
10493                         if(curParam) break;
10494                      }
10495
10496                      if(curParam)
10497                      {
10498                         ClassTemplateArgument arg = tClass.templateArgs[id];
10499                         Context context = SetupTemplatesContext(tClass);
10500                         Type basicType;
10501                         /*if(!arg.dataType)
10502                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10503
10504                         basicType = ProcessTypeString(arg.dataTypeString, false);
10505                         if(basicType)
10506                         {
10507                            if(basicType.kind == thisClassType)
10508                            {
10509                               FreeType(basicType);
10510                               basicType = ReplaceThisClassType(_class);
10511                            }
10512
10513                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10514                            if(tClass.templateClass)
10515                               basicType.passAsTemplate = true;
10516                            */
10517
10518                            FreeType(exp.expType);
10519
10520                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10521                            //exp.expType.refCount++;
10522                            if(!exp.destType)
10523                            {
10524                               exp.destType = exp.expType;
10525                               exp.destType.refCount++;
10526                            }
10527
10528                            {
10529                               Expression newExp { };
10530                               OldList * specs = MkList();
10531                               Declarator decl;
10532                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10533                               *newExp = *exp;
10534                               if(exp.destType) exp.destType.refCount++;
10535                               if(exp.expType)  exp.expType.refCount++;
10536                               exp.type = castExp;
10537                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10538                               exp.cast.exp = newExp;
10539                               //FreeType(exp.expType);
10540                               //exp.expType = null;
10541                               //ProcessExpressionType(sourceExp);
10542                            }
10543                         }
10544                         FinishTemplatesContext(context);
10545                      }
10546                   }
10547                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10548                   {
10549                      Class expClass = exp.expType._class.registered;
10550                      if(expClass)
10551                      {
10552                         Class cClass = null;
10553                         int p = 0;
10554                         int paramCount = 0;
10555                         int lastParam = -1;
10556                         char templateString[1024];
10557                         ClassTemplateParameter param;
10558                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10559                         while(cClass != expClass)
10560                         {
10561                            Class sClass;
10562                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10563                            cClass = sClass;
10564
10565                            for(param = cClass.templateParams.first; param; param = param.next)
10566                            {
10567                               Class cClassCur = null;
10568                               int cp = 0;
10569                               ClassTemplateParameter paramCur = null;
10570                               ClassTemplateArgument arg;
10571                               while(cClassCur != tClass && !paramCur)
10572                               {
10573                                  Class sClassCur;
10574                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10575                                  cClassCur = sClassCur;
10576
10577                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10578                                  {
10579                                     if(!strcmp(paramCur.name, param.name))
10580                                     {
10581
10582                                        break;
10583                                     }
10584                                     cp++;
10585                                  }
10586                               }
10587                               if(paramCur && paramCur.type == TemplateParameterType::type)
10588                                  arg = tClass.templateArgs[cp];
10589                               else
10590                                  arg = expClass.templateArgs[p];
10591
10592                               {
10593                                  char argument[256];
10594                                  argument[0] = '\0';
10595                                  /*if(arg.name)
10596                                  {
10597                                     strcat(argument, arg.name.string);
10598                                     strcat(argument, " = ");
10599                                  }*/
10600                                  switch(param.type)
10601                                  {
10602                                     case expression:
10603                                     {
10604                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10605                                        char expString[1024];
10606                                        OldList * specs = MkList();
10607                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10608                                        Expression exp;
10609                                        char * string = PrintHexUInt64(arg.expression.ui64);
10610                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10611                                        delete string;
10612
10613                                        ProcessExpressionType(exp);
10614                                        ComputeExpression(exp);
10615                                        expString[0] = '\0';
10616                                        PrintExpression(exp, expString);
10617                                        strcat(argument, expString);
10618                                        // delete exp;
10619                                        FreeExpression(exp);
10620                                        break;
10621                                     }
10622                                     case identifier:
10623                                     {
10624                                        strcat(argument, arg.member.name);
10625                                        break;
10626                                     }
10627                                     case TemplateParameterType::type:
10628                                     {
10629                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10630                                           strcat(argument, arg.dataTypeString);
10631                                        break;
10632                                     }
10633                                  }
10634                                  if(argument[0])
10635                                  {
10636                                     if(paramCount) strcat(templateString, ", ");
10637                                     if(lastParam != p - 1)
10638                                     {
10639                                        strcat(templateString, param.name);
10640                                        strcat(templateString, " = ");
10641                                     }
10642                                     strcat(templateString, argument);
10643                                     paramCount++;
10644                                     lastParam = p;
10645                                  }
10646                               }
10647                               p++;
10648                            }
10649                         }
10650                         {
10651                            int len = strlen(templateString);
10652                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10653                            templateString[len++] = '>';
10654                            templateString[len++] = '\0';
10655                         }
10656
10657                         FreeType(exp.expType);
10658                         {
10659                            Context context = SetupTemplatesContext(tClass);
10660                            exp.expType = ProcessTypeString(templateString, false);
10661                            FinishTemplatesContext(context);
10662                         }
10663                      }
10664                   }
10665                }
10666             }
10667             else
10668                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10669          }
10670          else if(type && (type.kind == structType || type.kind == unionType))
10671          {
10672             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10673             if(memberType)
10674             {
10675                exp.expType = memberType;
10676                if(memberType)
10677                   memberType.refCount++;
10678             }
10679          }
10680          else
10681          {
10682             char expString[10240];
10683             expString[0] = '\0';
10684             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10685             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10686          }
10687
10688          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10689          {
10690             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10691             {
10692                Identifier id = exp.member.member;
10693                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10694                if(_class)
10695                {
10696                   FreeType(exp.expType);
10697                   exp.expType = ReplaceThisClassType(_class);
10698                }
10699             }
10700          }
10701          yylloc = oldyylloc;
10702          break;
10703       }
10704       // Convert x->y into (*x).y
10705       case pointerExp:
10706       {
10707          Type destType = exp.destType;
10708
10709          // DOING THIS LATER NOW...
10710          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10711          {
10712             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10713             /* TODO: Name Space Fix ups
10714             if(!exp.member.member.classSym)
10715                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10716             */
10717          }
10718
10719          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10720          exp.type = memberExp;
10721          if(destType)
10722             destType.count++;
10723          ProcessExpressionType(exp);
10724          if(destType)
10725             destType.count--;
10726          break;
10727       }
10728       case classSizeExp:
10729       {
10730          //ComputeExpression(exp);
10731
10732          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10733          if(classSym && classSym.registered)
10734          {
10735             if(classSym.registered.type == noHeadClass || (classSym.registered.fixed && classSym.registered.structSize))
10736             {
10737                char name[1024];
10738                Class b = classSym.registered;
10739                name[0] = '\0';
10740                DeclareStruct(curExternal, classSym.string, false, true);
10741                FreeSpecifier(exp._class);
10742                FullClassNameCat(name, classSym.string, false);
10743
10744                if(b.offset == 0)
10745                {
10746                   exp.type = typeSizeExp;
10747                   exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10748                }
10749                else
10750                {
10751                   Expression e;
10752                   exp.type = opExp;
10753                   if(b.structSize == b.offset)
10754                      exp.op.exp1 = MkExpConstant("0");
10755                   else
10756                      exp.op.exp1 = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10757                   exp.op.op = '+';
10758                   e = exp;
10759                   while(b.offset != 0)
10760                   {
10761                      Symbol sym;
10762                      Expression typeSize;
10763
10764                      b = b.base;
10765                      sym = FindClass(b.fullName);
10766
10767                      name[0] = '\0';
10768                      DeclareStruct(curExternal, sym.string, false, true);
10769                      FullClassNameCat(name, sym.string, false);
10770
10771                      if(b.structSize == b.offset)
10772                         typeSize = MkExpConstant("0");
10773                      else
10774                         typeSize = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10775                      e.op.exp2 = b.offset ? MkExpOp(typeSize, '+', null) : typeSize;
10776                      e = e.op.exp2;
10777                   }
10778                }
10779             }
10780             else
10781             {
10782                if(classSym.registered.fixed && !classSym.registered.structSize)
10783                {
10784                   FreeSpecifier(exp._class);
10785                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10786                   exp.type = constantExp;
10787                }
10788                else
10789                {
10790                   char className[1024];
10791                   strcpy(className, "__ecereClass_");
10792                   FullClassNameCat(className, classSym.string, true);
10793
10794                   DeclareClass(curExternal, classSym, className);
10795
10796                   FreeExpContents(exp);
10797                   exp.type = pointerExp;
10798                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10799                   exp.member.member = MkIdentifier("structSize");
10800                }
10801             }
10802          }
10803
10804          exp.expType = Type
10805          {
10806             refCount = 1;
10807             kind = intSizeType;
10808          };
10809          // exp.isConstant = true;
10810          break;
10811       }
10812       case typeSizeExp:
10813       {
10814          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10815
10816          exp.expType = Type
10817          {
10818             refCount = 1;
10819             kind = intSizeType;
10820          };
10821          exp.isConstant = true;
10822
10823          DeclareType(curExternal, type, true, false);
10824          FreeType(type);
10825          break;
10826       }
10827       case castExp:
10828       {
10829          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10830          type.count = 1;
10831          FreeType(exp.cast.exp.destType);
10832          exp.cast.exp.destType = type;
10833          type.refCount++;
10834          type.casted = true;
10835          ProcessExpressionType(exp.cast.exp);
10836          type.casted = false;
10837          type.count = 0;
10838          exp.expType = type;
10839          //type.refCount++;
10840
10841          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10842          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10843          {
10844             void * prev = exp.prev, * next = exp.next;
10845             Type expType = exp.cast.exp.destType;
10846             Expression castExp = exp.cast.exp;
10847             Type destType = exp.destType;
10848
10849             if(expType) expType.refCount++;
10850
10851             //FreeType(exp.destType);
10852             FreeType(exp.expType);
10853             FreeTypeName(exp.cast.typeName);
10854
10855             *exp = *castExp;
10856             FreeType(exp.expType);
10857             FreeType(exp.destType);
10858
10859             exp.expType = expType;
10860             exp.destType = destType;
10861
10862             delete castExp;
10863
10864             exp.prev = prev;
10865             exp.next = next;
10866
10867          }
10868          else
10869          {
10870             exp.isConstant = exp.cast.exp.isConstant;
10871          }
10872          //FreeType(type);
10873          break;
10874       }
10875       case extensionInitializerExp:
10876       {
10877          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10878          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10879          // ProcessInitializer(exp.initializer.initializer, type);
10880          exp.expType = type;
10881          break;
10882       }
10883       case vaArgExp:
10884       {
10885          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10886          ProcessExpressionType(exp.vaArg.exp);
10887          exp.expType = type;
10888          break;
10889       }
10890       case conditionExp:
10891       {
10892          Expression e;
10893          Type t = exp.destType;
10894          if(t && !exp.destType.casted)
10895          {
10896             t = { };
10897             CopyTypeInto(t, exp.destType);
10898             t.count = 0;
10899          }
10900          else if(t)
10901             t.refCount++;
10902
10903          exp.isConstant = true;
10904
10905          FreeType(exp.cond.cond.destType);
10906          exp.cond.cond.destType = MkClassType("bool");
10907          exp.cond.cond.destType.truth = true;
10908          ProcessExpressionType(exp.cond.cond);
10909          if(!exp.cond.cond.isConstant)
10910             exp.isConstant = false;
10911          for(e = exp.cond.exp->first; e; e = e.next)
10912          {
10913             if(!e.next)
10914             {
10915                FreeType(e.destType);
10916                e.destType = t;
10917                if(e.destType) e.destType.refCount++;
10918             }
10919             ProcessExpressionType(e);
10920             if(!e.next)
10921             {
10922                exp.expType = e.expType;
10923                if(e.expType) e.expType.refCount++;
10924             }
10925             if(!e.isConstant)
10926                exp.isConstant = false;
10927          }
10928
10929          FreeType(exp.cond.elseExp.destType);
10930          // Added this check if we failed to find an expType
10931          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10932
10933          // Reversed it...
10934          exp.cond.elseExp.destType = t ? t : exp.expType;
10935
10936          if(exp.cond.elseExp.destType)
10937             exp.cond.elseExp.destType.refCount++;
10938          ProcessExpressionType(exp.cond.elseExp);
10939
10940          // FIXED THIS: Was done before calling process on elseExp
10941          if(!exp.cond.elseExp.isConstant)
10942             exp.isConstant = false;
10943
10944          FreeType(t);
10945          break;
10946       }
10947       case extensionCompoundExp:
10948       {
10949          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10950          {
10951             Statement last = exp.compound.compound.statements->last;
10952             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10953             {
10954                ((Expression)last.expressions->last).destType = exp.destType;
10955                if(exp.destType)
10956                   exp.destType.refCount++;
10957             }
10958             ProcessStatement(exp.compound);
10959             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10960             if(exp.expType)
10961                exp.expType.refCount++;
10962          }
10963          break;
10964       }
10965       case classExp:
10966       {
10967          Specifier spec = exp._classExp.specifiers->first;
10968          if(spec && spec.type == nameSpecifier)
10969          {
10970             exp.expType = MkClassType(spec.name);
10971             exp.expType.kind = subClassType;
10972             exp.byReference = true;
10973          }
10974          else
10975          {
10976             exp.expType = MkClassType("ecere::com::Class");
10977             exp.byReference = true;
10978          }
10979          break;
10980       }
10981       case classDataExp:
10982       {
10983          Class _class = thisClass ? thisClass : currentClass;
10984          if(_class)
10985          {
10986             Identifier id = exp.classData.id;
10987             char structName[1024];
10988             Expression classExp;
10989             strcpy(structName, "__ecereClassData_");
10990             FullClassNameCat(structName, _class.fullName, false);
10991             exp.type = pointerExp;
10992             exp.member.member = id;
10993             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10994                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10995             else
10996                classExp = MkExpIdentifier(MkIdentifier("class"));
10997
10998             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10999                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
11000                   MkExpBrackets(MkListOne(MkExpOp(
11001                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
11002                         MkExpMember(classExp, MkIdentifier("data"))), '+',
11003                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
11004                      )));
11005
11006             ProcessExpressionType(exp);
11007             return;
11008          }
11009          break;
11010       }
11011       case arrayExp:
11012       {
11013          Type type = null;
11014          const char * typeString = null;
11015          char typeStringBuf[1024];
11016          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
11017             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
11018          {
11019             Class templateClass = exp.destType._class.registered;
11020             typeString = templateClass.templateArgs[2].dataTypeString;
11021          }
11022          else if(exp.list)
11023          {
11024             // Guess type from expressions in the array
11025             Expression e;
11026             for(e = exp.list->first; e; e = e.next)
11027             {
11028                ProcessExpressionType(e);
11029                if(e.expType)
11030                {
11031                   if(!type) { type = e.expType; type.refCount++; }
11032                   else
11033                   {
11034                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
11035                      if(!MatchTypeExpression(e, type, null, false, true))
11036                      {
11037                         FreeType(type);
11038                         type = e.expType;
11039                         e.expType = null;
11040
11041                         e = exp.list->first;
11042                         ProcessExpressionType(e);
11043                         if(e.expType)
11044                         {
11045                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
11046                            if(!MatchTypeExpression(e, type, null, false, true))
11047                            {
11048                               FreeType(e.expType);
11049                               e.expType = null;
11050                               FreeType(type);
11051                               type = null;
11052                               break;
11053                            }
11054                         }
11055                      }
11056                   }
11057                   if(e.expType)
11058                   {
11059                      FreeType(e.expType);
11060                      e.expType = null;
11061                   }
11062                }
11063             }
11064             if(type)
11065             {
11066                typeStringBuf[0] = '\0';
11067                PrintTypeNoConst(type, typeStringBuf, false, true);
11068                typeString = typeStringBuf;
11069                FreeType(type);
11070                type = null;
11071             }
11072          }
11073          if(typeString)
11074          {
11075             /*
11076             (Container)& (struct BuiltInContainer)
11077             {
11078                ._vTbl = class(BuiltInContainer)._vTbl,
11079                ._class = class(BuiltInContainer),
11080                .refCount = 0,
11081                .data = (int[]){ 1, 7, 3, 4, 5 },
11082                .count = 5,
11083                .type = class(int),
11084             }
11085             */
11086             char templateString[1024];
11087             OldList * initializers = MkList();
11088             OldList * structInitializers = MkList();
11089             OldList * specs = MkList();
11090             Expression expExt;
11091             Declarator decl = SpecDeclFromString(typeString, specs, null);
11092             sprintf(templateString, "Container<%s>", typeString);
11093
11094             if(exp.list)
11095             {
11096                Expression e;
11097                type = ProcessTypeString(typeString, false);
11098                while((e = exp.list->first))
11099                {
11100                   exp.list->Remove(e);
11101                   e.destType = type;
11102                   type.refCount++;
11103                   ProcessExpressionType(e);
11104                   ListAdd(initializers, MkInitializerAssignment(e));
11105                }
11106                FreeType(type);
11107                delete exp.list;
11108             }
11109
11110             DeclareStruct(curExternal, "ecere::com::BuiltInContainer", false, true);
11111
11112             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11113                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11114             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11115                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11116             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11117                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11118             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11119                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11120                MkInitializerList(initializers))));
11121                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11122             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11123                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11124             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11125                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11126             exp.expType = ProcessTypeString(templateString, false);
11127             exp.type = bracketsExp;
11128             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11129                MkExpOp(null, '&',
11130                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11131                   MkInitializerList(structInitializers)))));
11132             ProcessExpressionType(expExt);
11133          }
11134          else
11135          {
11136             exp.expType = ProcessTypeString("Container", false);
11137             Compiler_Error($"Couldn't determine type of array elements\n");
11138          }
11139          break;
11140       }
11141    }
11142
11143    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11144    {
11145       FreeType(exp.expType);
11146       exp.expType = ReplaceThisClassType(thisClass);
11147    }
11148
11149    // Resolve structures here
11150    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11151    {
11152       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11153       // TODO: Fix members reference...
11154       if(symbol)
11155       {
11156          if(exp.expType.kind != enumType)
11157          {
11158             Type member;
11159             String enumName = CopyString(exp.expType.enumName);
11160
11161             // Fixed a memory leak on self-referencing C structs typedefs
11162             // by instantiating a new type rather than simply copying members
11163             // into exp.expType
11164             FreeType(exp.expType);
11165             exp.expType = Type { };
11166             exp.expType.kind = symbol.type.kind;
11167             exp.expType.refCount++;
11168             exp.expType.enumName = enumName;
11169
11170             exp.expType.members = symbol.type.members;
11171             for(member = symbol.type.members.first; member; member = member.next)
11172                member.refCount++;
11173          }
11174          else
11175          {
11176             NamedLink64 member;
11177             for(member = symbol.type.members.first; member; member = member.next)
11178             {
11179                NamedLink64 value { name = CopyString(member.name) };
11180                exp.expType.members.Add(value);
11181             }
11182          }
11183       }
11184    }
11185
11186    // Trying to do this here before conversion properties kick in and this becomes a new expression... (Fixing Class c; const char * a = c;)
11187    // Mark nohead classes as by reference, unless we're casting them to an integral type
11188    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11189       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11190          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11191           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11192    {
11193       exp.byReference = true;
11194    }
11195
11196    yylloc = exp.loc;
11197    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11198    else if(exp.destType && !exp.destType.keepCast)
11199    {
11200       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11201          exp.needTemplateCast = 1;
11202
11203       if(exp.destType.kind == voidType);
11204       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11205       {
11206          // Warn for casting unrelated types to/from struct classes
11207          bool invalidCast = false;
11208          if(inCompiler && exp.destType.count && exp.expType)
11209          {
11210             Class c1 = (exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
11211             Class c2 = (exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
11212             if(c1 && c1.type != structClass) c1 = null;
11213             if(c2 && c2.type != structClass) c2 = null;
11214             if((c1 && !exp.expType.byReference && !c2 && !exp.destType.isPointerType) || (c2 && !exp.destType.byReference && !c1 && !exp.expType.isPointerType))
11215                invalidCast = true;
11216          }
11217          if(!exp.destType.count || unresolved || invalidCast)
11218          {
11219             if(!exp.expType)
11220             {
11221                yylloc = exp.loc;
11222                if(exp.destType.kind != ellipsisType)
11223                {
11224                   char type2[1024];
11225                   type2[0] = '\0';
11226                   if(inCompiler)
11227                   {
11228                      char expString[10240];
11229                      expString[0] = '\0';
11230
11231                      PrintType(exp.destType, type2, false, true);
11232
11233                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11234                      if(unresolved)
11235                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11236                      else if(exp.type != dummyExp)
11237                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11238                   }
11239                }
11240                else
11241                {
11242                   char expString[10240] ;
11243                   expString[0] = '\0';
11244                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11245
11246                   if(unresolved)
11247                      Compiler_Error($"unresolved identifier %s\n", expString);
11248                   else if(exp.type != dummyExp)
11249                      Compiler_Error($"couldn't determine type of %s\n", expString);
11250                }
11251             }
11252             else
11253             {
11254                char type1[1024];
11255                char type2[1024];
11256                type1[0] = '\0';
11257                type2[0] = '\0';
11258                if(inCompiler)
11259                {
11260                   PrintType(exp.expType, type1, false, true);
11261                   PrintType(exp.destType, type2, false, true);
11262                }
11263
11264                //CheckExpressionType(exp, exp.destType, false);
11265
11266                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11267                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11268                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11269                else
11270                {
11271                   Expression nbExp = GetNonBracketsExp(exp);
11272                   bool skipWarning = false;
11273                   TypeKind kind = exp.destType.kind;
11274                   if(nbExp.type == conditionExp && nbExp.destType && !nbExp.destType.casted && nbExp.destType.kind == exp.destType.kind)
11275                      // The if/else operands have already been checked / warned about
11276                      skipWarning = true;
11277                   if((kind == charType || kind == shortType) && exp.destType.isSigned == exp.expType.signedBeforePromotion && nbExp.type == opExp && nbExp.op.exp1 && nbExp.op.exp2)
11278                   {
11279                      int op = nbExp.op.op;
11280                      Expression nbExp1, nbExp2;
11281                      TypeKind from;
11282
11283                      switch(op)
11284                      {
11285                         case '%': case '/':
11286                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11287                            from = nbExp1.expType.promotedFrom;
11288                            // Division and Modulo will not take more room than type before promotion
11289                            if(from == charType || (kind == shortType && from == shortType))
11290                               skipWarning = true;
11291                            break;
11292                         // Left shift
11293                         case LEFT_OP: case RIGHT_OP:
11294                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11295                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11296                            from = nbExp1.expType.promotedFrom;
11297                            // Right shift will not take more room than type before promotion
11298                            if(op == RIGHT_OP && (from == charType || (kind == shortType && from == shortType)))
11299                               skipWarning = true;
11300                            else if(nbExp2.isConstant && nbExp2.type == constantExp && (nbExp.op.op == RIGHT_OP || nbExp1.expType.bitMemberSize))
11301                            {
11302                               int n = (int)strtol(nbExp2.constant, null, 0);
11303                               int s = from == charType ? 8 : 16;
11304                               // Left shifting a bit member constrained in size may still fit in type before promotion
11305                               if(nbExp1.expType.bitMemberSize && nbExp1.expType.bitMemberSize < s)
11306                                  s = nbExp1.expType.bitMemberSize;
11307
11308                               // If right shifted enough things will fit in smaller type
11309                               if(nbExp.op.op == RIGHT_OP)
11310                                  s -= n;
11311                               else
11312                                  s += n;
11313                               if(s <= (kind == charType ? 8 : 16))
11314                                  skipWarning = true;
11315                            }
11316                            break;
11317                         case '-':
11318                            if(!exp.destType.isSigned)
11319                            {
11320                               nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11321                               nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11322                               from = nbExp2.expType.promotedFrom;
11323                               // Max value of unsigned type before promotion minus the same will always fit
11324                               if((from == charType || from == shortType) && nbExp1.isConstant && nbExp1.type == constantExp)
11325                               {
11326                                  int n = (int)strtol(nbExp1.constant, null, 0);
11327                                  if(n == (from == charType ? 255 : 65535))
11328                                     skipWarning = true;
11329                               }
11330                            }
11331                            break;
11332                         case '|':
11333                         {
11334                            TypeKind kind1, kind2;
11335                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11336                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11337                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11338                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11339                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) &&
11340                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11341                               skipWarning = true;
11342                            break;
11343                         }
11344                         case '&':
11345                         {
11346                            TypeKind kind1, kind2;
11347                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11348                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11349                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11350                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11351                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) ||
11352                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11353                               skipWarning = true;
11354                            break;
11355                         }
11356                      }
11357                   }
11358
11359                   if(!skipWarning)
11360                   {
11361                      char expString[10240];
11362                      expString[0] = '\0';
11363                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11364
11365 #ifdef _DEBUG
11366                      CheckExpressionType(exp, exp.destType, false, true);
11367 #endif
11368
11369                      // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11370                      if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11371                                         !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11372                                         !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11373                                         !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11374                      {
11375                         if(invalidCast)
11376                            Compiler_Error($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11377                         else
11378                            Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11379                      }
11380                   }
11381
11382                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11383                   if(!inCompiler)
11384                   {
11385                      FreeType(exp.expType);
11386                      exp.destType.refCount++;
11387                      exp.expType = exp.destType;
11388                   }
11389                }
11390             }
11391          }
11392       }
11393       // Cast function pointers to void * as eC already checked compatibility
11394       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11395               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11396       {
11397          Expression nbExp = GetNonBracketsExp(exp);
11398          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11399          {
11400             Expression e = MoveExpContents(exp);
11401             exp.cast.exp = MkExpBrackets(MkListOne(e));
11402             exp.type = castExp;
11403             exp.cast.exp.destType = exp.destType;
11404             if(exp.destType) exp.destType.refCount++;
11405             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11406          }
11407       }
11408    }
11409    else if(unresolved)
11410    {
11411       if(exp.identifier._class && exp.identifier._class.name)
11412          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11413       else if(exp.identifier.string && exp.identifier.string[0])
11414          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11415    }
11416    else if(!exp.expType && exp.type != dummyExp)
11417    {
11418       char expString[10240];
11419       expString[0] = '\0';
11420       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11421       Compiler_Error($"couldn't determine type of %s\n", expString);
11422    }
11423
11424    // Let's try to support any_object & typed_object here:
11425    if(inCompiler)
11426       ApplyAnyObjectLogic(exp);
11427
11428    // Mark nohead classes as by reference, unless we're casting them to an integral type
11429    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11430       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11431          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11432           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11433    {
11434       exp.byReference = true;
11435    }
11436    yylloc = oldyylloc;
11437 }
11438
11439 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11440 {
11441    // THIS CODE WILL FIND NEXT MEMBER...
11442    if(*curMember)
11443    {
11444       *curMember = (*curMember).next;
11445
11446       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11447       {
11448          *curMember = subMemberStack[--(*subMemberStackPos)];
11449          *curMember = (*curMember).next;
11450       }
11451
11452       // SKIP ALL PROPERTIES HERE...
11453       while((*curMember) && (*curMember).isProperty)
11454          *curMember = (*curMember).next;
11455
11456       if(subMemberStackPos)
11457       {
11458          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11459          {
11460             subMemberStack[(*subMemberStackPos)++] = *curMember;
11461
11462             *curMember = (*curMember).members.first;
11463             while(*curMember && (*curMember).isProperty)
11464                *curMember = (*curMember).next;
11465          }
11466       }
11467    }
11468    while(!*curMember)
11469    {
11470       if(!*curMember)
11471       {
11472          if(subMemberStackPos && *subMemberStackPos)
11473          {
11474             *curMember = subMemberStack[--(*subMemberStackPos)];
11475             *curMember = (*curMember).next;
11476          }
11477          else
11478          {
11479             Class lastCurClass = *curClass;
11480
11481             if(*curClass == _class) break;     // REACHED THE END
11482
11483             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11484             *curMember = (*curClass).membersAndProperties.first;
11485          }
11486
11487          while((*curMember) && (*curMember).isProperty)
11488             *curMember = (*curMember).next;
11489          if(subMemberStackPos)
11490          {
11491             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11492             {
11493                subMemberStack[(*subMemberStackPos)++] = *curMember;
11494
11495                *curMember = (*curMember).members.first;
11496                while(*curMember && (*curMember).isProperty)
11497                   *curMember = (*curMember).next;
11498             }
11499          }
11500       }
11501    }
11502 }
11503
11504
11505 static void ProcessInitializer(Initializer init, Type type)
11506 {
11507    switch(init.type)
11508    {
11509       case expInitializer:
11510          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11511          {
11512             // TESTING THIS FOR SHUTTING = 0 WARNING
11513             if(init.exp && !init.exp.destType)
11514             {
11515                FreeType(init.exp.destType);
11516                init.exp.destType = type;
11517                if(type) type.refCount++;
11518             }
11519             if(init.exp)
11520             {
11521                ProcessExpressionType(init.exp);
11522                init.isConstant = init.exp.isConstant;
11523             }
11524             break;
11525          }
11526          else
11527          {
11528             Expression exp = init.exp;
11529             Instantiation inst = exp.instance;
11530             MembersInit members;
11531
11532             init.type = listInitializer;
11533             init.list = MkList();
11534
11535             if(inst.members)
11536             {
11537                for(members = inst.members->first; members; members = members.next)
11538                {
11539                   if(members.type == dataMembersInit)
11540                   {
11541                      MemberInit member;
11542                      for(member = members.dataMembers->first; member; member = member.next)
11543                      {
11544                         ListAdd(init.list, member.initializer);
11545                         member.initializer = null;
11546                      }
11547                   }
11548                   // Discard all MembersInitMethod
11549                }
11550             }
11551             FreeExpression(exp);
11552          }
11553       case listInitializer:
11554       {
11555          Initializer i;
11556          Type initializerType = null;
11557          Class curClass = null;
11558          DataMember curMember = null;
11559          DataMember subMemberStack[256];
11560          int subMemberStackPos = 0;
11561
11562          if(type && type.kind == arrayType)
11563             initializerType = Dereference(type);
11564          else if(type && (type.kind == structType || type.kind == unionType))
11565             initializerType = type.members.first;
11566
11567          for(i = init.list->first; i; i = i.next)
11568          {
11569             if(type && type.kind == classType && type._class && type._class.registered)
11570             {
11571                // 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)
11572                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11573                // TODO: Generate error on initializing a private data member this way from another module...
11574                if(curMember)
11575                {
11576                   if(!curMember.dataType)
11577                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11578                   initializerType = curMember.dataType;
11579                }
11580             }
11581             ProcessInitializer(i, initializerType);
11582             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11583                initializerType = initializerType.next;
11584             if(!i.isConstant)
11585                init.isConstant = false;
11586          }
11587
11588          if(type && type.kind == arrayType)
11589             FreeType(initializerType);
11590
11591          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11592          {
11593             Compiler_Error($"Assigning list initializer to non list\n");
11594          }
11595          break;
11596       }
11597    }
11598 }
11599
11600 static void ProcessSpecifier(Specifier spec, bool declareStruct, bool warnClasses)
11601 {
11602    switch(spec.type)
11603    {
11604       case baseSpecifier:
11605       {
11606          if(spec.specifier == THISCLASS)
11607          {
11608             if(thisClass)
11609             {
11610                spec.type = nameSpecifier;
11611                spec.name = ReplaceThisClass(thisClass);
11612                spec.symbol = FindClass(spec.name);
11613                ProcessSpecifier(spec, declareStruct, false);
11614             }
11615          }
11616          break;
11617       }
11618       case nameSpecifier:
11619       {
11620          Symbol symbol = FindType(curContext, spec.name);
11621          if(symbol)
11622             DeclareType(curExternal, symbol.type, true, true);
11623          else if(spec.symbol /*&& declareStruct*/)
11624          {
11625             Class c = spec.symbol.registered;
11626             if(warnClasses && !c)
11627                Compiler_Warning("Undeclared class %s\n", spec.name);
11628             DeclareStruct(curExternal, spec.name, c && c.type == noHeadClass, declareStruct && c && c.type == structClass);
11629          }
11630          break;
11631       }
11632       case enumSpecifier:
11633       {
11634          Enumerator e;
11635          if(spec.list)
11636          {
11637             for(e = spec.list->first; e; e = e.next)
11638             {
11639                if(e.exp)
11640                   ProcessExpressionType(e.exp);
11641             }
11642          }
11643          // Fall through for IDE type processing
11644          if(inCompiler)
11645             break;
11646       }
11647       case structSpecifier:
11648       case unionSpecifier:
11649       {
11650          if(spec.definitions)
11651          {
11652             //ClassDef def;
11653             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11654             //if(symbol)
11655                ProcessClass(spec.definitions, symbol);
11656             /*else
11657             {
11658                for(def = spec.definitions->first; def; def = def.next)
11659                {
11660                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11661                      ProcessDeclaration(def.decl);
11662                }
11663             }*/
11664          }
11665          break;
11666       }
11667       /*
11668       case classSpecifier:
11669       {
11670          Symbol classSym = FindClass(spec.name);
11671          if(classSym && classSym.registered && classSym.registered.type == structClass)
11672             DeclareStruct(spec.name, false, true);
11673          break;
11674       }
11675       */
11676    }
11677 }
11678
11679
11680 static void ProcessDeclarator(Declarator decl, bool isFunction)
11681 {
11682    switch(decl.type)
11683    {
11684       case identifierDeclarator:
11685          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11686          {
11687             FreeSpecifier(decl.identifier._class);
11688             decl.identifier._class = null;
11689          }
11690          break;
11691       case arrayDeclarator:
11692          if(decl.array.exp)
11693             ProcessExpressionType(decl.array.exp);
11694       case structDeclarator:
11695       case bracketsDeclarator:
11696       case functionDeclarator:
11697       case pointerDeclarator:
11698       case extendedDeclarator:
11699       case extendedDeclaratorEnd:
11700       {
11701          Identifier id = null;
11702          Specifier classSpec = null;
11703          if(decl.type == functionDeclarator)
11704          {
11705             id = GetDeclId(decl);
11706             if(id && id._class)
11707             {
11708                classSpec = id._class;
11709                id._class = null;
11710             }
11711          }
11712          if(decl.declarator)
11713             ProcessDeclarator(decl.declarator, isFunction);
11714          if(decl.type == functionDeclarator)
11715          {
11716             if(classSpec)
11717             {
11718                TypeName param
11719                {
11720                   qualifiers = MkListOne(classSpec);
11721                   declarator = null;
11722                };
11723                if(!decl.function.parameters)
11724                   decl.function.parameters = MkList();
11725                decl.function.parameters->Insert(null, param);
11726             }
11727             if(decl.function.parameters)
11728             {
11729                TypeName param;
11730
11731                for(param = decl.function.parameters->first; param; param = param.next)
11732                {
11733                   if(param.qualifiers)
11734                   {
11735                      Specifier spec;
11736                      for(spec = param.qualifiers->first; spec; spec = spec.next)
11737                      {
11738                         if(spec.type == baseSpecifier)
11739                         {
11740                            if(spec.specifier == TYPED_OBJECT)
11741                            {
11742                               Declarator d = param.declarator;
11743                               TypeName newParam
11744                               {
11745                                  qualifiers = MkListOne(MkSpecifier(VOID));
11746                                  declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11747                               };
11748                               if(!d || d.type != pointerDeclarator)
11749                                  newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11750
11751                               FreeList(param.qualifiers, FreeSpecifier);
11752
11753                               param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11754                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11755
11756                               DeclareStruct(curExternal, "ecere::com::Class", false, true);
11757
11758                               decl.function.parameters->Insert(param, newParam);
11759                               param = newParam;
11760                               break;
11761                            }
11762                            else if(spec.specifier == ANY_OBJECT)
11763                            {
11764                               Declarator d = param.declarator;
11765
11766                               FreeList(param.qualifiers, FreeSpecifier);
11767
11768                               param.qualifiers = MkListOne(MkSpecifier(VOID));
11769                               if(!d || d.type != pointerDeclarator)
11770                                  param.qualifiers->Insert(null, MkSpecifier(CONST));
11771                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11772                               break;
11773                            }
11774                            else if(spec.specifier == THISCLASS)
11775                            {
11776                               if(thisClass)
11777                               {
11778                                  spec.type = nameSpecifier;
11779                                  spec.name = ReplaceThisClass(thisClass);
11780                                  spec.symbol = FindClass(spec.name);
11781                                  ProcessSpecifier(spec, false, false);
11782                               }
11783                               break;
11784                            }
11785                         }
11786                         else if(spec.type == nameSpecifier)
11787                         {
11788                            ProcessSpecifier(spec, isFunction, true);
11789                         }
11790                         else if((spec.type == structSpecifier || spec.type == unionSpecifier) && !spec.definitions && spec.id && spec.id.string)
11791                         {
11792                            Declarator d = param.declarator;
11793                            if(!d || d.type != pointerDeclarator)
11794                               DeclareStruct(curExternal, spec.id.string, false, true);
11795                         }
11796                      }
11797                   }
11798
11799                   if(param.declarator)
11800                      ProcessDeclarator(param.declarator, false);
11801                }
11802             }
11803          }
11804          break;
11805       }
11806    }
11807 }
11808
11809 static void ProcessDeclaration(Declaration decl, bool warnClasses)
11810 {
11811    yylloc = decl.loc;
11812    switch(decl.type)
11813    {
11814       case initDeclaration:
11815       {
11816          bool declareStruct = false;
11817          /*
11818          lineNum = decl.pos.line;
11819          column = decl.pos.col;
11820          */
11821
11822          if(decl.declarators)
11823          {
11824             InitDeclarator d;
11825
11826             for(d = decl.declarators->first; d; d = d.next)
11827             {
11828                Type type, subType;
11829                ProcessDeclarator(d.declarator, false);
11830
11831                type = ProcessType(decl.specifiers, d.declarator);
11832
11833                if(d.initializer)
11834                {
11835                   ProcessInitializer(d.initializer, type);
11836
11837                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11838
11839                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11840                      d.initializer.exp.type == instanceExp)
11841                   {
11842                      if(type.kind == classType && type._class ==
11843                         d.initializer.exp.expType._class)
11844                      {
11845                         Instantiation inst = d.initializer.exp.instance;
11846                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11847
11848                         d.initializer.exp.instance = null;
11849                         if(decl.specifiers)
11850                            FreeList(decl.specifiers, FreeSpecifier);
11851                         FreeList(decl.declarators, FreeInitDeclarator);
11852
11853                         d = null;
11854
11855                         decl.type = instDeclaration;
11856                         decl.inst = inst;
11857                      }
11858                   }
11859                }
11860                for(subType = type; subType;)
11861                {
11862                   if(subType.kind == classType)
11863                   {
11864                      declareStruct = true;
11865                      break;
11866                   }
11867                   else if(subType.kind == pointerType)
11868                      break;
11869                   else if(subType.kind == arrayType)
11870                      subType = subType.arrayType;
11871                   else
11872                      break;
11873                }
11874
11875                FreeType(type);
11876                if(!d) break;
11877             }
11878          }
11879
11880          if(decl.specifiers)
11881          {
11882             Specifier s;
11883             for(s = decl.specifiers->first; s; s = s.next)
11884             {
11885                ProcessSpecifier(s, declareStruct, true);
11886             }
11887          }
11888          break;
11889       }
11890       case instDeclaration:
11891       {
11892          ProcessInstantiationType(decl.inst);
11893          break;
11894       }
11895       case structDeclaration:
11896       {
11897          Specifier spec;
11898          Declarator d;
11899          bool declareStruct = false;
11900
11901          if(decl.declarators)
11902          {
11903             for(d = decl.declarators->first; d; d = d.next)
11904             {
11905                Type type = ProcessType(decl.specifiers, d.declarator);
11906                Type subType;
11907                ProcessDeclarator(d, false);
11908                for(subType = type; subType;)
11909                {
11910                   if(subType.kind == classType)
11911                   {
11912                      declareStruct = true;
11913                      break;
11914                   }
11915                   else if(subType.kind == pointerType)
11916                      break;
11917                   else if(subType.kind == arrayType)
11918                      subType = subType.arrayType;
11919                   else
11920                      break;
11921                }
11922                FreeType(type);
11923             }
11924          }
11925          if(decl.specifiers)
11926          {
11927             for(spec = decl.specifiers->first; spec; spec = spec.next)
11928                ProcessSpecifier(spec, declareStruct, warnClasses);
11929          }
11930          break;
11931       }
11932    }
11933 }
11934
11935 static FunctionDefinition curFunction;
11936
11937 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11938 {
11939    char propName[1024], propNameM[1024];
11940    char getName[1024], setName[1024];
11941    OldList * args;
11942
11943    DeclareProperty(curExternal, prop, setName, getName);
11944
11945    // eInstance_FireWatchers(object, prop);
11946    strcpy(propName, "__ecereProp_");
11947    FullClassNameCat(propName, prop._class.fullName, false);
11948    strcat(propName, "_");
11949    FullClassNameCat(propName, prop.name, true);
11950
11951    strcpy(propNameM, "__ecerePropM_");
11952    FullClassNameCat(propNameM, prop._class.fullName, false);
11953    strcat(propNameM, "_");
11954    FullClassNameCat(propNameM, prop.name, true);
11955
11956    if(prop.isWatchable)
11957    {
11958       args = MkList();
11959       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11960       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11961       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11962
11963       args = MkList();
11964       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11965       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11966       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11967
11968       DeclareFunctionUtil(curExternal, "eInstance_FireWatchers");
11969    }
11970
11971    {
11972       args = MkList();
11973       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11974       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11975       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11976
11977       args = MkList();
11978       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11979       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11980       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11981
11982       DeclareFunctionUtil(curExternal, "eInstance_FireSelfWatchers");
11983    }
11984
11985    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11986       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11987       curFunction.propSet.fireWatchersDone = true;
11988 }
11989
11990 static void ProcessStatement(Statement stmt)
11991 {
11992    yylloc = stmt.loc;
11993    /*
11994    lineNum = stmt.pos.line;
11995    column = stmt.pos.col;
11996    */
11997    switch(stmt.type)
11998    {
11999       case labeledStmt:
12000          ProcessStatement(stmt.labeled.stmt);
12001          break;
12002       case caseStmt:
12003          // This expression should be constant...
12004          if(stmt.caseStmt.exp)
12005          {
12006             FreeType(stmt.caseStmt.exp.destType);
12007             stmt.caseStmt.exp.destType = curSwitchType;
12008             if(curSwitchType) curSwitchType.refCount++;
12009             ProcessExpressionType(stmt.caseStmt.exp);
12010             ComputeExpression(stmt.caseStmt.exp);
12011          }
12012          if(stmt.caseStmt.stmt)
12013             ProcessStatement(stmt.caseStmt.stmt);
12014          break;
12015       case compoundStmt:
12016       {
12017          if(stmt.compound.context)
12018          {
12019             Declaration decl;
12020             Statement s;
12021
12022             Statement prevCompound = curCompound;
12023             Context prevContext = curContext;
12024
12025             if(!stmt.compound.isSwitch)
12026                curCompound = stmt;
12027             curContext = stmt.compound.context;
12028
12029             if(stmt.compound.declarations)
12030             {
12031                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
12032                   ProcessDeclaration(decl, true);
12033             }
12034             if(stmt.compound.statements)
12035             {
12036                for(s = stmt.compound.statements->first; s; s = s.next)
12037                   ProcessStatement(s);
12038             }
12039
12040             curContext = prevContext;
12041             curCompound = prevCompound;
12042          }
12043          break;
12044       }
12045       case expressionStmt:
12046       {
12047          Expression exp;
12048          if(stmt.expressions)
12049          {
12050             for(exp = stmt.expressions->first; exp; exp = exp.next)
12051                ProcessExpressionType(exp);
12052          }
12053          break;
12054       }
12055       case ifStmt:
12056       {
12057          Expression exp;
12058
12059          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
12060          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
12061          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
12062          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
12063          {
12064             ProcessExpressionType(exp);
12065          }
12066          if(stmt.ifStmt.stmt)
12067             ProcessStatement(stmt.ifStmt.stmt);
12068          if(stmt.ifStmt.elseStmt)
12069             ProcessStatement(stmt.ifStmt.elseStmt);
12070          break;
12071       }
12072       case switchStmt:
12073       {
12074          Type oldSwitchType = curSwitchType;
12075          if(stmt.switchStmt.exp)
12076          {
12077             Expression exp;
12078             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
12079             {
12080                if(!exp.next)
12081                {
12082                   /*
12083                   Type destType
12084                   {
12085                      kind = intType;
12086                      refCount = 1;
12087                   };
12088                   e.exp.destType = destType;
12089                   */
12090
12091                   ProcessExpressionType(exp);
12092                }
12093                if(!exp.next)
12094                   curSwitchType = exp.expType;
12095             }
12096          }
12097          ProcessStatement(stmt.switchStmt.stmt);
12098          curSwitchType = oldSwitchType;
12099          break;
12100       }
12101       case whileStmt:
12102       {
12103          if(stmt.whileStmt.exp)
12104          {
12105             Expression exp;
12106
12107             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
12108             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
12109             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
12110             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
12111             {
12112                ProcessExpressionType(exp);
12113             }
12114          }
12115          if(stmt.whileStmt.stmt)
12116             ProcessStatement(stmt.whileStmt.stmt);
12117          break;
12118       }
12119       case doWhileStmt:
12120       {
12121          if(stmt.doWhile.exp)
12122          {
12123             Expression exp;
12124
12125             if(stmt.doWhile.exp->last)
12126             {
12127                FreeType(((Expression)stmt.doWhile.exp->last).destType);
12128                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
12129                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
12130             }
12131             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
12132             {
12133                ProcessExpressionType(exp);
12134             }
12135          }
12136          if(stmt.doWhile.stmt)
12137             ProcessStatement(stmt.doWhile.stmt);
12138          break;
12139       }
12140       case forStmt:
12141       {
12142          Expression exp;
12143          if(stmt.forStmt.init)
12144             ProcessStatement(stmt.forStmt.init);
12145
12146          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
12147          {
12148             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
12149             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
12150             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
12151          }
12152
12153          if(stmt.forStmt.check)
12154             ProcessStatement(stmt.forStmt.check);
12155          if(stmt.forStmt.increment)
12156          {
12157             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
12158                ProcessExpressionType(exp);
12159          }
12160
12161          if(stmt.forStmt.stmt)
12162             ProcessStatement(stmt.forStmt.stmt);
12163          break;
12164       }
12165       case forEachStmt:
12166       {
12167          Identifier id = stmt.forEachStmt.id;
12168          OldList * exp = stmt.forEachStmt.exp;
12169          OldList * filter = stmt.forEachStmt.filter;
12170          Statement block = stmt.forEachStmt.stmt;
12171          char iteratorType[1024];
12172          Type source;
12173          Expression e;
12174          bool isBuiltin = exp && exp->last &&
12175             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12176               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12177          Expression arrayExp;
12178          const char * typeString = null;
12179          int builtinCount = 0;
12180
12181          for(e = exp ? exp->first : null; e; e = e.next)
12182          {
12183             if(!e.next)
12184             {
12185                FreeType(e.destType);
12186                e.destType = ProcessTypeString("Container", false);
12187             }
12188             if(!isBuiltin || e.next)
12189                ProcessExpressionType(e);
12190          }
12191
12192          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12193          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12194             eClass_IsDerived(source._class.registered, containerClass)))
12195          {
12196             Class _class = source ? source._class.registered : null;
12197             Symbol symbol;
12198             Expression expIt = null;
12199             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12200             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12201             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12202             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12203
12204             if(inCompiler)
12205             {
12206                stmt.type = compoundStmt;
12207
12208                stmt.compound.context = Context { };
12209                stmt.compound.context.parent = curContext;
12210                curContext = stmt.compound.context;
12211             }
12212
12213             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12214             {
12215                Class mapClass = eSystem_FindClass(privateModule, "Map");
12216                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12217                isCustomAVLTree = true;
12218                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12219                   isAVLTree = true;
12220                else */if(eClass_IsDerived(source._class.registered, mapClass))
12221                   isMap = true;
12222             }
12223             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12224             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12225             {
12226                Class listClass = eSystem_FindClass(privateModule, "List");
12227                isLinkList = true;
12228                isList = eClass_IsDerived(source._class.registered, listClass);
12229             }
12230
12231             if(inCompiler && isArray)
12232             {
12233                Declarator decl;
12234                OldList * specs = MkList();
12235                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12236                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12237                stmt.compound.declarations = MkListOne(
12238                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12239                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12240                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12241                      MkInitializerAssignment(MkExpBrackets(exp))))));
12242             }
12243             else if(isBuiltin)
12244             {
12245                Type type = null;
12246                char typeStringBuf[1024];
12247
12248                // TODO: Merge this code?
12249                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12250                if(((Expression)exp->last).type == castExp)
12251                {
12252                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12253                   if(typeName)
12254                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12255                }
12256
12257                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12258                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12259                   arrayExp.destType._class.registered.templateArgs)
12260                {
12261                   Class templateClass = arrayExp.destType._class.registered;
12262                   typeString = templateClass.templateArgs[2].dataTypeString;
12263                }
12264                else if(arrayExp.list)
12265                {
12266                   // Guess type from expressions in the array
12267                   Expression e;
12268                   for(e = arrayExp.list->first; e; e = e.next)
12269                   {
12270                      ProcessExpressionType(e);
12271                      if(e.expType)
12272                      {
12273                         if(!type) { type = e.expType; type.refCount++; }
12274                         else
12275                         {
12276                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12277                            if(!MatchTypeExpression(e, type, null, false, true))
12278                            {
12279                               FreeType(type);
12280                               type = e.expType;
12281                               e.expType = null;
12282
12283                               e = arrayExp.list->first;
12284                               ProcessExpressionType(e);
12285                               if(e.expType)
12286                               {
12287                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12288                                  if(!MatchTypeExpression(e, type, null, false, true))
12289                                  {
12290                                     FreeType(e.expType);
12291                                     e.expType = null;
12292                                     FreeType(type);
12293                                     type = null;
12294                                     break;
12295                                  }
12296                               }
12297                            }
12298                         }
12299                         if(e.expType)
12300                         {
12301                            FreeType(e.expType);
12302                            e.expType = null;
12303                         }
12304                      }
12305                   }
12306                   if(type)
12307                   {
12308                      typeStringBuf[0] = '\0';
12309                      PrintType(type, typeStringBuf, false, true);
12310                      typeString = typeStringBuf;
12311                      FreeType(type);
12312                   }
12313                }
12314                if(typeString)
12315                {
12316                   if(inCompiler)
12317                   {
12318                      OldList * initializers = MkList();
12319                      Declarator decl;
12320                      OldList * specs = MkList();
12321                      if(arrayExp.list)
12322                      {
12323                         Expression e;
12324
12325                         builtinCount = arrayExp.list->count;
12326                         type = ProcessTypeString(typeString, false);
12327                         while((e = arrayExp.list->first))
12328                         {
12329                            arrayExp.list->Remove(e);
12330                            e.destType = type;
12331                            type.refCount++;
12332                            ProcessExpressionType(e);
12333                            if(inCompiler)
12334                               ListAdd(initializers, MkInitializerAssignment(e));
12335                         }
12336                         FreeType(type);
12337                         delete arrayExp.list;
12338                      }
12339                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12340
12341                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12342                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12343
12344                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12345                         PlugDeclarator(
12346                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12347                            ), MkInitializerList(initializers)))));
12348                      FreeList(exp, FreeExpression);
12349                   }
12350                   else if(arrayExp.list)
12351                   {
12352                      Expression e;
12353                      type = ProcessTypeString(typeString, false);
12354                      for(e = arrayExp.list->first; e; e = e.next)
12355                      {
12356                         e.destType = type;
12357                         type.refCount++;
12358                         ProcessExpressionType(e);
12359                      }
12360                      FreeType(type);
12361                   }
12362                }
12363                else
12364                {
12365                   arrayExp.expType = ProcessTypeString("Container", false);
12366                   Compiler_Error($"Couldn't determine type of array elements\n");
12367                }
12368
12369                /*
12370                Declarator decl;
12371                OldList * specs = MkList();
12372
12373                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12374                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12375                stmt.compound.declarations = MkListOne(
12376                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12377                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12378                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12379                      MkInitializerAssignment(MkExpBrackets(exp))))));
12380                */
12381             }
12382             else if(inCompiler && isLinkList && !isList)
12383             {
12384                Declarator decl;
12385                OldList * specs = MkList();
12386                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12387                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12388                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12389                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12390                      MkInitializerAssignment(MkExpBrackets(exp))))));
12391             }
12392             /*else if(isCustomAVLTree)
12393             {
12394                Declarator decl;
12395                OldList * specs = MkList();
12396                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12397                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12398                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12399                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12400                      MkInitializerAssignment(MkExpBrackets(exp))))));
12401             }*/
12402             else if(inCompiler && _class.templateArgs)
12403             {
12404                if(isMap)
12405                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12406                else
12407                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12408
12409                stmt.compound.declarations = MkListOne(
12410                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12411                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12412                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12413             }
12414             if(inCompiler)
12415             {
12416                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12417
12418                if(block)
12419                {
12420                   // Reparent sub-contexts in this statement
12421                   switch(block.type)
12422                   {
12423                      case compoundStmt:
12424                         if(block.compound.context)
12425                            block.compound.context.parent = stmt.compound.context;
12426                         break;
12427                      case ifStmt:
12428                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12429                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12430                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12431                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12432                         break;
12433                      case switchStmt:
12434                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12435                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12436                         break;
12437                      case whileStmt:
12438                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12439                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12440                         break;
12441                      case doWhileStmt:
12442                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12443                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12444                         break;
12445                      case forStmt:
12446                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12447                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12448                         break;
12449                      case forEachStmt:
12450                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12451                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12452                         break;
12453                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12454                      case labeledStmt:
12455                      case caseStmt
12456                      case expressionStmt:
12457                      case gotoStmt:
12458                      case continueStmt:
12459                      case breakStmt
12460                      case returnStmt:
12461                      case asmStmt:
12462                      case badDeclarationStmt:
12463                      case fireWatchersStmt:
12464                      case stopWatchingStmt:
12465                      case watchStmt:
12466                      */
12467                   }
12468                }
12469
12470                if(filter)
12471                {
12472                   block = MkIfStmt(filter, block, null);
12473                }
12474                if(isArray)
12475                {
12476                   stmt.compound.statements = MkListOne(MkForStmt(
12477                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12478                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12479                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12480                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12481                      block));
12482                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12483                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12484                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12485                }
12486                else if(isBuiltin)
12487                {
12488                   char count[128];
12489                   //OldList * specs = MkList();
12490                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12491
12492                   sprintf(count, "%d", builtinCount);
12493
12494                   stmt.compound.statements = MkListOne(MkForStmt(
12495                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12496                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12497                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12498                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12499                      block));
12500
12501                   /*
12502                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12503                   stmt.compound.statements = MkListOne(MkForStmt(
12504                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12505                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12506                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12507                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12508                      block));
12509                  */
12510                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12511                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12512                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12513                }
12514                else if(isLinkList && !isList)
12515                {
12516                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12517                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12518                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12519                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12520                   {
12521                      stmt.compound.statements = MkListOne(MkForStmt(
12522                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12523                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12524                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12525                         block));
12526                   }
12527                   else
12528                   {
12529                      OldList * specs = MkList();
12530                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12531                      stmt.compound.statements = MkListOne(MkForStmt(
12532                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12533                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12534                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12535                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12536                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12537                         block));
12538                   }
12539                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12540                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12541                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12542                }
12543                /*else if(isCustomAVLTree)
12544                {
12545                   stmt.compound.statements = MkListOne(MkForStmt(
12546                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12547                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12548                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12549                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12550                      block));
12551
12552                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12553                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12554                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12555                }*/
12556                else
12557                {
12558                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12559                      MkIdentifier("Next")), null)), block));
12560                }
12561                ProcessExpressionType(expIt);
12562                if(stmt.compound.declarations->first)
12563                   ProcessDeclaration(stmt.compound.declarations->first, true);
12564
12565                if(symbol)
12566                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12567
12568                ProcessStatement(stmt);
12569             }
12570             else
12571                ProcessStatement(stmt.forEachStmt.stmt);
12572             if(inCompiler)
12573                curContext = stmt.compound.context.parent;
12574             break;
12575          }
12576          else
12577          {
12578             Compiler_Error($"Expression is not a container\n");
12579          }
12580          break;
12581       }
12582       case gotoStmt:
12583          break;
12584       case continueStmt:
12585          break;
12586       case breakStmt:
12587          break;
12588       case returnStmt:
12589       {
12590          Expression exp;
12591          if(stmt.expressions)
12592          {
12593             for(exp = stmt.expressions->first; exp; exp = exp.next)
12594             {
12595                if(!exp.next)
12596                {
12597                   if(curFunction && !curFunction.type)
12598                      curFunction.type = ProcessType(
12599                         curFunction.specifiers, curFunction.declarator);
12600                   FreeType(exp.destType);
12601                   // TODO: current property if not compiling
12602                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12603                   if(exp.destType) exp.destType.refCount++;
12604                }
12605                ProcessExpressionType(exp);
12606             }
12607          }
12608          break;
12609       }
12610       case badDeclarationStmt:
12611       {
12612          ProcessDeclaration(stmt.decl, true);
12613          break;
12614       }
12615       case asmStmt:
12616       {
12617          AsmField field;
12618          if(stmt.asmStmt.inputFields)
12619          {
12620             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12621                if(field.expression)
12622                   ProcessExpressionType(field.expression);
12623          }
12624          if(stmt.asmStmt.outputFields)
12625          {
12626             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12627                if(field.expression)
12628                   ProcessExpressionType(field.expression);
12629          }
12630          if(stmt.asmStmt.clobberedFields)
12631          {
12632             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12633             {
12634                if(field.expression)
12635                   ProcessExpressionType(field.expression);
12636             }
12637          }
12638          break;
12639       }
12640       case watchStmt:
12641       {
12642          PropertyWatch propWatch;
12643          OldList * watches = stmt._watch.watches;
12644          Expression object = stmt._watch.object;
12645          Expression watcher = stmt._watch.watcher;
12646          if(watcher)
12647             ProcessExpressionType(watcher);
12648          if(object)
12649             ProcessExpressionType(object);
12650
12651          if(inCompiler)
12652          {
12653             if(watcher || thisClass)
12654             {
12655                External external = curExternal;
12656                Context context = curContext;
12657
12658                stmt.type = expressionStmt;
12659                stmt.expressions = MkList();
12660
12661                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12662                {
12663                   ClassFunction func;
12664                   char watcherName[1024];
12665                   Class watcherClass = watcher ?
12666                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12667                   External createdExternal;
12668
12669                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12670                   if(propWatch.deleteWatch)
12671                      strcat(watcherName, "_delete");
12672                   else
12673                   {
12674                      Identifier propID;
12675                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12676                      {
12677                         strcat(watcherName, "_");
12678                         strcat(watcherName, propID.string);
12679                      }
12680                   }
12681
12682                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12683                   {
12684                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12685                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12686                      ProcessClassFunctionBody(func, propWatch.compound);
12687                      propWatch.compound = null;
12688
12689                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12690
12691                      FreeClassFunction(func);
12692
12693                      curExternal = createdExternal;
12694                      ProcessFunction(createdExternal.function);
12695
12696                      if(propWatch.deleteWatch)
12697                      {
12698                         OldList * args = MkList();
12699                         ListAdd(args, CopyExpression(object));
12700                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12701                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12702                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12703                      }
12704                      else
12705                      {
12706                         Class _class = object.expType._class.registered;
12707                         Identifier propID;
12708
12709                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12710                         {
12711                            char propName[1024];
12712                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12713                            if(prop)
12714                            {
12715                               char getName[1024], setName[1024];
12716                               OldList * args = MkList();
12717
12718                               DeclareProperty(createdExternal, prop, setName, getName);
12719
12720                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12721                               strcpy(propName, "__ecereProp_");
12722                               FullClassNameCat(propName, prop._class.fullName, false);
12723                               strcat(propName, "_");
12724                               FullClassNameCat(propName, prop.name, true);
12725
12726                               ListAdd(args, CopyExpression(object));
12727                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12728                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12729                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12730
12731                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12732
12733                               external.CreateUniqueEdge(createdExternal, true);
12734                            }
12735                            else
12736                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12737                         }
12738                      }
12739                   }
12740                   else
12741                      Compiler_Error($"Invalid watched object\n");
12742                }
12743
12744                curExternal = external;
12745                curContext = context;
12746
12747                if(watcher)
12748                   FreeExpression(watcher);
12749                if(object)
12750                   FreeExpression(object);
12751                FreeList(watches, FreePropertyWatch);
12752             }
12753             else
12754                Compiler_Error($"No observer specified and not inside a class\n");
12755          }
12756          else
12757          {
12758             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12759             {
12760                ProcessStatement(propWatch.compound);
12761             }
12762
12763          }
12764          break;
12765       }
12766       case fireWatchersStmt:
12767       {
12768          OldList * watches = stmt._watch.watches;
12769          Expression object = stmt._watch.object;
12770          Class _class;
12771          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12772          // printf("%X\n", watches);
12773          // printf("%X\n", stmt._watch.watches);
12774          if(object)
12775             ProcessExpressionType(object);
12776
12777          if(inCompiler)
12778          {
12779             _class = object ?
12780                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12781
12782             if(_class)
12783             {
12784                Identifier propID;
12785
12786                stmt.type = expressionStmt;
12787                stmt.expressions = MkList();
12788
12789                // Check if we're inside a property set
12790                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12791                {
12792                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12793                }
12794                else if(!watches)
12795                {
12796                   //Compiler_Error($"No property specified and not inside a property set\n");
12797                }
12798                if(watches)
12799                {
12800                   for(propID = watches->first; propID; propID = propID.next)
12801                   {
12802                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12803                      if(prop)
12804                      {
12805                         CreateFireWatcher(prop, object, stmt);
12806                      }
12807                      else
12808                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12809                   }
12810                }
12811                else
12812                {
12813                   // Fire all properties!
12814                   Property prop;
12815                   Class base;
12816                   for(base = _class; base; base = base.base)
12817                   {
12818                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12819                      {
12820                         if(prop.isProperty && prop.isWatchable)
12821                         {
12822                            CreateFireWatcher(prop, object, stmt);
12823                         }
12824                      }
12825                   }
12826                }
12827
12828                if(object)
12829                   FreeExpression(object);
12830                FreeList(watches, FreeIdentifier);
12831             }
12832             else
12833                Compiler_Error($"Invalid object specified and not inside a class\n");
12834          }
12835          break;
12836       }
12837       case stopWatchingStmt:
12838       {
12839          OldList * watches = stmt._watch.watches;
12840          Expression object = stmt._watch.object;
12841          Expression watcher = stmt._watch.watcher;
12842          Class _class;
12843          if(object)
12844             ProcessExpressionType(object);
12845          if(watcher)
12846             ProcessExpressionType(watcher);
12847          if(inCompiler)
12848          {
12849             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12850
12851             if(watcher || thisClass)
12852             {
12853                if(_class)
12854                {
12855                   Identifier propID;
12856
12857                   stmt.type = expressionStmt;
12858                   stmt.expressions = MkList();
12859
12860                   if(!watches)
12861                   {
12862                      OldList * args;
12863                      // eInstance_StopWatching(object, null, watcher);
12864                      args = MkList();
12865                      ListAdd(args, CopyExpression(object));
12866                      ListAdd(args, MkExpConstant("0"));
12867                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12868                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12869                   }
12870                   else
12871                   {
12872                      for(propID = watches->first; propID; propID = propID.next)
12873                      {
12874                         char propName[1024];
12875                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12876                         if(prop)
12877                         {
12878                            char getName[1024], setName[1024];
12879                            OldList * args = MkList();
12880
12881                            DeclareProperty(curExternal, prop, setName, getName);
12882
12883                            // eInstance_StopWatching(object, prop, watcher);
12884                            strcpy(propName, "__ecereProp_");
12885                            FullClassNameCat(propName, prop._class.fullName, false);
12886                            strcat(propName, "_");
12887                            FullClassNameCat(propName, prop.name, true);
12888
12889                            ListAdd(args, CopyExpression(object));
12890                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12891                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12892                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12893                         }
12894                         else
12895                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12896                      }
12897                   }
12898
12899                   if(object)
12900                      FreeExpression(object);
12901                   if(watcher)
12902                      FreeExpression(watcher);
12903                   FreeList(watches, FreeIdentifier);
12904                }
12905                else
12906                   Compiler_Error($"Invalid object specified and not inside a class\n");
12907             }
12908             else
12909                Compiler_Error($"No observer specified and not inside a class\n");
12910          }
12911          break;
12912       }
12913    }
12914 }
12915
12916 static void ProcessFunction(FunctionDefinition function)
12917 {
12918    Identifier id = GetDeclId(function.declarator);
12919    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12920    Type type = symbol ? symbol.type : null;
12921    Class oldThisClass = thisClass;
12922    Context oldTopContext = topContext;
12923
12924    yylloc = function.loc;
12925    // Process thisClass
12926
12927    if(type && type.thisClass)
12928    {
12929       Symbol classSym = type.thisClass;
12930       Class _class = type.thisClass.registered;
12931       char className[1024];
12932       char structName[1024];
12933       Declarator funcDecl;
12934       Symbol thisSymbol;
12935
12936       bool typedObject = false;
12937
12938       if(_class && !_class.base)
12939       {
12940          _class = currentClass;
12941          if(_class && !_class.symbol)
12942             _class.symbol = FindClass(_class.fullName);
12943          classSym = _class ? _class.symbol : null;
12944          typedObject = true;
12945       }
12946
12947       thisClass = _class;
12948
12949       if(inCompiler && _class)
12950       {
12951          if(type.kind == functionType)
12952          {
12953             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12954             {
12955                //TypeName param = symbol.type.params.first;
12956                Type param = symbol.type.params.first;
12957                symbol.type.params.Remove(param);
12958                //FreeTypeName(param);
12959                FreeType(param);
12960             }
12961             if(type.classObjectType != classPointer)
12962             {
12963                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12964                symbol.type.staticMethod = true;
12965                symbol.type.thisClass = null;
12966
12967                // HIGH DANGER: VERIFYING THIS...
12968                symbol.type.extraParam = false;
12969             }
12970          }
12971
12972          strcpy(className, "__ecereClass_");
12973          FullClassNameCat(className, _class.fullName, true);
12974
12975          structName[0] = 0;
12976          FullClassNameCat(structName, _class.fullName, false);
12977
12978          // [class] this
12979          funcDecl = GetFuncDecl(function.declarator);
12980          if(funcDecl)
12981          {
12982             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12983             {
12984                TypeName param = funcDecl.function.parameters->first;
12985                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12986                {
12987                   funcDecl.function.parameters->Remove(param);
12988                   FreeTypeName(param);
12989                }
12990             }
12991
12992             if(!function.propertyNoThis)
12993             {
12994                TypeName thisParam = null;
12995
12996                if(type.classObjectType != classPointer)
12997                {
12998                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12999                   if(!funcDecl.function.parameters)
13000                      funcDecl.function.parameters = MkList();
13001                   funcDecl.function.parameters->Insert(null, thisParam);
13002                }
13003
13004                if(typedObject)
13005                {
13006                   if(type.classObjectType != classPointer)
13007                   {
13008                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
13009                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
13010                   }
13011
13012                   thisParam = TypeName
13013                   {
13014                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
13015                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
13016                   };
13017                   DeclareStruct(curExternal, "ecere::com::Class", false, true);
13018                   funcDecl.function.parameters->Insert(null, thisParam);
13019                }
13020             }
13021          }
13022
13023          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13024          {
13025             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13026             funcDecl = GetFuncDecl(initDecl.declarator);
13027             if(funcDecl)
13028             {
13029                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
13030                {
13031                   TypeName param = funcDecl.function.parameters->first;
13032                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
13033                   {
13034                      funcDecl.function.parameters->Remove(param);
13035                      FreeTypeName(param);
13036                   }
13037                }
13038
13039                if(type.classObjectType != classPointer)
13040                {
13041                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
13042                   {
13043                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
13044
13045                      if(!funcDecl.function.parameters)
13046                         funcDecl.function.parameters = MkList();
13047                      funcDecl.function.parameters->Insert(null, thisParam);
13048                   }
13049                }
13050             }
13051          }
13052       }
13053
13054       // Add this to the context
13055       if(function.body)
13056       {
13057          if(type.classObjectType != classPointer)
13058          {
13059             thisSymbol = Symbol
13060             {
13061                string = CopyString("this");
13062                type = classSym ? MkClassType(classSym.string) : null;
13063             };
13064             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
13065
13066             if(typedObject && thisSymbol.type)
13067             {
13068                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
13069                thisSymbol.type.byReference = type.byReference;
13070                thisSymbol.type.typedByReference = type.byReference;
13071             }
13072          }
13073       }
13074
13075       // Pointer to class data
13076       if(inCompiler && _class && _class.type == normalClass && type.classObjectType != classPointer)
13077       {
13078          DataMember member = null;
13079          {
13080             Class base;
13081             for(base = _class; base && base.type != systemClass; base = base.next)
13082             {
13083                for(member = base.membersAndProperties.first; member; member = member.next)
13084                   if(!member.isProperty)
13085                      break;
13086                if(member)
13087                   break;
13088             }
13089          }
13090          for(member = _class.membersAndProperties.first; member; member = member.next)
13091             if(!member.isProperty)
13092                break;
13093          if(member)
13094          {
13095             char pointerName[1024];
13096
13097             Declaration decl;
13098             Initializer initializer;
13099             Expression exp, bytePtr;
13100
13101             strcpy(pointerName, "__ecerePointer_");
13102             FullClassNameCat(pointerName, _class.fullName, false);
13103             {
13104                char className[1024];
13105                strcpy(className, "__ecereClass_");
13106                FullClassNameCat(className, classSym.string, true);
13107
13108                DeclareClass(curExternal, classSym, className);
13109             }
13110
13111             // ((byte *) this)
13112             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
13113
13114             if(_class.fixed)
13115             {
13116                Expression e;
13117                if(_class.offset && _class.offset == (_class.base.type == noHeadClass ? _class.base.memberOffset : _class.base.structSize))
13118                {
13119                   e = MkExpClassSize(MkSpecifierName(_class.base.fullName));
13120                   ProcessExpressionType(e);
13121                }
13122                else
13123                {
13124                   char string[256];
13125                   sprintf(string, "%d", _class.offset);  // Need Bootstrap Fix
13126                   e = MkExpConstant(string);
13127                }
13128                exp = QBrackets(MkExpOp(bytePtr, '+', e));
13129             }
13130             else
13131             {
13132                // ([bytePtr] + [className]->offset)
13133                exp = QBrackets(MkExpOp(bytePtr, '+',
13134                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
13135             }
13136
13137             // (this ? [exp] : 0)
13138             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
13139             exp.expType = Type
13140             {
13141                refCount = 1;
13142                kind = pointerType;
13143                type = Type { refCount = 1, kind = voidType };
13144             };
13145
13146             if(function.body)
13147             {
13148                yylloc = function.body.loc;
13149                // ([structName] *) [exp]
13150                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13151                initializer = MkInitializerAssignment(
13152                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13153
13154                // [structName] * [pointerName] = [initializer];
13155                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13156
13157                {
13158                   Context prevContext = curContext;
13159                   OldList * list;
13160                   curContext = function.body.compound.context;
13161
13162                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13163                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13164                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13165
13166                   curContext = prevContext;
13167                }
13168
13169                // WHY?
13170                decl.symbol = null;
13171
13172                if(!function.body.compound.declarations)
13173                   function.body.compound.declarations = MkList();
13174                function.body.compound.declarations->Insert(null, decl);
13175             }
13176          }
13177       }
13178
13179
13180       // Loop through the function and replace undeclared identifiers
13181       // which are a member of the class (methods, properties or data)
13182       // by "this.[member]"
13183    }
13184    else
13185       thisClass = null;
13186
13187    if(id)
13188    {
13189       FreeSpecifier(id._class);
13190       id._class = null;
13191
13192       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13193       {
13194          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13195          id = GetDeclId(initDecl.declarator);
13196
13197          FreeSpecifier(id._class);
13198          id._class = null;
13199       }
13200    }
13201    if(function.body)
13202       topContext = function.body.compound.context;
13203    {
13204       FunctionDefinition oldFunction = curFunction;
13205       curFunction = function;
13206       if(function.body)
13207          ProcessStatement(function.body);
13208
13209       // If this is a property set and no firewatchers has been done yet, add one here
13210       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13211       {
13212          Statement prevCompound = curCompound;
13213          Context prevContext = curContext;
13214
13215          Statement fireWatchers = MkFireWatchersStmt(null, null);
13216          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13217          ListAdd(function.body.compound.statements, fireWatchers);
13218
13219          curCompound = function.body;
13220          curContext = function.body.compound.context;
13221
13222          ProcessStatement(fireWatchers);
13223
13224          curContext = prevContext;
13225          curCompound = prevCompound;
13226
13227       }
13228
13229       curFunction = oldFunction;
13230    }
13231
13232    if(function.declarator)
13233    {
13234       ProcessDeclarator(function.declarator, true);
13235    }
13236
13237    topContext = oldTopContext;
13238    thisClass = oldThisClass;
13239 }
13240
13241 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13242 static void ProcessClass(OldList definitions, Symbol symbol)
13243 {
13244    ClassDef def;
13245    External external = curExternal;
13246    Class regClass = symbol ? symbol.registered : null;
13247
13248    // Process all functions
13249    for(def = definitions.first; def; def = def.next)
13250    {
13251       if(def.type == functionClassDef)
13252       {
13253          if(def.function.declarator)
13254             curExternal = def.function.declarator.symbol.pointerExternal;
13255          else
13256             curExternal = external;
13257
13258          ProcessFunction((FunctionDefinition)def.function);
13259       }
13260       else if(def.type == declarationClassDef)
13261       {
13262          if(def.decl.type == instDeclaration)
13263          {
13264             thisClass = regClass;
13265             ProcessInstantiationType(def.decl.inst);
13266             thisClass = null;
13267          }
13268          // Testing this
13269          else
13270          {
13271             Class backThisClass = thisClass;
13272             if(regClass) thisClass = regClass;
13273             ProcessDeclaration(def.decl, symbol ? true : false);
13274             thisClass = backThisClass;
13275          }
13276       }
13277       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13278       {
13279          MemberInit defProperty;
13280
13281          // Add this to the context
13282          Symbol thisSymbol = Symbol
13283          {
13284             string = CopyString("this");
13285             type = regClass ? MkClassType(regClass.fullName) : null;
13286          };
13287          globalContext.symbols.Add((BTNode)thisSymbol);
13288
13289          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13290          {
13291             thisClass = regClass;
13292             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13293             thisClass = null;
13294          }
13295
13296          globalContext.symbols.Remove((BTNode)thisSymbol);
13297          FreeSymbol(thisSymbol);
13298       }
13299       else if(def.type == propertyClassDef && def.propertyDef)
13300       {
13301          PropertyDef prop = def.propertyDef;
13302
13303          // Add this to the context
13304          thisClass = regClass;
13305          if(prop.setStmt)
13306          {
13307             if(regClass)
13308             {
13309                Symbol thisSymbol
13310                {
13311                   string = CopyString("this");
13312                   type = MkClassType(regClass.fullName);
13313                };
13314                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13315             }
13316
13317             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13318             ProcessStatement(prop.setStmt);
13319          }
13320          if(prop.getStmt)
13321          {
13322             if(regClass)
13323             {
13324                Symbol thisSymbol
13325                {
13326                   string = CopyString("this");
13327                   type = MkClassType(regClass.fullName);
13328                };
13329                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13330             }
13331
13332             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13333             ProcessStatement(prop.getStmt);
13334          }
13335          if(prop.issetStmt)
13336          {
13337             if(regClass)
13338             {
13339                Symbol thisSymbol
13340                {
13341                   string = CopyString("this");
13342                   type = MkClassType(regClass.fullName);
13343                };
13344                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13345             }
13346
13347             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13348             ProcessStatement(prop.issetStmt);
13349          }
13350
13351          thisClass = null;
13352       }
13353       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13354       {
13355          PropertyWatch propertyWatch = def.propertyWatch;
13356
13357          thisClass = regClass;
13358          if(propertyWatch.compound)
13359          {
13360             Symbol thisSymbol
13361             {
13362                string = CopyString("this");
13363                type = regClass ? MkClassType(regClass.fullName) : null;
13364             };
13365
13366             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13367
13368             curExternal = null;
13369             ProcessStatement(propertyWatch.compound);
13370          }
13371          thisClass = null;
13372       }
13373    }
13374 }
13375
13376 void DeclareFunctionUtil(External neededBy, const String s)
13377 {
13378    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13379    if(function)
13380    {
13381       char name[1024];
13382       name[0] = 0;
13383       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13384          strcpy(name, "__ecereFunction_");
13385       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13386       DeclareFunction(neededBy, function, name);
13387    }
13388    else if(neededBy)
13389       FindSymbol(s, globalContext, globalContext, false, false);
13390 }
13391
13392 bool reachedPass15;
13393
13394 void ComputeDataTypes()
13395 {
13396    External external;
13397
13398    currentClass = null;
13399
13400    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13401
13402    DeclareStruct(null, "ecere::com::Class", false, true);
13403    DeclareStruct(null, "ecere::com::Instance", false, true);
13404    DeclareStruct(null, "ecere::com::Property", false, true);
13405    DeclareStruct(null, "ecere::com::DataMember", false, true);
13406    DeclareStruct(null, "ecere::com::Method", false, true);
13407    DeclareStruct(null, "ecere::com::SerialBuffer", false, true);
13408    DeclareStruct(null, "ecere::com::ClassTemplateArgument", false, true);
13409
13410    DeclareFunctionUtil(null, "eSystem_New");
13411    DeclareFunctionUtil(null, "eSystem_New0");
13412    DeclareFunctionUtil(null, "eSystem_Renew");
13413    DeclareFunctionUtil(null, "eSystem_Renew0");
13414    DeclareFunctionUtil(null, "eSystem_Delete");
13415    DeclareFunctionUtil(null, "eClass_GetProperty");
13416    DeclareFunctionUtil(null, "eClass_SetProperty");
13417    DeclareFunctionUtil(null, "eInstance_FireSelfWatchers");
13418    DeclareFunctionUtil(null, "eInstance_SetMethod");
13419    DeclareFunctionUtil(null, "eInstance_IncRef");
13420    DeclareFunctionUtil(null, "eInstance_StopWatching");
13421    DeclareFunctionUtil(null, "eInstance_Watch");
13422    DeclareFunctionUtil(null, "eInstance_FireWatchers");
13423    reachedPass15 = true;
13424
13425    for(external = ast->first; external; external = external.next)
13426    {
13427       afterExternal = curExternal = external;
13428       if(external.type == functionExternal)
13429       {
13430          if(memoryGuard)
13431          {
13432             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13433             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13434          }
13435
13436          currentClass = external.function._class;
13437          ProcessFunction(external.function);
13438       }
13439       // There shouldn't be any _class member access here anyways...
13440       else if(external.type == declarationExternal)
13441       {
13442          if(memoryGuard && external.declaration && external.declaration.type == instDeclaration)
13443          {
13444             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13445             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13446          }
13447
13448          currentClass = null;
13449          if(external.declaration)
13450             ProcessDeclaration(external.declaration, true);
13451       }
13452       else if(external.type == classExternal)
13453       {
13454          ClassDefinition _class = external._class;
13455          currentClass = external.symbol.registered;
13456          if(memoryGuard)
13457          {
13458             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13459             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13460          }
13461          if(_class.definitions)
13462          {
13463             ProcessClass(_class.definitions, _class.symbol);
13464          }
13465          if(inCompiler)
13466          {
13467             // Free class data...
13468             ast->Remove(external);
13469             delete external;
13470          }
13471       }
13472       else if(external.type == nameSpaceExternal)
13473       {
13474          thisNameSpace = external.id.string;
13475       }
13476    }
13477    currentClass = null;
13478    thisNameSpace = null;
13479    curExternal = null;
13480 }