compiler/libec: (#205) Corrections to integer promotions
[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 ? _class.base.templateClass.structSize : _class.base.structSize) : 0) + _class.memberOffset + extra;
670             if(!member)
671             {
672                Property prop;
673                for(prop = _class.membersAndProperties.first; prop; prop = prop.next)
674                {
675                   if(prop.isProperty && prop.isWatchable)
676                   {
677                      prop.watcherOffset = _class.structSize;
678                      _class.structSize += sizeof(OldList);
679                   }
680                }
681             }
682
683             // Fix Derivatives
684             {
685                OldLink derivative;
686                for(derivative = _class.derivatives.first; derivative; derivative = derivative.next)
687                {
688                   Class deriv = derivative.data;
689
690                   if(deriv.computeSize)
691                   {
692                      // TESTING THIS NEW CODE HERE... TRYING TO FIX ScrollBar MEMBERS DEBUGGING
693                      deriv.offset = /*_class.offset + */_class.structSize;
694                      deriv.memberOffset = 0;
695                      // ----------------------
696
697                      deriv.structSize = deriv.offset;
698
699                      ComputeClassMembers(deriv, false);
700                   }
701                }
702             }
703          }
704       }
705    }
706    if(context)
707       FinishTemplatesContext(context);
708 }
709
710 public void ComputeModuleClasses(Module module)
711 {
712    Class _class;
713    OldLink subModule;
714
715    for(subModule = module.modules.first; subModule; subModule = subModule.next)
716       ComputeModuleClasses(subModule.data);
717    for(_class = module.classes.first; _class; _class = _class.next)
718       ComputeClassMembers(_class, false);
719 }
720
721
722 public int ComputeTypeSize(Type type)
723 {
724    uint size = type ? type.size : 0;
725    if(!size && type && !type.computing)
726    {
727       type.computing = true;
728       switch(type.kind)
729       {
730          case _BoolType: type.alignment = size = sizeof(char); break;   // Assuming 1 byte _Bool
731          case charType: type.alignment = size = sizeof(char); break;
732          case intType: type.alignment = size = sizeof(int); break;
733          case int64Type: type.alignment = size = sizeof(int64); break;
734          case intPtrType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
735          case intSizeType: type.alignment = size = targetBits / 8; type.pointerAlignment = true; break;
736          case longType: type.alignment = size = sizeof(long); break;
737          case shortType: type.alignment = size = sizeof(short); break;
738          case floatType: type.alignment = size = sizeof(float); break;
739          case doubleType: type.alignment = size = sizeof(double); break;
740          case classType:
741          {
742             Class _class = type._class ? type._class.registered : null;
743
744             if(_class && _class.type == structClass)
745             {
746                // Ensure all members are properly registered
747                ComputeClassMembers(_class, false);
748                type.alignment = _class.structAlignment;
749                type.pointerAlignment = (bool)_class.pointerAlignment;
750                size = _class.structSize;
751                if(type.alignment && size % type.alignment)
752                   size += type.alignment - (size % type.alignment);
753
754             }
755             else if(_class && (_class.type == unitClass ||
756                    _class.type == enumClass ||
757                    _class.type == bitClass))
758             {
759                if(!_class.dataType)
760                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
761                size = type.alignment = ComputeTypeSize(_class.dataType);
762             }
763             else
764             {
765                size = type.alignment = targetBits / 8; // sizeof(Instance *);
766                type.pointerAlignment = true;
767             }
768             break;
769          }
770          case pointerType: case subClassType: size = type.alignment = targetBits / 8; /*sizeof(void *); */ type.pointerAlignment = true; break;
771          case arrayType:
772             if(type.arraySizeExp)
773             {
774                ProcessExpressionType(type.arraySizeExp);
775                ComputeExpression(type.arraySizeExp);
776                if(!type.arraySizeExp.isConstant || (type.arraySizeExp.expType.kind != intType &&
777                   type.arraySizeExp.expType.kind != shortType &&
778                   type.arraySizeExp.expType.kind != charType &&
779                   type.arraySizeExp.expType.kind != longType &&
780                   type.arraySizeExp.expType.kind != int64Type &&
781                   type.arraySizeExp.expType.kind != intSizeType &&
782                   type.arraySizeExp.expType.kind != intPtrType &&
783                   type.arraySizeExp.expType.kind != enumType &&
784                   (type.arraySizeExp.expType.kind != classType || !type.arraySizeExp.expType._class.registered || type.arraySizeExp.expType._class.registered.type != enumClass)))
785                {
786                   Location oldLoc = yylloc;
787                   // bool isConstant = type.arraySizeExp.isConstant;
788                   char expression[10240];
789                   expression[0] = '\0';
790                   type.arraySizeExp.expType = null;
791                   yylloc = type.arraySizeExp.loc;
792                   if(inCompiler)
793                      PrintExpression(type.arraySizeExp, expression);
794                   Compiler_Error($"Array size not constant int (%s)\n", expression);
795                   yylloc = oldLoc;
796                }
797                GetInt(type.arraySizeExp, &type.arraySize);
798             }
799             else if(type.enumClass)
800             {
801                if(type.enumClass && type.enumClass.registered && type.enumClass.registered.type == enumClass)
802                {
803                   type.arraySize = (int)eClass_GetProperty(type.enumClass.registered, "enumSize");
804                }
805                else
806                   type.arraySize = 0;
807             }
808             else
809             {
810                // Unimplemented auto size
811                type.arraySize = 0;
812             }
813
814             size = ComputeTypeSize(type.type) * type.arraySize;
815             if(type.type)
816             {
817                type.alignment = type.type.alignment;
818                type.pointerAlignment = type.type.pointerAlignment;
819             }
820
821             break;
822          case structType:
823          {
824             if(!type.members.first && type.enumName)
825             {
826                Symbol symbol = FindStruct(curContext, type.enumName);
827                if(symbol && symbol.type)
828                {
829                   ComputeTypeSize(symbol.type);
830                   size = symbol.type.size;
831                }
832             }
833             else
834             {
835                Type member;
836                for(member = type.members.first; member; member = member.next)
837                {
838                   uint addSize = ComputeTypeSize(member);
839
840                   member.offset = size;
841                   if(member.alignment && size % member.alignment)
842                      member.offset += member.alignment - (size % member.alignment);
843                   size = member.offset;
844
845                   if(member.pointerAlignment && type.size <= 4)
846                      type.pointerAlignment = true;
847                   else if(!member.pointerAlignment && member.alignment >= 8)
848                      type.pointerAlignment = false;
849
850                   type.alignment = Max(type.alignment, member.alignment);
851                   size += addSize;
852                }
853                if(type.alignment && size % type.alignment)
854                   size += type.alignment - (size % type.alignment);
855             }
856             break;
857          }
858          case unionType:
859          {
860             if(!type.members.first && type.enumName)
861             {
862                Symbol symbol = FindStruct(curContext, type.enumName);
863                if(symbol && symbol.type)
864                {
865                   ComputeTypeSize(symbol.type);
866                   size = symbol.type.size;
867                   type.alignment = symbol.type.alignment;
868                }
869             }
870             else
871             {
872                Type member;
873                for(member = type.members.first; member; member = member.next)
874                {
875                   uint addSize = ComputeTypeSize(member);
876
877                   member.offset = size;
878                   if(member.alignment && size % member.alignment)
879                      member.offset += member.alignment - (size % member.alignment);
880                   size = member.offset;
881
882                   if(member.pointerAlignment && type.size <= 4)
883                      type.pointerAlignment = true;
884                   else if(!member.pointerAlignment && member.alignment >= 8)
885                      type.pointerAlignment = false;
886
887                   type.alignment = Max(type.alignment, member.alignment);
888
889                   size = Max(size, addSize);
890                }
891                if(type.alignment && size % type.alignment)
892                   size += type.alignment - (size % type.alignment);
893             }
894             break;
895          }
896          case templateType:
897          {
898             TemplateParameter param = type.templateParameter;
899             Type baseType = ProcessTemplateParameterType(param);
900             if(baseType)
901             {
902                size = ComputeTypeSize(baseType);
903                type.alignment = baseType.alignment;
904                type.pointerAlignment = baseType.pointerAlignment;
905             }
906             else
907                type.alignment = size = sizeof(uint64);
908             break;
909          }
910          case enumType:
911          {
912             type.alignment = size = sizeof(enum { test });
913             break;
914          }
915          case thisClassType:
916          {
917             type.alignment = size = targetBits / 8; //sizeof(void *);
918             type.pointerAlignment = true;
919             break;
920          }
921       }
922       type.size = size;
923       type.computing = false;
924    }
925    return size;
926 }
927
928
929 /*static */int AddMembers(External neededBy, OldList * declarations, Class _class, bool isMember, uint * retSize, Class topClass, bool *addedPadding)
930 {
931    // This function is in need of a major review when implementing private members etc.
932    DataMember topMember = isMember ? (DataMember) _class : null;
933    uint totalSize = 0;
934    uint maxSize = 0;
935    int alignment;
936    uint size;
937    DataMember member;
938    int anonID = 1;
939    Context context = isMember ? null : SetupTemplatesContext(_class);
940    if(addedPadding)
941       *addedPadding = false;
942
943    if(!isMember && _class.base)
944    {
945       maxSize = _class.structSize;
946       //if(_class.base.type != systemClass) // Commented out with new Instance _class
947       {
948          // DANGER: Testing this noHeadClass here...
949          if(_class.type == structClass || _class.type == noHeadClass)
950             /*totalSize = */AddMembers(neededBy, declarations, _class.base, false, &totalSize, topClass, null);
951          else
952          {
953             uint baseSize = _class.base.templateClass ? _class.base.templateClass.structSize : _class.base.structSize;
954             if(maxSize > baseSize)
955                maxSize -= baseSize;
956             else
957                maxSize = 0;
958          }
959       }
960    }
961
962    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
963    {
964       if(!member.isProperty)
965       {
966          switch(member.type)
967          {
968             case normalMember:
969             {
970                if(member.dataTypeString)
971                {
972                   OldList * specs = MkList(), * decls = MkList();
973                   Declarator decl;
974
975                   decl = SpecDeclFromString(member.dataTypeString, specs,
976                      MkDeclaratorIdentifier(MkIdentifier(member.name)));
977                   ListAdd(decls, MkStructDeclarator(decl, null));
978                   ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, decls, null)));
979
980                   if(!member.dataType)
981                      member.dataType = ProcessType(specs, decl);
982
983                   ReplaceThisClassSpecifiers(specs, topClass /*member._class*/);
984
985                   {
986                      Type type = ProcessType(specs, decl);
987                      DeclareType(neededBy, member.dataType, true, false);
988                      FreeType(type);
989                   }
990                   /*
991                   if(member.dataType && member.dataType.kind == classType && member.dataType._class &&
992                      member.dataType._class.registered && member.dataType._class.registered.type == structClass)
993                      DeclareStruct(member.dataType._class.string, false);
994                   */
995
996                   ComputeTypeSize(member.dataType);
997                   size = member.dataType.size;
998                   alignment = member.dataType.alignment;
999
1000                   if(alignment)
1001                   {
1002                      if(totalSize % alignment)
1003                         totalSize += alignment - (totalSize % alignment);
1004                   }
1005                   totalSize += size;
1006                }
1007                break;
1008             }
1009             case unionMember:
1010             case structMember:
1011             {
1012                OldList * specs = MkList(), * list = MkList();
1013                char id[100];
1014                sprintf(id, "__anon%d", anonID++);
1015
1016                size = 0;
1017                AddMembers(neededBy, list, (Class)member, true, &size, topClass, null);
1018                ListAdd(specs,
1019                   MkStructOrUnion((member.type == unionMember)?unionSpecifier:structSpecifier, null, list));
1020                ListAdd(declarations, MkClassDefDeclaration(MkStructDeclaration(specs, MkListOne(MkDeclaratorIdentifier(MkIdentifier(id))),null)));
1021                alignment = member.structAlignment;
1022
1023                if(alignment)
1024                {
1025                   if(totalSize % alignment)
1026                      totalSize += alignment - (totalSize % alignment);
1027                }
1028                totalSize += size;
1029                break;
1030             }
1031          }
1032       }
1033    }
1034    if(retSize)
1035    {
1036       if(topMember && topMember.type == unionMember)
1037          *retSize = Max(*retSize, totalSize);
1038       else
1039          *retSize += totalSize;
1040    }
1041    else if(totalSize < maxSize && _class.type != systemClass)
1042    {
1043       int autoPadding = 0;
1044       if(!isMember && _class.structAlignment && totalSize % _class.structAlignment)
1045          autoPadding = _class.structAlignment - (totalSize % _class.structAlignment);
1046       if(totalSize + autoPadding < maxSize)
1047       {
1048          char sizeString[50];
1049          sprintf(sizeString, "%d", maxSize - totalSize);
1050          ListAdd(declarations,
1051             MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(CHAR)),
1052             MkListOne(MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__ecere_padding")), MkExpConstant(sizeString))), null)));
1053          if(addedPadding)
1054             *addedPadding = true;
1055       }
1056    }
1057    if(context)
1058       FinishTemplatesContext(context);
1059    return topMember ? topMember.memberID : _class.memberID;
1060 }
1061
1062 static int DeclareMembers(External neededBy, Class _class, bool isMember)
1063 {
1064    DataMember topMember = isMember ? (DataMember) _class : null;
1065    DataMember member;
1066    Context context = isMember ? null : SetupTemplatesContext(_class);
1067
1068    if(!isMember && (_class.type == structClass || _class.type == noHeadClass) && _class.base.type != systemClass)
1069       DeclareMembers(neededBy, _class.base, false);
1070
1071    for(member = isMember ? topMember.members.first : _class.membersAndProperties.first; member; member = member.next)
1072    {
1073       if(!member.isProperty)
1074       {
1075          switch(member.type)
1076          {
1077             case normalMember:
1078             {
1079                if(!member.dataType && member.dataTypeString)
1080                   member.dataType = ProcessTypeString(member.dataTypeString, false);
1081                if(member.dataType)
1082                   DeclareType(neededBy, member.dataType, true, false);
1083                break;
1084             }
1085             case unionMember:
1086             case structMember:
1087             {
1088                DeclareMembers(neededBy, (Class)member, true);
1089                break;
1090             }
1091          }
1092       }
1093    }
1094    if(context)
1095       FinishTemplatesContext(context);
1096
1097    return topMember ? topMember.memberID : _class.memberID;
1098 }
1099
1100 static void IdentifyAnonStructs(OldList/*<ClassDef>*/ *  definitions)
1101 {
1102    ClassDef def;
1103    int anonID = 1;
1104    for(def = definitions->first; def; def = def.next)
1105    {
1106       if(def.type == declarationClassDef)
1107       {
1108          Declaration decl = def.decl;
1109          if(decl && decl.specifiers)
1110          {
1111             Specifier spec;
1112             bool isStruct = false;
1113             for(spec = decl.specifiers->first; spec; spec = spec.next)
1114             {
1115                if(spec.type == structSpecifier || spec.type == unionSpecifier)
1116                {
1117                   if(spec.definitions)
1118                      IdentifyAnonStructs(spec.definitions);
1119                   isStruct = true;
1120                }
1121             }
1122             if(isStruct)
1123             {
1124                Declarator d = null;
1125                if(decl.declarators)
1126                {
1127                   for(d = decl.declarators->first; d; d = d.next)
1128                   {
1129                      Identifier idDecl = GetDeclId(d);
1130                      if(idDecl)
1131                         break;
1132                   }
1133                }
1134                if(!d)
1135                {
1136                   char id[100];
1137                   sprintf(id, "__anon%d", anonID++);
1138                   if(!decl.declarators)
1139                      decl.declarators = MkList();
1140                   ListAdd(decl.declarators, MkDeclaratorIdentifier(MkIdentifier(id)));
1141                }
1142             }
1143          }
1144       }
1145    }
1146 }
1147
1148 External DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference)
1149 {
1150    return _DeclareStruct(neededBy, name, skipNoHead, needDereference, false);
1151 }
1152
1153 External _DeclareStruct(External neededBy, const char * name, bool skipNoHead, bool needDereference, bool fwdDecl)
1154 {
1155    External external = null;
1156    Symbol classSym = FindClass(name);
1157    OldList * curDeclarations = null;
1158    Specifier curSpec = null;
1159
1160    if(!inCompiler || !classSym) return null;
1161
1162    // We don't need any declaration for bit classes...
1163    if(classSym.registered &&
1164       (classSym.registered.type == bitClass || classSym.registered.type == unitClass || classSym.registered.type == enumClass))
1165       return null;
1166
1167    if(!classSym.registered || (classSym.registered.type == normalClass && classSym.registered.structSize && classSym.registered.base && classSym.registered.base.base))
1168       _DeclareStruct(neededBy, "ecere::com::Instance", false, true, fwdDecl);
1169
1170    external = classSym.structExternal;
1171
1172    if(external && external.declaration)
1173    {
1174       Specifier spec;
1175       for(spec = external.declaration.specifiers ? external.declaration.specifiers->first : null; spec; spec = spec.next)
1176          if(spec.type == structSpecifier || spec.type == unionSpecifier)
1177          {
1178             curSpec = spec;
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
1191       classSym.declaring++;
1192
1193       if(strchr(classSym.string, '<'))
1194       {
1195          if(classSym.registered.templateClass)
1196          {
1197             external = _DeclareStruct(neededBy, classSym.registered.templateClass.fullName, skipNoHead, needDereference, fwdDecl);
1198             classSym.declaring--;
1199          }
1200          return external;
1201       }
1202
1203       structName[0] = 0;
1204       FullClassNameCat(structName, name, false);
1205
1206       classSym.declaredStructSym = true;
1207       if(!external || (classSym.registered.type == noHeadClass && !skipNoHead && !curDeclarations))
1208       {
1209          bool add = false;
1210          if(!external)
1211          {
1212             external = MkExternalDeclaration(null);
1213             classSym.structExternal = external;
1214             external.symbol = classSym;
1215
1216             add = true;
1217          }
1218
1219          if(!skipNoHead)
1220          {
1221             declarations = MkList();
1222             AddMembers(external, declarations, classSym.registered, false, null, classSym.registered, &addedPadding);
1223          }
1224
1225          if(declarations && (!declarations->count || (declarations->count == 1 && addedPadding)))
1226          {
1227             FreeList(declarations, FreeClassDef);
1228             declarations = null;
1229          }
1230
1231          if(classSym.registered.type != noHeadClass && !declarations)
1232          {
1233             FreeExternal(external);
1234             external = null;
1235             classSym.structExternal = null;
1236          }
1237          else
1238          {
1239             if(curSpec)
1240                curSpec.definitions = declarations;
1241             else
1242             {
1243                char className[1024];
1244                strcpy(className, "__ecereClass_");
1245                FullClassNameCat(className, classSym.string, true);
1246
1247                specifiers = MkList();
1248                declarators = MkList();
1249                ListAdd(specifiers, MkStructOrUnion(structSpecifier, MkIdentifier(structName), declarations));
1250                external.declaration = MkDeclaration(specifiers, declarators);
1251             }
1252             if(add)
1253                ast->Add(external);
1254          }
1255       }
1256       classSym.declaring--;
1257    }
1258    else if(!classSym.declaredStructSym && classSym.structExternal)
1259    {
1260       classSym.declaredStructSym = true;
1261
1262       if(classSym.registered)
1263          DeclareMembers(classSym.structExternal, classSym.registered, false);
1264
1265       if(classSym.structExternal.declaration && classSym.structExternal.declaration.specifiers)
1266       {
1267          Specifier spec;
1268          for(spec = classSym.structExternal.declaration.specifiers->first; spec; spec = spec.next)
1269          {
1270             if(spec.definitions)
1271                IdentifyAnonStructs(spec.definitions);
1272          }
1273       }
1274    }
1275    if(inCompiler && neededBy && (external || !classSym.imported))
1276    {
1277       if(!external)
1278       {
1279          classSym.structExternal = external = MkExternalDeclaration(null);
1280          external.symbol = classSym;
1281          ast->Add(external);
1282       }
1283       if(fwdDecl)
1284       {
1285          External e = external.fwdDecl ? external.fwdDecl : external;
1286          if(e.incoming.count)
1287             neededBy.CreateUniqueEdge(e, !needDereference && !external.fwdDecl);
1288       }
1289       else
1290          neededBy.CreateUniqueEdge(external, !needDereference);
1291    }
1292    return external;
1293 }
1294
1295 void DeclareProperty(External neededBy, Property prop, char * setName, char * getName)
1296 {
1297    Symbol symbol = prop.symbol;
1298    bool imported = false;
1299    bool dllImport = false;
1300    External structExternal = null;
1301    External instExternal = null;
1302
1303    strcpy(setName, "__ecereProp_");
1304    FullClassNameCat(setName, prop._class.fullName, false);
1305    strcat(setName, "_Set_");
1306    FullClassNameCat(setName, prop.name, true);
1307
1308    strcpy(getName, "__ecereProp_");
1309    FullClassNameCat(getName, prop._class.fullName, false);
1310    strcat(getName, "_Get_");
1311    FullClassNameCat(getName, prop.name, true);
1312
1313    if(!symbol || symbol._import)
1314    {
1315       if(!symbol)
1316       {
1317          Symbol classSym;
1318
1319          if(!prop._class.symbol)
1320             prop._class.symbol = FindClass(prop._class.fullName);
1321          classSym = prop._class.symbol;
1322          if(classSym && !classSym._import)
1323          {
1324             ModuleImport module;
1325
1326             if(prop._class.module)
1327                module = FindModule(prop._class.module);
1328             else
1329                module = mainModule;
1330
1331             classSym._import = ClassImport
1332             {
1333                name = CopyString(prop._class.fullName);
1334                isRemote = prop._class.isRemote;
1335             };
1336             module.classes.Add(classSym._import);
1337          }
1338          symbol = prop.symbol = Symbol { };
1339          symbol._import = (ClassImport)PropertyImport
1340          {
1341             name = CopyString(prop.name);
1342             isVirtual = false; //prop.isVirtual;
1343             hasSet = prop.Set ? true : false;
1344             hasGet = prop.Get ? true : false;
1345          };
1346          if(classSym)
1347             classSym._import.properties.Add(symbol._import);
1348       }
1349       imported = true;
1350       // Ugly work around for isNan properties declared within float/double classes which are initialized with ecereCOM
1351       if((prop._class.module != privateModule || !strcmp(prop._class.name, "float") || !strcmp(prop._class.name, "double")) &&
1352          prop._class.module.importType != staticImport)
1353          dllImport = true;
1354    }
1355
1356    if(!symbol.type)
1357    {
1358       Context context = SetupTemplatesContext(prop._class);
1359       symbol.type = ProcessTypeString(prop.dataTypeString, false);
1360       FinishTemplatesContext(context);
1361    }
1362
1363    if((prop.Get && !symbol.externalGet) || (prop.Set && !symbol.externalSet))
1364    {
1365       if(prop._class.type == normalClass && prop._class.structSize)
1366          instExternal = DeclareStruct(null, "ecere::com::Instance", false, true);
1367       structExternal = DeclareStruct(null, prop._class.fullName, prop._class.type != structClass /*true*/, false);
1368    }
1369
1370    // Get
1371    if(prop.Get && !symbol.externalGet)
1372    {
1373       Declaration decl;
1374       OldList * specifiers, * declarators;
1375       Declarator d;
1376       OldList * params;
1377       Specifier spec = null;
1378       External external;
1379       Declarator typeDecl;
1380       bool simple = false;
1381       bool needReference;
1382
1383       specifiers = MkList();
1384       declarators = MkList();
1385       params = MkList();
1386
1387       ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1388          MkDeclaratorIdentifier(MkIdentifier("this"))));
1389
1390       d = MkDeclaratorIdentifier(MkIdentifier(getName));
1391       //if(imported)
1392       if(dllImport)
1393          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1394
1395       {
1396          Context context = SetupTemplatesContext(prop._class);
1397          typeDecl = SpecDeclFromString(prop.dataTypeString, specifiers, null);
1398          FinishTemplatesContext(context);
1399       }
1400
1401       // Make sure the simple _class's type is declared
1402       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1403       for(spec = specifiers->first; spec; spec = spec.next)
1404       {
1405          if(spec.type == nameSpecifier)
1406          {
1407             Symbol classSym = spec.symbol;
1408             if(needReference)
1409             {
1410                symbol._class = classSym.registered;
1411                if(classSym.registered && classSym.registered.type == structClass)
1412                   simple = true;
1413             }
1414             break;
1415          }
1416       }
1417
1418       if(!simple)
1419          d = PlugDeclarator(typeDecl, d);
1420       else
1421       {
1422          ListAdd(params, MkTypeName(specifiers,
1423             PlugDeclarator(typeDecl, MkDeclaratorIdentifier(MkIdentifier("value")))));
1424          specifiers = MkList();
1425       }
1426
1427       d = MkDeclaratorFunction(d, params);
1428
1429       //if(imported)
1430       if(dllImport)
1431          specifiers->Insert(null, MkSpecifier(EXTERN));
1432       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1433          specifiers->Insert(null, MkSpecifier(STATIC));
1434       if(simple)
1435          ListAdd(specifiers, MkSpecifier(VOID));
1436
1437       ListAdd(declarators, MkInitDeclarator(d, null));
1438
1439       decl = MkDeclaration(specifiers, declarators);
1440
1441       external = MkExternalDeclaration(decl);
1442
1443       if(structExternal)
1444          external.CreateEdge(structExternal, false);
1445       if(instExternal)
1446          external.CreateEdge(instExternal, false);
1447
1448       if(spec)
1449          DeclareStruct(external, spec.name, false, needReference);
1450
1451       ast->Add(external);
1452       external.symbol = symbol;
1453       symbol.externalGet = external;
1454
1455       ReplaceThisClassSpecifiers(specifiers, prop._class);
1456
1457       if(typeDecl)
1458          FreeDeclarator(typeDecl);
1459    }
1460
1461    // Set
1462    if(prop.Set && !symbol.externalSet)
1463    {
1464       Declaration decl;
1465       OldList * specifiers, * declarators;
1466       Declarator d;
1467       OldList * params;
1468       Specifier spec = null;
1469       External external;
1470       Declarator typeDecl;
1471       bool needReference;
1472
1473       declarators = MkList();
1474       params = MkList();
1475
1476       if(!prop.conversion || prop._class.type == structClass)
1477       {
1478          ListAdd(params, MkTypeName(MkListOne(MkSpecifierName(prop._class.fullName)),
1479             MkDeclaratorIdentifier(MkIdentifier("this"))));
1480       }
1481
1482       specifiers = MkList();
1483
1484       {
1485          Context context = SetupTemplatesContext(prop._class);
1486          typeDecl = d = SpecDeclFromString(prop.dataTypeString, specifiers,
1487             MkDeclaratorIdentifier(MkIdentifier("value")));
1488          FinishTemplatesContext(context);
1489       }
1490       if(!strcmp(prop._class.base.fullName, "eda::Row") || !strcmp(prop._class.base.fullName, "eda::Id"))
1491          specifiers->Insert(null, MkSpecifier(CONST));
1492
1493       ListAdd(params, MkTypeName(specifiers, d));
1494
1495       d = MkDeclaratorIdentifier(MkIdentifier(setName));
1496       if(dllImport)
1497          d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
1498       d = MkDeclaratorFunction(d, params);
1499
1500       // Make sure the simple _class's type is declared
1501       needReference = !typeDecl || typeDecl.type == identifierDeclarator;
1502       for(spec = specifiers->first; spec; spec = spec.next)
1503       {
1504          if(spec.type == nameSpecifier)
1505          {
1506             Symbol classSym = spec.symbol;
1507             if(needReference)
1508                symbol._class = classSym.registered;
1509             break;
1510          }
1511       }
1512
1513       ListAdd(declarators, MkInitDeclarator(d, null));
1514
1515       specifiers = MkList();
1516       if(dllImport)
1517          specifiers->Insert(null, MkSpecifier(EXTERN));
1518       else if(prop._class.symbol && ((Symbol)prop._class.symbol).isStatic)
1519          specifiers->Insert(null, MkSpecifier(STATIC));
1520
1521       if(!prop.conversion || prop._class.type == structClass)
1522          ListAdd(specifiers, MkSpecifier(VOID));
1523       else
1524          ListAdd(specifiers, MkSpecifierName(prop._class.fullName));
1525
1526       decl = MkDeclaration(specifiers, declarators);
1527
1528       external = MkExternalDeclaration(decl);
1529
1530       if(structExternal)
1531          external.CreateEdge(structExternal, false);
1532       if(instExternal)
1533          external.CreateEdge(instExternal, false);
1534
1535       if(spec)
1536          DeclareStruct(external, spec.name, false, needReference);
1537
1538       ast->Add(external);
1539       external.symbol = symbol;
1540       symbol.externalSet = external;
1541
1542       ReplaceThisClassSpecifiers(specifiers, prop._class);
1543    }
1544
1545    // Property (for Watchers)
1546    if(!symbol.externalPtr)
1547    {
1548       Declaration decl;
1549       External external;
1550       OldList * specifiers = MkList();
1551       char propName[1024];
1552
1553       if(imported)
1554          specifiers->Insert(null, MkSpecifier(EXTERN));
1555       else
1556       {
1557          specifiers->Insert(null, MkSpecifier(STATIC));
1558          specifiers->Add(MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
1559       }
1560
1561       ListAdd(specifiers, MkSpecifierName("Property"));
1562
1563       strcpy(propName, "__ecereProp_");
1564       FullClassNameCat(propName, prop._class.fullName, false);
1565       strcat(propName, "_");
1566       FullClassNameCat(propName, prop.name, true);
1567
1568       {
1569          OldList * list = MkList();
1570          ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1571
1572          if(!imported)
1573          {
1574             strcpy(propName, "__ecerePropM_");
1575             FullClassNameCat(propName, prop._class.fullName, false);
1576             strcat(propName, "_");
1577             FullClassNameCat(propName, prop.name, true);
1578
1579             ListAdd(list, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(propName)), null));
1580          }
1581          decl = MkDeclaration(specifiers, list);
1582       }
1583
1584       external = MkExternalDeclaration(decl);
1585       ast->Insert(curExternal.prev, external);
1586       external.symbol = symbol;
1587       symbol.externalPtr = external;
1588    }
1589
1590    if(inCompiler && neededBy)
1591    {
1592       // Could improve this to create edge on only what is needed...
1593       if(symbol.externalPtr)
1594          neededBy.CreateUniqueEdge(symbol.externalPtr, false);
1595
1596       if(symbol.externalGet)
1597          neededBy.CreateUniqueEdge(symbol.externalGet, symbol.externalGet.type == functionExternal);
1598
1599       if(symbol.externalSet)
1600          neededBy.CreateUniqueEdge(symbol.externalSet, symbol.externalSet.type == functionExternal);
1601
1602       // IsSet ?
1603    }
1604 }
1605
1606 // ***************** EXPRESSION PROCESSING ***************************
1607 public Type Dereference(Type source)
1608 {
1609    Type type = null;
1610    if(source)
1611    {
1612       if(source.kind == pointerType || source.kind == arrayType)
1613       {
1614          type = source.type;
1615          source.type.refCount++;
1616       }
1617       else if(source.kind == classType && !strcmp(source._class.string, "String"))
1618       {
1619          type = Type
1620          {
1621             kind = charType;
1622             refCount = 1;
1623          };
1624       }
1625       // Support dereferencing of no head classes for now...
1626       else if(source.kind == classType && source._class && source._class.registered && source._class.registered.type == noHeadClass)
1627       {
1628          type = source;
1629          source.refCount++;
1630       }
1631       else
1632          Compiler_Error($"cannot dereference type\n");
1633    }
1634    return type;
1635 }
1636
1637 static Type Reference(Type source)
1638 {
1639    Type type = null;
1640    if(source)
1641    {
1642       type = Type
1643       {
1644          kind = pointerType;
1645          type = source;
1646          refCount = 1;
1647       };
1648       source.refCount++;
1649    }
1650    return type;
1651 }
1652
1653 void ProcessMemberInitData(MemberInit member, Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
1654 {
1655    Identifier ident = member.identifiers ? member.identifiers->first : null;
1656    bool found = false;
1657    DataMember dataMember = null;
1658    Method method = null;
1659    bool freeType = false;
1660
1661    yylloc = member.loc;
1662
1663    if(!ident)
1664    {
1665       if(curMember)
1666       {
1667          eClass_FindNextMember(_class, curClass, curMember, subMemberStack, subMemberStackPos);
1668          if(*curMember)
1669          {
1670             found = true;
1671             dataMember = *curMember;
1672          }
1673       }
1674    }
1675    else
1676    {
1677       DataMember thisMember = (DataMember)eClass_FindProperty(_class, ident.string, privateModule);
1678       DataMember _subMemberStack[256];
1679       int _subMemberStackPos = 0;
1680
1681       // FILL MEMBER STACK
1682       if(!thisMember)
1683          thisMember = eClass_FindDataMember(_class, ident.string, privateModule, _subMemberStack, &_subMemberStackPos);
1684       if(thisMember)
1685       {
1686          dataMember = thisMember;
1687          if(curMember && thisMember.memberAccess == publicAccess)
1688          {
1689             *curMember = thisMember;
1690             *curClass = thisMember._class;
1691             memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
1692             *subMemberStackPos = _subMemberStackPos;
1693          }
1694          found = true;
1695       }
1696       else
1697       {
1698          // Setting a method
1699          method = eClass_FindMethod(_class, ident.string, privateModule);
1700          if(method && method.type == virtualMethod)
1701             found = true;
1702          else
1703             method = null;
1704       }
1705    }
1706
1707    if(found)
1708    {
1709       Type type = null;
1710       if(dataMember)
1711       {
1712          if(!dataMember.dataType && dataMember.dataTypeString)
1713          {
1714             //Context context = SetupTemplatesContext(dataMember._class);
1715             Context context = SetupTemplatesContext(_class);
1716             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
1717             FinishTemplatesContext(context);
1718          }
1719          type = dataMember.dataType;
1720       }
1721       else if(method)
1722       {
1723          // This is for destination type...
1724          if(!method.dataType)
1725             ProcessMethodType(method);
1726          //DeclareMethod(method);
1727          // method.dataType = ((Symbol)method.symbol)->type;
1728          type = method.dataType;
1729       }
1730
1731       if(ident && ident.next)
1732       {
1733          for(ident = ident.next; ident && type; ident = ident.next)
1734          {
1735             if(type.kind == classType)
1736             {
1737                dataMember = (DataMember)eClass_FindProperty(type._class.registered, ident.string, privateModule);
1738                if(!dataMember)
1739                   dataMember = eClass_FindDataMember(type._class.registered, ident.string, privateModule, null, null);
1740                if(dataMember)
1741                   type = dataMember.dataType;
1742             }
1743             else if(type.kind == structType || type.kind == unionType)
1744             {
1745                Type memberType;
1746                for(memberType = type.members.first; memberType; memberType = memberType.next)
1747                {
1748                   if(!strcmp(memberType.name, ident.string))
1749                   {
1750                      type = memberType;
1751                      break;
1752                   }
1753                }
1754             }
1755          }
1756       }
1757
1758       // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
1759       if(type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type && _class.templateArgs /* TODO: Watch out for these _class.templateClass*/)
1760       {
1761          int id = 0;
1762          ClassTemplateParameter curParam = null;
1763          Class sClass;
1764          for(sClass = _class; sClass; sClass = sClass.base)
1765          {
1766             id = 0;
1767             if(sClass.templateClass) sClass = sClass.templateClass;
1768             for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
1769             {
1770                if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
1771                {
1772                   for(sClass = sClass.base; sClass; sClass = sClass.base)
1773                   {
1774                      if(sClass.templateClass) sClass = sClass.templateClass;
1775                      id += sClass.templateParams.count;
1776                   }
1777                   break;
1778                }
1779                id++;
1780             }
1781             if(curParam) break;
1782          }
1783
1784          if(curParam)
1785          {
1786             ClassTemplateArgument arg = _class.templateArgs[id];
1787             if(arg.dataTypeString)
1788             {
1789                bool constant = type.constant;
1790                // FreeType(type);
1791                type = ProcessTypeString(arg.dataTypeString, false);
1792                if(type.kind == classType && constant) type.constant = true;
1793                else if(type.kind == pointerType)
1794                {
1795                   Type t = type.type;
1796                   while(t.kind == pointerType) t = t.type;
1797                   if(constant) t.constant = constant;
1798                }
1799                freeType = true;
1800                if(type && _class.templateClass)
1801                   type.passAsTemplate = true;
1802                if(type)
1803                {
1804                   // type.refCount++;
1805                   /*if(!exp.destType)
1806                   {
1807                      exp.destType = ProcessTypeString(arg.dataTypeString, false);
1808                      exp.destType.refCount++;
1809                   }*/
1810                }
1811             }
1812          }
1813       }
1814       if(type && type.kind == classType && type._class && type._class.registered && strchr(type._class.registered.fullName, '<'))
1815       {
1816          Class expClass = type._class.registered;
1817          Class cClass = null;
1818          int paramCount = 0;
1819          int lastParam = -1;
1820
1821          char templateString[1024];
1822          ClassTemplateParameter param;
1823          sprintf(templateString, "%s<", expClass.templateClass.fullName);
1824          for(cClass = expClass; cClass; cClass = cClass.base)
1825          {
1826             int p = 0;
1827             if(cClass.templateClass) cClass = cClass.templateClass;
1828             for(param = cClass.templateParams.first; param; param = param.next)
1829             {
1830                int id = p;
1831                Class sClass;
1832                ClassTemplateArgument arg;
1833                for(sClass = cClass.base; sClass; sClass = sClass.base)
1834                {
1835                   if(sClass.templateClass) sClass = sClass.templateClass;
1836                   id += sClass.templateParams.count;
1837                }
1838                arg = expClass.templateArgs[id];
1839
1840                for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
1841                {
1842                   ClassTemplateParameter cParam;
1843                   //int p = numParams - sClass.templateParams.count;
1844                   int p = 0;
1845                   Class nextClass;
1846                   if(sClass.templateClass) sClass = sClass.templateClass;
1847
1848                   for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
1849                   {
1850                      if(nextClass.templateClass) nextClass = nextClass.templateClass;
1851                      p += nextClass.templateParams.count;
1852                   }
1853
1854                   for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
1855                   {
1856                      if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
1857                      {
1858                         if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1859                         {
1860                            arg.dataTypeString = _class.templateArgs[p].dataTypeString;
1861                            arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
1862                            break;
1863                         }
1864                      }
1865                   }
1866                }
1867
1868                {
1869                   char argument[256];
1870                   argument[0] = '\0';
1871                   /*if(arg.name)
1872                   {
1873                      strcat(argument, arg.name.string);
1874                      strcat(argument, " = ");
1875                   }*/
1876                   switch(param.type)
1877                   {
1878                      case expression:
1879                      {
1880                         // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
1881                         char expString[1024];
1882                         OldList * specs = MkList();
1883                         Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
1884                         Expression exp;
1885                         char * string = PrintHexUInt64(arg.expression.ui64);
1886                         exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
1887                         delete string;
1888
1889                         ProcessExpressionType(exp);
1890                         ComputeExpression(exp);
1891                         expString[0] = '\0';
1892                         PrintExpression(exp, expString);
1893                         strcat(argument, expString);
1894                         //delete exp;
1895                         FreeExpression(exp);
1896                         break;
1897                      }
1898                      case identifier:
1899                      {
1900                         strcat(argument, arg.member.name);
1901                         break;
1902                      }
1903                      case TemplateParameterType::type:
1904                      {
1905                         if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
1906                            strcat(argument, arg.dataTypeString);
1907                         break;
1908                      }
1909                   }
1910                   if(argument[0])
1911                   {
1912                      if(paramCount) strcat(templateString, ", ");
1913                      if(lastParam != p - 1)
1914                      {
1915                         strcat(templateString, param.name);
1916                         strcat(templateString, " = ");
1917                      }
1918                      strcat(templateString, argument);
1919                      paramCount++;
1920                      lastParam = p;
1921                   }
1922                   p++;
1923                }
1924             }
1925          }
1926          {
1927             int len = strlen(templateString);
1928             if(templateString[len-1] == '<')
1929                len--;
1930             else
1931             {
1932                if(templateString[len-1] == '>')
1933                   templateString[len++] = ' ';
1934                templateString[len++] = '>';
1935             }
1936             templateString[len++] = '\0';
1937          }
1938          {
1939             Context context = SetupTemplatesContext(_class);
1940             if(freeType) FreeType(type);
1941             type = ProcessTypeString(templateString, false);
1942             freeType = true;
1943             FinishTemplatesContext(context);
1944          }
1945       }
1946
1947       if(method && member.initializer && member.initializer.type == expInitializer && member.initializer.exp)
1948       {
1949          ProcessExpressionType(member.initializer.exp);
1950          if(!member.initializer.exp.expType)
1951          {
1952             if(inCompiler)
1953             {
1954                char expString[10240];
1955                expString[0] = '\0';
1956                PrintExpression(member.initializer.exp, expString);
1957                ChangeCh(expString, '\n', ' ');
1958                Compiler_Error($"unresolved symbol used as an instance method %s\n", expString);
1959             }
1960          }
1961          //else if(!MatchTypes(member.exp.expType, type, null, _class, null, true, true, false, false))
1962          else if(!MatchTypes(member.initializer.exp.expType, type, null, null, _class, true, true, false, false, true))
1963          {
1964             Compiler_Error($"incompatible instance method %s\n", ident.string);
1965          }
1966       }
1967       else if(member.initializer)
1968       {
1969          /*
1970          FreeType(member.exp.destType);
1971          member.exp.destType = type;
1972          if(member.exp.destType)
1973             member.exp.destType.refCount++;
1974          ProcessExpressionType(member.exp);
1975          */
1976
1977          ProcessInitializer(member.initializer, type);
1978       }
1979       if(freeType) FreeType(type);
1980    }
1981    else
1982    {
1983       if(_class && _class.type == unitClass)
1984       {
1985          if(member.initializer)
1986          {
1987             /*
1988             FreeType(member.exp.destType);
1989             member.exp.destType = MkClassType(_class.fullName);
1990             ProcessExpressionType(member.initializer, type);
1991             */
1992             Type type = MkClassType(_class.fullName);
1993             ProcessInitializer(member.initializer, type);
1994             FreeType(type);
1995          }
1996       }
1997       else
1998       {
1999          if(member.initializer)
2000          {
2001             //ProcessExpressionType(member.exp);
2002             ProcessInitializer(member.initializer, null);
2003          }
2004          if(ident)
2005          {
2006             if(method)
2007             {
2008                Compiler_Error($"couldn't find virtual method %s in class %s\n", ident.string, _class.fullName);
2009             }
2010             else if(_class)
2011             {
2012                Compiler_Error($"couldn't find member %s in class %s\n", ident.string, _class.fullName);
2013                if(inCompiler)
2014                   eClass_AddDataMember(_class, ident.string, "int", 0, 0, publicAccess);
2015             }
2016          }
2017          else if(_class)
2018             Compiler_Error($"too many initializers for instantiation of class %s\n", _class.fullName);
2019       }
2020    }
2021 }
2022
2023 void ProcessInstantiationType(Instantiation inst)
2024 {
2025    yylloc = inst.loc;
2026    if(inst._class)
2027    {
2028       MembersInit members;
2029       Symbol classSym;
2030       Class _class;
2031
2032       classSym = inst._class.symbol;
2033       _class = classSym ? classSym.registered : null;
2034
2035       if(!_class || _class.type != noHeadClass)
2036          DeclareStruct(curExternal, inst._class.name, false, true);
2037
2038       afterExternal = afterExternal ? afterExternal : curExternal;
2039
2040       if(inst.exp)
2041          ProcessExpressionType(inst.exp);
2042
2043       inst.isConstant = true;
2044       if(inst.members)
2045       {
2046          DataMember curMember = null;
2047          Class curClass = null;
2048          DataMember subMemberStack[256];
2049          int subMemberStackPos = 0;
2050
2051          for(members = inst.members->first; members; members = members.next)
2052          {
2053             switch(members.type)
2054             {
2055                case methodMembersInit:
2056                {
2057                   char name[1024];
2058                   static uint instMethodID = 0;
2059                   External external = curExternal;
2060                   Context context = curContext;
2061                   Declarator declarator = members.function.declarator;
2062                   Identifier nameID = GetDeclId(declarator);
2063                   char * unmangled = nameID ? nameID.string : null;
2064                   Expression exp;
2065                   External createdExternal = null;
2066
2067                   if(inCompiler)
2068                   {
2069                      char number[16];
2070                      strcpy(name, "__ecereInstMeth_");
2071                      FullClassNameCat(name, _class ? _class.fullName : "_UNKNOWNCLASS", false);
2072                      strcat(name, "_");
2073                      strcat(name, nameID.string);
2074                      strcat(name, "_");
2075                      sprintf(number, "_%08d", instMethodID++);
2076                      strcat(name, number);
2077                      nameID.string = CopyString(name);
2078                   }
2079
2080                   // Do modifications here...
2081                   if(declarator)
2082                   {
2083                      Symbol symbol = declarator.symbol;
2084                      Method method = eClass_FindMethod(_class, unmangled, privateModule);
2085
2086                      if(method && method.type == virtualMethod)
2087                      {
2088                         symbol.method = method;
2089                         ProcessMethodType(method);
2090
2091                         if(!symbol.type.thisClass)
2092                         {
2093                            if(method.dataType.thisClass && currentClass &&
2094                               eClass_IsDerived(currentClass, method.dataType.thisClass.registered))
2095                            {
2096                               if(!currentClass.symbol)
2097                                  currentClass.symbol = FindClass(currentClass.fullName);
2098                               symbol.type.thisClass = currentClass.symbol;
2099                            }
2100                            else
2101                            {
2102                               if(!_class.symbol)
2103                                  _class.symbol = FindClass(_class.fullName);
2104                               symbol.type.thisClass = _class.symbol;
2105                            }
2106                         }
2107                         DeclareType(curExternal, symbol.type, true, true);
2108
2109                      }
2110                      else if(classSym)
2111                      {
2112                         Compiler_Error($"couldn't find virtual method %s in class %s\n",
2113                            unmangled, classSym.string);
2114                      }
2115                   }
2116
2117                   createdExternal = ProcessClassFunction(classSym ? classSym.registered : null, members.function, ast, afterExternal, true);
2118
2119                   if(nameID)
2120                   {
2121                      FreeSpecifier(nameID._class);
2122                      nameID._class = null;
2123                   }
2124
2125                   curExternal = createdExternal;
2126                   if(inCompiler)
2127                   {
2128                      if(createdExternal.function)
2129                         ProcessFunction(createdExternal.function);
2130                   }
2131                   else if(declarator)
2132                   {
2133                      curExternal = declarator.symbol.pointerExternal;
2134                      ProcessFunction((FunctionDefinition)members.function);
2135                   }
2136                   curExternal = external;
2137                   curContext = context;
2138
2139                   if(inCompiler)
2140                   {
2141                      FreeClassFunction(members.function);
2142
2143                      // In this pass, turn this into a MemberInitData
2144                      exp = QMkExpId(name);
2145                      members.type = dataMembersInit;
2146                      members.dataMembers = MkListOne(MkMemberInit(MkListOne(MkIdentifier(unmangled)), MkInitializerAssignment(exp)));
2147
2148                      delete unmangled;
2149                   }
2150                   break;
2151                }
2152                case dataMembersInit:
2153                {
2154                   if(members.dataMembers && classSym)
2155                   {
2156                      MemberInit member;
2157                      Location oldyyloc = yylloc;
2158                      for(member = members.dataMembers->first; member; member = member.next)
2159                      {
2160                         ProcessMemberInitData(member, classSym.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
2161                         if(member.initializer && !member.initializer.isConstant)
2162                            inst.isConstant = false;
2163                      }
2164                      yylloc = oldyyloc;
2165                   }
2166                   break;
2167                }
2168             }
2169          }
2170       }
2171    }
2172 }
2173
2174 void DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2175 {
2176    _DeclareType(neededFor, type, needDereference, forFunctionDef, false);
2177 }
2178
2179 void DeclareTypeForwardDeclare(External neededFor, Type type, bool needDereference, bool forFunctionDef)
2180 {
2181    _DeclareType(neededFor, type, needDereference, forFunctionDef, true);
2182 }
2183
2184 static void _DeclareType(External neededFor, Type type, bool needDereference, bool forFunctionDef, bool fwdDecl)
2185 {
2186    if(inCompiler)
2187    {
2188       if(type.kind == functionType)
2189       {
2190          Type param;
2191          for(param = type.params.first; param; param = param.next)
2192             _DeclareType(neededFor, param, forFunctionDef, false, fwdDecl);
2193          _DeclareType(neededFor, type.returnType, forFunctionDef, false, fwdDecl);
2194       }
2195       else if(type.kind == pointerType)
2196          _DeclareType(neededFor, type.type, false, false, fwdDecl);
2197       else if(type.kind == classType)
2198       {
2199          Class c = type._class.registered;
2200          _DeclareStruct(neededFor, c ? c.fullName : "ecere::com::Instance", c ? c.type == noHeadClass : false, needDereference && c && c.type == structClass, fwdDecl);
2201       }
2202       else if(type.kind == structType || type.kind == unionType)
2203       {
2204          Type member;
2205          for(member = type.members.first; member; member = member.next)
2206             _DeclareType(neededFor, member, needDereference, forFunctionDef, fwdDecl);
2207       }
2208       else if(type.kind == arrayType)
2209          _DeclareType(neededFor, type.arrayType, true, false, fwdDecl);
2210    }
2211 }
2212
2213 ClassTemplateArgument * FindTemplateArg(Class _class, TemplateParameter param)
2214 {
2215    ClassTemplateArgument * arg = null;
2216    int id = 0;
2217    ClassTemplateParameter curParam = null;
2218    Class sClass;
2219    for(sClass = _class; sClass; sClass = sClass.base)
2220    {
2221       id = 0;
2222       if(sClass.templateClass) sClass = sClass.templateClass;
2223       for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
2224       {
2225          if(curParam.type == TemplateParameterType::type && !strcmp(param.identifier.string, curParam.name))
2226          {
2227             for(sClass = sClass.base; sClass; sClass = sClass.base)
2228             {
2229                if(sClass.templateClass) sClass = sClass.templateClass;
2230                id += sClass.templateParams.count;
2231             }
2232             break;
2233          }
2234          id++;
2235       }
2236       if(curParam) break;
2237    }
2238    if(curParam)
2239    {
2240       arg = &_class.templateArgs[id];
2241       if(arg && param.type == type)
2242          arg->dataTypeClass = eSystem_FindClass(_class.module, arg->dataTypeString);
2243    }
2244    return arg;
2245 }
2246
2247 public Context SetupTemplatesContext(Class _class)
2248 {
2249    Context context = PushContext();
2250    context.templateTypesOnly = true;
2251    if(_class.symbol && ((Symbol)_class.symbol).templateParams)
2252    {
2253       TemplateParameter param = ((Symbol)_class.symbol).templateParams->first;
2254       for(; param; param = param.next)
2255       {
2256          if(param.type == type && param.identifier)
2257          {
2258             TemplatedType type { key = (uintptr)param.identifier.string, param = param };
2259             curContext.templateTypes.Add((BTNode)type);
2260          }
2261       }
2262    }
2263    else if(_class)
2264    {
2265       Class sClass;
2266       for(sClass = _class; sClass; sClass = sClass.base)
2267       {
2268          ClassTemplateParameter p;
2269          for(p = sClass.templateParams.first; p; p = p.next)
2270          {
2271             //OldList * specs = MkList();
2272             //Declarator decl = null;
2273             //decl = SpecDeclFromString(p.dataTypeString, specs, null);
2274             if(p.type == type)
2275             {
2276                TemplateParameter param = p.param;
2277                TemplatedType type;
2278                if(!param)
2279                {
2280                   // ADD DATA TYPE HERE...
2281                   p.param = param = TemplateParameter
2282                   {
2283                      identifier = MkIdentifier(p.name), type = p.type,
2284                      dataTypeString = p.dataTypeString /*, dataType = { specs, decl }*/
2285                   };
2286                }
2287                type = TemplatedType { key = (uintptr)p.name, param = param };
2288                curContext.templateTypes.Add((BTNode)type);
2289             }
2290          }
2291       }
2292    }
2293    return context;
2294 }
2295
2296 public void FinishTemplatesContext(Context context)
2297 {
2298    PopContext(context);
2299    FreeContext(context);
2300    delete context;
2301 }
2302
2303 public void ProcessMethodType(Method method)
2304 {
2305    if(!method.dataType)
2306    {
2307       Context context = SetupTemplatesContext(method._class);
2308
2309       method.dataType = ProcessTypeString(method.dataTypeString, false);
2310
2311       FinishTemplatesContext(context);
2312
2313       if(method.type != virtualMethod && method.dataType)
2314       {
2315          if(!method.dataType.thisClass && !method.dataType.staticMethod)
2316          {
2317             if(!method._class.symbol)
2318                method._class.symbol = FindClass(method._class.fullName);
2319             method.dataType.thisClass = method._class.symbol;
2320          }
2321       }
2322
2323       // Why was this commented out? Working fine without now...
2324
2325       /*
2326       if(method.dataType.kind == functionType && !method.dataType.staticMethod && !method.dataType.thisClass)
2327          method.dataType.thisClass = method._class.symbol; // FindClass(method._class.fullName);
2328          */
2329    }
2330
2331    /*
2332    if(type)
2333    {
2334       char * par = strstr(type, "(");
2335       char * classOp = null;
2336       int classOpLen = 0;
2337       if(par)
2338       {
2339          int c;
2340          for(c = par-type-1; c >= 0; c++)
2341          {
2342             if(type[c] == ':' && type[c+1] == ':')
2343             {
2344                classOp = type + c - 1;
2345                for(c = c-1; c >=0 && !isspace(type[c]); c--)
2346                {
2347                   classOp--;
2348                   classOpLen++;
2349                }
2350                break;
2351             }
2352             else if(!isspace(type[c]))
2353                break;
2354          }
2355       }
2356       if(classOp)
2357       {
2358          char temp[1024];
2359          int typeLen = strlen(type);
2360          memcpy(temp, classOp, classOpLen);
2361          temp[classOpLen] = '\0';
2362          if(temp[0])
2363             _class = eSystem_FindClass(module, temp);
2364          else
2365             _class = null;
2366          method.dataTypeString = new char[typeLen - classOpLen + 1];
2367          memcpy(method.dataTypeString, type, classOp - type);
2368          memcpy(method.dataTypeString + (classOp - type), classOp + classOpLen, typeLen - (classOp - type + classOpLen));
2369       }
2370       else
2371          method.dataTypeString = type;
2372    }
2373    */
2374 }
2375
2376
2377 public void ProcessPropertyType(Property prop)
2378 {
2379    if(!prop.dataType)
2380    {
2381       Context context = SetupTemplatesContext(prop._class);
2382       prop.dataType = ProcessTypeString(prop.dataTypeString, false);
2383       FinishTemplatesContext(context);
2384    }
2385 }
2386
2387 public void DeclareMethod(External neededFor, Method method, const char * name)
2388 {
2389    Symbol symbol = method.symbol;
2390    if(!symbol || (!symbol.pointerExternal && (!symbol.methodCodeExternal || method.type == virtualMethod)))
2391    {
2392       bool dllImport = false;
2393
2394       if(!method.dataType)
2395          method.dataType = ProcessTypeString(method.dataTypeString, false);
2396
2397       //if(!symbol || symbol._import || method.type == virtualMethod)
2398       {
2399          if(!symbol || method.type == virtualMethod)
2400          {
2401             Symbol classSym;
2402             if(!method._class.symbol)
2403                method._class.symbol = FindClass(method._class.fullName);
2404             classSym = method._class.symbol;
2405             if(!classSym._import)
2406             {
2407                ModuleImport module;
2408
2409                if(method._class.module && method._class.module.name)
2410                   module = FindModule(method._class.module);
2411                else
2412                   module = mainModule;
2413                classSym._import = ClassImport
2414                {
2415                   name = CopyString(method._class.fullName);
2416                   isRemote = method._class.isRemote;
2417                };
2418                module.classes.Add(classSym._import);
2419             }
2420             if(!symbol)
2421             {
2422                symbol = method.symbol = Symbol { };
2423             }
2424             if(!symbol._import)
2425             {
2426                symbol._import = (ClassImport)MethodImport
2427                {
2428                   name = CopyString(method.name);
2429                   isVirtual = method.type == virtualMethod;
2430                };
2431                classSym._import.methods.Add(symbol._import);
2432             }
2433             if(!symbol)
2434             {
2435                symbol.type = method.dataType;
2436                if(symbol.type) symbol.type.refCount++;
2437             }
2438          }
2439          if(!method.dataType.dllExport)
2440          {
2441             if((method._class.module != privateModule || !strcmp(method._class.name, "float") || !strcmp(method._class.name, "double")) && method._class.module.importType != staticImport)
2442                dllImport = true;
2443          }
2444       }
2445
2446       if(inCompiler)
2447       {
2448          // We need a declaration here :)
2449          Declaration decl;
2450          OldList * specifiers, * declarators;
2451          Declarator d;
2452          Declarator funcDecl;
2453          External external;
2454
2455          specifiers = MkList();
2456          declarators = MkList();
2457
2458          if(dllImport)
2459             ListAdd(specifiers, MkSpecifier(EXTERN));
2460          else if(method._class.symbol && ((Symbol)method._class.symbol).isStatic)
2461             ListAdd(specifiers, MkSpecifier(STATIC));
2462
2463          if(method.type == virtualMethod)
2464          {
2465             ListAdd(specifiers, MkSpecifier(INT));
2466             d = MkDeclaratorIdentifier(MkIdentifier(name));
2467          }
2468          else
2469          {
2470             d = MkDeclaratorIdentifier(MkIdentifier(name));
2471             if(dllImport)
2472                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2473             {
2474                Context context = SetupTemplatesContext(method._class);
2475                d = SpecDeclFromString(method.dataTypeString, specifiers, d);
2476                FinishTemplatesContext(context);
2477             }
2478             funcDecl = GetFuncDecl(d);
2479
2480             if(dllImport)
2481             {
2482                Specifier spec, next;
2483                for(spec = specifiers->first; spec; spec = next)
2484                {
2485                   next = spec.next;
2486                   if(spec.type == extendedSpecifier)
2487                   {
2488                      specifiers->Remove(spec);
2489                      FreeSpecifier(spec);
2490                   }
2491                }
2492             }
2493
2494             // Add this parameter if not a static method
2495             if(method.dataType && !method.dataType.staticMethod)
2496             {
2497                if(funcDecl && funcDecl.function.parameters && funcDecl.function.parameters->count)
2498                {
2499                   Class _class = method.dataType.thisClass ? method.dataType.thisClass.registered : method._class;
2500                   TypeName thisParam = MkTypeName(MkListOne(
2501                      MkSpecifierName(method.dataType.thisClass ? method.dataType.thisClass.string : method._class.fullName)),
2502                      (_class && _class.type == systemClass) ? MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("this"))) : MkDeclaratorIdentifier(MkIdentifier("this")));
2503                   TypeName firstParam = ((TypeName)funcDecl.function.parameters->first);
2504                   Specifier firstSpec = firstParam.qualifiers ? firstParam.qualifiers->first : null;
2505
2506                   if(firstSpec && firstSpec.type == baseSpecifier && firstSpec.specifier == VOID && !firstParam.declarator)
2507                   {
2508                      TypeName param = funcDecl.function.parameters->first;
2509                      funcDecl.function.parameters->Remove(param);
2510                      FreeTypeName(param);
2511                   }
2512
2513                   if(!funcDecl.function.parameters)
2514                      funcDecl.function.parameters = MkList();
2515                   funcDecl.function.parameters->Insert(null, thisParam);
2516                }
2517             }
2518          }
2519          ProcessDeclarator(d, true);
2520
2521          ListAdd(declarators, MkInitDeclarator(d, null));
2522
2523          decl = MkDeclaration(specifiers, declarators);
2524
2525          ReplaceThisClassSpecifiers(specifiers, method._class);
2526
2527          external = MkExternalDeclaration(decl);
2528          external.symbol = symbol;
2529          symbol.pointerExternal = external;
2530          ast->Add(external);
2531          DeclareStruct(external, method._class.fullName, true, true);
2532          if(method.dataType)
2533             DeclareType(external, method.dataType, true, true);
2534       }
2535    }
2536    if(inCompiler && neededFor)
2537    {
2538       External external = symbol.pointerExternal ? symbol.pointerExternal : symbol.methodCodeExternal;
2539       neededFor.CreateUniqueEdge(external, external.type == functionExternal);
2540    }
2541 }
2542
2543 char * ReplaceThisClass(Class _class)
2544 {
2545    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2546    {
2547       bool first = true;
2548       int p = 0;
2549       ClassTemplateParameter param;
2550       int lastParam = -1;
2551
2552       char className[1024];
2553       strcpy(className, _class.fullName);
2554       for(param = _class.templateParams.first; param; param = param.next)
2555       {
2556          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2557          {
2558             if(first) strcat(className, "<");
2559             if(!first) strcat(className, ", ");
2560             if(lastParam + 1 != p)
2561             {
2562                strcat(className, param.name);
2563                strcat(className, " = ");
2564             }
2565             strcat(className, param.name);
2566             first = false;
2567             lastParam = p;
2568          }
2569          p++;
2570       }
2571       if(!first)
2572       {
2573          int len = strlen(className);
2574          if(className[len-1] == '>') className[len++] = ' ';
2575          className[len++] = '>';
2576          className[len++] = '\0';
2577       }
2578       return CopyString(className);
2579    }
2580    else
2581       return CopyString(_class.fullName);
2582 }
2583
2584 Type ReplaceThisClassType(Class _class)
2585 {
2586    Type type;
2587    if(thisClassParams && _class.templateParams.count && !_class.templateClass)
2588    {
2589       bool first = true;
2590       int p = 0;
2591       ClassTemplateParameter param;
2592       int lastParam = -1;
2593       char className[1024];
2594       strcpy(className, _class.fullName);
2595
2596       for(param = _class.templateParams.first; param; param = param.next)
2597       {
2598          // if((!param.defaultArg.dataTypeString && !param.defaultArg.expression.ui64))
2599          {
2600             if(first) strcat(className, "<");
2601             if(!first) strcat(className, ", ");
2602             if(lastParam + 1 != p)
2603             {
2604                strcat(className, param.name);
2605                strcat(className, " = ");
2606             }
2607             strcat(className, param.name);
2608             first = false;
2609             lastParam = p;
2610          }
2611          p++;
2612       }
2613       if(!first)
2614       {
2615          int len = strlen(className);
2616          if(className[len-1] == '>') className[len++] = ' ';
2617          className[len++] = '>';
2618          className[len++] = '\0';
2619       }
2620       type = MkClassType(className);
2621       //type = ProcessTypeString(className, false);
2622    }
2623    else
2624    {
2625       type = MkClassType(_class.fullName);
2626       //type = ProcessTypeString(_class.fullName, false);
2627    }
2628    //type.wasThisClass = true;
2629    return type;
2630 }
2631
2632 void ReplaceThisClassSpecifiers(OldList specs, Class _class)
2633 {
2634    if(specs != null && _class)
2635    {
2636       Specifier spec;
2637       for(spec = specs.first; spec; spec = spec.next)
2638       {
2639          if(spec.type == baseSpecifier && spec.specifier == THISCLASS)
2640          {
2641             spec.type = nameSpecifier;
2642             spec.name = ReplaceThisClass(_class);
2643             spec.symbol = FindClass(spec.name); //_class.symbol;
2644          }
2645       }
2646    }
2647 }
2648
2649 // Returns imported or not
2650 bool DeclareFunction(External neededFor, GlobalFunction function, char * name)
2651 {
2652    Symbol symbol = function.symbol;
2653    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2654    if(!symbol || !symbol.pointerExternal)
2655    {
2656       bool imported = false;
2657       bool dllImport = false;
2658
2659       if(!function.dataType)
2660       {
2661          function.dataType = ProcessTypeString(function.dataTypeString, false);
2662          if(!function.dataType.thisClass)
2663             function.dataType.staticMethod = true;
2664       }
2665
2666       if(inCompiler)
2667       {
2668          if(!symbol)
2669          {
2670             ModuleImport module = FindModule(function.module);
2671             // WARNING: This is not added anywhere...
2672             symbol = function.symbol = Symbol {  };
2673
2674             if(module.name)
2675             {
2676                if(!function.dataType.dllExport)
2677                {
2678                   symbol._import = (ClassImport)FunctionImport { name = CopyString(function.name) };
2679                   module.functions.Add(symbol._import);
2680                }
2681             }
2682             // Set the symbol type
2683             {
2684                symbol.type = ProcessTypeString(function.dataTypeString, false);
2685                if(!symbol.type.thisClass)
2686                   symbol.type.staticMethod = true;
2687             }
2688          }
2689          imported = symbol._import ? true : false;
2690          if(imported && function.module != privateModule && function.module.importType != staticImport)
2691             dllImport = true;
2692       }
2693
2694       if(inCompiler)
2695       {
2696          // TOCHECK: What's with the functionExternal check here? Is it Edge breaking / forward declaration?
2697          //if(!symbol.pointerExternal || symbol.pointerExternal.type == functionExternal)
2698          {
2699             // We need a declaration here :)
2700             Declaration decl;
2701             OldList * specifiers, * declarators;
2702             Declarator d;
2703             Declarator funcDecl;
2704             External external;
2705
2706             specifiers = MkList();
2707             declarators = MkList();
2708
2709             ListAdd(specifiers, MkSpecifier(EXTERN));
2710
2711             d = MkDeclaratorIdentifier(MkIdentifier(imported ? name : function.name));
2712             if(dllImport)
2713                d = MkDeclaratorBrackets(MkDeclaratorPointer(MkPointer(null, null), d));
2714
2715             d = SpecDeclFromString(function.dataTypeString, specifiers, d);
2716             // TAKE OUT THE DLL EXPORT IF STATICALLY IMPORTED:
2717             if(function.module.importType == staticImport)
2718             {
2719                Specifier spec;
2720                for(spec = specifiers->first; spec; spec = spec.next)
2721                   if(spec.type == extendedSpecifier && spec.extDecl && spec.extDecl.type == extDeclString && !strcmp(spec.extDecl.s, "dllexport"))
2722                   {
2723                      specifiers->Remove(spec);
2724                      FreeSpecifier(spec);
2725                      break;
2726                   }
2727             }
2728
2729             funcDecl = GetFuncDecl(d);
2730
2731             // Make sure we don't have empty parameter declarations for static methods...
2732             if(funcDecl && !funcDecl.function.parameters)
2733             {
2734                funcDecl.function.parameters = MkList();
2735                funcDecl.function.parameters->Insert(null,
2736                   MkTypeName(MkListOne(MkSpecifier(VOID)),null));
2737             }
2738
2739             ListAdd(declarators, MkInitDeclarator(d, null));
2740
2741             {
2742                Context oldCtx = curContext;
2743                curContext = globalContext;
2744                decl = MkDeclaration(specifiers, declarators);
2745                curContext = oldCtx;
2746             }
2747
2748             // Keep a different symbol for the function definition than the declaration...
2749             /* Note: This should be handled by the edge breaking...
2750             if(symbol.pointerExternal && symbol.pointerExternal.type == functionExternal)
2751             {
2752                Symbol functionSymbol { };
2753                // Copy symbol
2754                {
2755                   *functionSymbol = *symbol;
2756                   functionSymbol.string = CopyString(symbol.string);
2757                   if(functionSymbol.type)
2758                      functionSymbol.type.refCount++;
2759                }
2760
2761                excludedSymbols->Add(functionSymbol);
2762
2763                symbol.pointerExternal.symbol = functionSymbol;
2764             }
2765             */
2766             external = MkExternalDeclaration(decl);
2767             ast->Add(external);
2768             external.symbol = symbol;
2769             symbol.pointerExternal = external;
2770
2771             DeclareType(external, function.dataType, true, true);
2772          }
2773       }
2774    }
2775    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2776       neededFor.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
2777    return (symbol && symbol._import && function.module != privateModule && function.module.importType != staticImport) ? true : false;
2778 }
2779
2780 void DeclareGlobalData(External neededFor, GlobalData data)
2781 {
2782    Symbol symbol = data.symbol;
2783    // TOCHECK: Might get rid of the pointerExternal check in favor of marking the edge as breakable
2784    if(!symbol || !symbol.pointerExternal)
2785    {
2786       if(inCompiler)
2787       {
2788          if(!symbol)
2789             symbol = data.symbol = Symbol { };
2790       }
2791       if(!data.dataType)
2792          data.dataType = ProcessTypeString(data.dataTypeString, false);
2793
2794       if(inCompiler)
2795       {
2796          // We need a declaration here :)
2797          Declaration decl;
2798          OldList * specifiers, * declarators;
2799          Declarator d;
2800          External external;
2801
2802          specifiers = MkList();
2803          declarators = MkList();
2804
2805          ListAdd(specifiers, MkSpecifier(EXTERN));
2806          d = MkDeclaratorIdentifier(MkIdentifier(data.fullName));
2807          d = SpecDeclFromString(data.dataTypeString, specifiers, d);
2808
2809          ListAdd(declarators, MkInitDeclarator(d, null));
2810
2811          decl = MkDeclaration(specifiers, declarators);
2812          external = MkExternalDeclaration(decl);
2813          if(curExternal)
2814             ast->Insert(curExternal.prev, external);
2815          external.symbol = symbol;
2816          symbol.pointerExternal = external;
2817
2818          DeclareType(external, data.dataType, true, true);
2819       }
2820    }
2821    if(inCompiler && neededFor && symbol && symbol.pointerExternal)
2822       neededFor.CreateUniqueEdge(symbol.pointerExternal, false);
2823 }
2824
2825 class Conversion : struct
2826 {
2827    Conversion prev, next;
2828    Property convert;
2829    bool isGet;
2830    Type resultType;
2831 };
2832
2833 static bool CheckConstCompatibility(Type source, Type dest, bool warn)
2834 {
2835    bool status = true;
2836    if(((source.kind == classType && source._class && source._class.registered) || source.kind == arrayType || source.kind == pointerType) &&
2837       ((dest.kind == classType && dest._class && dest._class.registered) || /*dest.kind == arrayType || */dest.kind == pointerType))
2838    {
2839       Class sourceClass = source.kind == classType ? source._class.registered : null;
2840       Class destClass = dest.kind == classType ? dest._class.registered : null;
2841       if((!sourceClass || (sourceClass && sourceClass.type == normalClass && !sourceClass.structSize)) &&
2842          (!destClass || (destClass && destClass.type == normalClass && !destClass.structSize)))
2843       {
2844          Type sourceType = source, destType = dest;
2845          while((sourceType.kind == pointerType || sourceType.kind == arrayType) && sourceType.type) sourceType = sourceType.type;
2846          while((destType.kind == pointerType || destType.kind == arrayType) && destType.type) destType = destType.type;
2847          if(!destType.constant && sourceType.constant)
2848          {
2849             status = false;
2850             if(warn)
2851                Compiler_Warning($"discarding const qualifier\n");
2852          }
2853       }
2854    }
2855    return status;
2856 }
2857
2858 public bool MatchTypes(Type source, Type dest, OldList conversions, Class owningClassSource, Class owningClassDest, bool doConversion, bool enumBaseType, bool acceptReversedParams,
2859                        bool isConversionExploration, bool warnConst)
2860 {
2861    if(source && dest)
2862    {
2863       if(warnConst)
2864          CheckConstCompatibility(source, dest, true);
2865       // Property convert;
2866
2867       if(source.kind == templateType && dest.kind != templateType)
2868       {
2869          Type type = ProcessTemplateParameterType(source.templateParameter);
2870          if(type) source = type;
2871       }
2872
2873       if(dest.kind == templateType && source.kind != templateType)
2874       {
2875          Type type = ProcessTemplateParameterType(dest.templateParameter);
2876          if(type) dest = type;
2877       }
2878
2879       if(dest.classObjectType == typedObject && dest.kind != functionType)
2880       {
2881          if(source.classObjectType != anyObject)
2882             return true;
2883          else
2884          {
2885             // If either the source or the destination defines the class, accepts any_object as compatible for a typed_object
2886             if((dest._class && strcmp(dest._class.string, "class")) || (source._class && strcmp(source._class.string, "class")))
2887             {
2888                return true;
2889             }
2890          }
2891       }
2892       else
2893       {
2894          if(source.kind != functionType && source.classObjectType == anyObject)
2895             return true;
2896          if(dest.kind != functionType && dest.classObjectType == anyObject && source.classObjectType != typedObject)
2897             return true;
2898       }
2899
2900       if((dest.kind == structType && source.kind == structType) ||
2901          (dest.kind == unionType && source.kind == unionType))
2902       {
2903          if((dest.enumName && source.enumName && !strcmp(dest.enumName, source.enumName)) ||
2904              (source.members.first && source.members.first == dest.members.first))
2905             return true;
2906       }
2907
2908       if(dest.kind == ellipsisType && source.kind != voidType)
2909          return true;
2910
2911       if(dest.kind == pointerType && dest.type.kind == voidType &&
2912          ((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))
2913          || source.kind == subClassType || source.kind == pointerType || source.kind == arrayType || source.kind == functionType || source.kind == thisClassType)
2914
2915          /*source.kind != voidType && source.kind != structType && source.kind != unionType  */
2916
2917          /*&& (source.kind != classType /-*|| source._class.registered.type != structClass)*/)
2918          return true;
2919       if(!isConversionExploration && source.kind == pointerType && source.type.kind == voidType &&
2920          ((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))
2921          || dest.kind == subClassType || dest.kind == pointerType || dest.kind == arrayType || dest.kind == functionType || dest.kind == thisClassType)
2922          /* dest.kind != voidType && dest.kind != structType && dest.kind != unionType  */
2923
2924          /*&& (dest.kind != classType || dest._class.registered.type != structClass)*/)
2925          return true;
2926
2927       if(((source.kind == classType && dest.kind == classType) || (source.kind == subClassType && dest.kind == subClassType)) && source._class)
2928       {
2929          if(source._class.registered && source._class.registered.type == unitClass)
2930          {
2931             if(conversions != null)
2932             {
2933                if(source._class.registered == dest._class.registered)
2934                   return true;
2935             }
2936             else
2937             {
2938                Class sourceBase, destBase;
2939                for(sourceBase = source._class.registered; sourceBase && sourceBase.base.type != systemClass; sourceBase = sourceBase.base);
2940                for(destBase = dest._class.registered; destBase && destBase.base.type != systemClass; destBase = destBase.base);
2941                if(sourceBase == destBase)
2942                   return true;
2943             }
2944          }
2945          // Don't match enum inheriting from other enum if resolving enumeration values
2946          // TESTING: !dest.classObjectType
2947          else if(source._class && dest._class && (dest.classObjectType == source.classObjectType || !dest.classObjectType) &&
2948             (enumBaseType ||
2949                (!source._class.registered || source._class.registered.type != enumClass) ||
2950                (!dest._class.registered || dest._class.registered.type != enumClass)) && eClass_IsDerived(source._class.registered, dest._class.registered))
2951             return true;
2952          else
2953          {
2954             // Added this so that DefinedColor = Color doesn't go through ColorRGB property
2955             if(enumBaseType &&
2956                dest._class && dest._class.registered && dest._class.registered.type == enumClass &&
2957                ((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)
2958             {
2959                if(eClass_IsDerived(dest._class.registered, source._class.registered))
2960                {
2961                   return true;
2962                }
2963             }
2964          }
2965       }
2966
2967       // JUST ADDED THIS...
2968       if(source.kind == subClassType && dest.kind == classType && dest._class && !strcmp(dest._class.string, "ecere::com::Class"))
2969          return true;
2970
2971       if(doConversion)
2972       {
2973          // Just added this for Straight conversion of ColorAlpha => Color
2974          if(source.kind == classType)
2975          {
2976             Class _class;
2977             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
2978             {
2979                Property convert;
2980                for(convert = _class.conversions.first; convert; convert = convert.next)
2981                {
2982                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
2983                   {
2984                      Conversion after = (conversions != null) ? conversions.last : null;
2985
2986                      if(!convert.dataType)
2987                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
2988                      // Only go ahead with this conversion flow while processing an existing conversion if the conversion data type is a class
2989                      if((!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
2990                         MatchTypes(convert.dataType, dest, conversions, null, null,
2991                            (convert.dataType.kind == classType && !strcmp(convert.dataTypeString, "String")) ? true : false,
2992                               convert.dataType.kind == classType, false, true, warnConst))
2993                      {
2994                         if(!conversions && !convert.Get)
2995                            return true;
2996                         else if(conversions != null)
2997                         {
2998                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
2999                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3000                               (dest.kind != classType || dest._class.registered != _class.base))
3001                               return true;
3002                            else
3003                            {
3004                               Conversion conv { convert = convert, isGet = true };
3005                               // conversions.Add(conv);
3006                               conversions.Insert(after, conv);
3007
3008                               return true;
3009                            }
3010                         }
3011                      }
3012                   }
3013                }
3014             }
3015          }
3016
3017          // MOVING THIS??
3018
3019          if(dest.kind == classType)
3020          {
3021             Class _class;
3022             for(_class = dest._class ? dest._class.registered : null; _class; _class = _class.base)
3023             {
3024                Property convert;
3025                for(convert = _class.conversions.first; convert; convert = convert.next)
3026                {
3027                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3028                   {
3029                      Type constType = null;
3030                      bool success = false;
3031                      // Conversion after = (conversions != null) ? conversions.last : null;
3032
3033                      if(!convert.dataType)
3034                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3035
3036                      if(warnConst && convert.dataType.kind == pointerType && convert.dataType.type && dest.constant)
3037                      {
3038                         Type ptrType { };
3039                         constType = { kind = pointerType, refCount = 1, type = ptrType };
3040                         CopyTypeInto(ptrType, convert.dataType.type);
3041                         ptrType.constant = true;
3042                      }
3043
3044                      // Just added this equality check to prevent recursion.... Make it safer?
3045                      // Changed enumBaseType to false here to prevent all int-compatible enums to show up in AnchorValues
3046                      if((constType || convert.dataType != dest) && MatchTypes(source, constType ? constType : convert.dataType, conversions, null, null, true, false /*true*/, false, true, warnConst))
3047                      {
3048                         if(!conversions && !convert.Set)
3049                            success = true;
3050                         else if(conversions != null)
3051                         {
3052                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3053                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3054                               (source.kind != classType || source._class.registered != _class.base))
3055                               success = true;
3056                            else
3057                            {
3058                               // *** Testing this! ***
3059                               Conversion conv { convert = convert };
3060                               conversions.Add(conv);
3061                               //conversions.Insert(after, conv);
3062                               success = true;
3063                            }
3064                         }
3065                      }
3066                      if(constType)
3067                         FreeType(constType);
3068                      if(success)
3069                         return true;
3070                   }
3071                }
3072             }
3073             /*if(dest._class.registered && !strcmp(dest._class.registered.name, "bool"))
3074             {
3075                if(source.kind != voidType && source.kind != structType && source.kind != unionType &&
3076                   (source.kind != classType || source._class.registered.type != structClass))
3077                   return true;
3078             }*/
3079
3080             // TESTING THIS... IS THIS OK??
3081             if(enumBaseType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3082             {
3083                if(!dest._class.registered.dataType)
3084                   dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3085                // Only support this for classes...
3086                if(dest._class.registered.dataType.kind == classType || source.truth || dest.truth/* ||
3087                   !strcmp(dest._class.registered.name, "bool") || (source.kind == classType && !strcmp(source._class.string, "bool"))*/)
3088                {
3089                   if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, dest._class.registered.dataType.kind == classType, false, false, warnConst))
3090                   {
3091                      return true;
3092                   }
3093                }
3094             }
3095          }
3096
3097          // Moved this lower
3098          if(source.kind == classType)
3099          {
3100             Class _class;
3101             for(_class = source._class ? source._class.registered : null; _class; _class = _class.base)
3102             {
3103                Property convert;
3104                for(convert = _class.conversions.first; convert; convert = convert.next)
3105                {
3106                   if(convert.memberAccess == publicAccess || _class.module == privateModule)
3107                   {
3108                      Conversion after = (conversions != null) ? conversions.last : null;
3109
3110                      if(!convert.dataType)
3111                         convert.dataType = ProcessTypeString(convert.dataTypeString, false);
3112                      if(convert.dataType != source &&
3113                         (!isConversionExploration || convert.dataType.kind == classType || !strcmp(_class.name, "String")) &&
3114                         MatchTypes(convert.dataType, dest, conversions, null, null, convert.dataType.kind == classType, convert.dataType.kind == classType, false, true, warnConst))
3115                      {
3116                         if(!conversions && !convert.Get)
3117                            return true;
3118                         else if(conversions != null)
3119                         {
3120                            if(_class.type == unitClass && convert.dataType.kind == classType && convert.dataType._class &&
3121                               convert.dataType._class.registered && _class.base == convert.dataType._class.registered.base &&
3122                               (dest.kind != classType || dest._class.registered != _class.base))
3123                               return true;
3124                            else
3125                            {
3126                               Conversion conv { convert = convert, isGet = true };
3127
3128                               // conversions.Add(conv);
3129                               conversions.Insert(after, conv);
3130                               return true;
3131                            }
3132                         }
3133                      }
3134                   }
3135                }
3136             }
3137
3138             // TESTING THIS... IS THIS OK??
3139             if(enumBaseType && source._class && source._class.registered && source._class.registered.type == enumClass)
3140             {
3141                if(!source._class.registered.dataType)
3142                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3143                if(!isConversionExploration || source._class.registered.dataType.kind == classType || !strcmp(source._class.registered.name, "String"))
3144                {
3145                   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))
3146                      return true;
3147                   // For bool to be accepted by byte, short, etc.
3148                   else if(MatchTypes(dest, source._class.registered.dataType, null, null, null, false, false, false, false, warnConst))
3149                      return true;
3150                }
3151             }
3152          }
3153       }
3154
3155       if(source.kind == classType || source.kind == subClassType)
3156          ;
3157       else if(dest.kind == source.kind &&
3158          (dest.kind != structType && dest.kind != unionType &&
3159           dest.kind != functionType && dest.kind != arrayType && dest.kind != pointerType && dest.kind != methodType))
3160           return true;
3161       // RECENTLY ADDED THESE
3162       else if(dest.kind == doubleType && source.kind == floatType)
3163          return true;
3164       else if(dest.kind == shortType && (source.kind == charType || source.kind == _BoolType))
3165          return true;
3166       else if(dest.kind == intType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intSizeType /* Exception here for size_t */))
3167          return true;
3168       else if(dest.kind == int64Type && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intPtrType || source.kind == intSizeType))
3169          return true;
3170       else if(dest.kind == intPtrType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == intSizeType || source.kind == int64Type))
3171          return true;
3172       else if(dest.kind == intSizeType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType || source.kind == int64Type || source.kind == intPtrType))
3173          return true;
3174       else if(source.kind == enumType &&
3175          (dest.kind == intType || dest.kind == shortType || dest.kind == charType || source.kind == _BoolType || dest.kind == longType || dest.kind == int64Type || dest.kind == intPtrType || dest.kind == intSizeType))
3176           return true;
3177       else if(dest.kind == enumType && !isConversionExploration &&
3178          (source.kind == intType || source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == longType || source.kind == int64Type || source.kind == intPtrType || source.kind == intSizeType))
3179           return true;
3180       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) &&
3181               ((source.kind == functionType || (source.kind == pointerType && source.type.kind == functionType) || source.kind == methodType)))
3182       {
3183          Type paramSource, paramDest;
3184
3185          if(dest.kind == methodType)
3186             owningClassDest = dest.methodClass ? dest.methodClass : dest.method._class;
3187          if(source.kind == methodType)
3188             owningClassSource = source.methodClass ? source.methodClass : source.method._class;
3189
3190          if(dest.kind == pointerType && dest.type.kind == functionType) dest = dest.type;
3191          if(source.kind == pointerType && source.type.kind == functionType) source = source.type;
3192          if(dest.kind == methodType)
3193             dest = dest.method.dataType;
3194          if(source.kind == methodType)
3195             source = source.method.dataType;
3196
3197          paramSource = source.params.first;
3198          if(paramSource && paramSource.kind == voidType) paramSource = null;
3199          paramDest = dest.params.first;
3200          if(paramDest && paramDest.kind == voidType) paramDest = null;
3201
3202
3203          if((dest.staticMethod || (!dest.thisClass && !owningClassDest)) &&
3204             !(source.staticMethod || (!source.thisClass && !owningClassSource)))
3205          {
3206             // Source thisClass must be derived from destination thisClass
3207             if(!paramDest || (!(paramDest.kind == pointerType && paramDest.type && paramDest.type.kind == voidType) && (paramDest.kind != classType ||
3208                !eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource,paramDest._class.registered))))
3209             {
3210                if(paramDest && paramDest.kind == classType)
3211                   Compiler_Error($"method class must be derived from %s\n", paramDest._class.string);
3212                else
3213                   Compiler_Error($"method class should not take an object\n");
3214                return false;
3215             }
3216             paramDest = paramDest.next;
3217          }
3218          else if(!dest.staticMethod && (dest.thisClass || owningClassDest))
3219          {
3220             if((source.staticMethod || (!source.thisClass && !owningClassSource)))
3221             {
3222                if(dest.thisClass)
3223                {
3224                   if(!paramSource || paramSource.kind != classType || !eClass_IsDerived(paramSource._class.registered,dest.thisClass.registered))
3225                   {
3226                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3227                      return false;
3228                   }
3229                }
3230                else
3231                {
3232                   // THIS WAS BACKWARDS:
3233                   // if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(owningClassDest, paramSource._class.registered)))
3234                   if(!paramSource || paramSource.kind != classType || (owningClassDest && !eClass_IsDerived(paramSource._class.registered, owningClassDest)))
3235                   {
3236                      if(owningClassDest)
3237                        Compiler_Error($"%s expected to be derived from method class\n", owningClassDest.fullName);
3238                      else
3239                         Compiler_Error($"overriding class expected to be derived from method class\n");
3240                      return false;
3241                   }
3242                }
3243                paramSource = paramSource.next;
3244             }
3245             else
3246             {
3247                if(dest.thisClass)
3248                {
3249                   // Source thisClass must be derived from destination thisClass
3250                   if(!eClass_IsDerived(source.thisClass ? source.thisClass.registered : owningClassSource, dest.thisClass.registered))
3251                   {
3252                      Compiler_Error($"method class must be derived from %s\n", dest.thisClass.string);
3253                      return false;
3254                   }
3255                }
3256                else
3257                {
3258                   // THIS WAS BACKWARDS TOO??
3259                   // if(source.thisClass && owningClassDest && !eClass_IsDerived(owningClassDest, source.thisClass.registered))
3260                   if(source.thisClass && source.thisClass.registered && owningClassDest && !eClass_IsDerived(source.thisClass.registered, owningClassDest))
3261                   {
3262                      //if(owningClass)
3263                         Compiler_Error($"%s expected to be derived from method class\n", /*owningClass.name*/ source.thisClass.registered.fullName);
3264                      //else
3265                         //Compiler_Error($"overriding class expected to be derived from method class\n");
3266                      return false;
3267                   }
3268                }
3269             }
3270          }
3271
3272
3273          // Source return type must be derived from destination return type
3274          if(!MatchTypes(source.returnType, dest.returnType, null, null, null, true, true, false, false, warnConst))
3275          {
3276             Compiler_Warning($"incompatible return type for function\n");
3277             return false;
3278          }
3279          // The const check is backwards from the MatchTypes above (for derivative classes checks)
3280          else
3281             CheckConstCompatibility(dest.returnType, source.returnType, true);
3282
3283          // Check parameters
3284
3285          for(; paramDest; paramDest = paramDest.next)
3286          {
3287             if(!paramSource)
3288             {
3289                //Compiler_Warning($"not enough parameters\n");
3290                Compiler_Error($"not enough parameters\n");
3291                return false;
3292             }
3293             {
3294                Type paramDestType = paramDest;
3295                Type paramSourceType = paramSource;
3296                Type type = paramDestType;
3297
3298                // *** WORKING CODE: TESTING THIS HERE FOR TEMPLATES ***
3299                if(paramDest.kind == templateType && paramDest.templateParameter.type == TemplateParameterType::type && owningClassSource &&
3300                   paramSource.kind != templateType)
3301                {
3302                   int id = 0;
3303                   ClassTemplateParameter curParam = null;
3304                   Class sClass;
3305                   for(sClass = owningClassSource; sClass; sClass = sClass.base)
3306                   {
3307                      id = 0;
3308                      if(sClass.templateClass) sClass = sClass.templateClass;
3309                      for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
3310                      {
3311                         if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
3312                         {
3313                            for(sClass = sClass.base; sClass; sClass = sClass.base)
3314                            {
3315                               if(sClass.templateClass) sClass = sClass.templateClass;
3316                               id += sClass.templateParams.count;
3317                            }
3318                            break;
3319                         }
3320                         id++;
3321                      }
3322                      if(curParam) break;
3323                   }
3324
3325                   if(curParam)
3326                   {
3327                      ClassTemplateArgument arg = owningClassSource.templateArgs[id];
3328                      paramDestType = type = ProcessTypeString(arg.dataTypeString, false);
3329                   }
3330                }
3331
3332                // paramDest must be derived from paramSource
3333                if(!MatchTypes(paramDestType, paramSourceType, null, null, null, true, true, false, false, warnConst) &&
3334                   (!acceptReversedParams || !MatchTypes(paramSourceType, paramDestType, null, null, null, true, true, false, false, warnConst)))
3335                {
3336                   char type[1024];
3337                   type[0] = 0;
3338                   PrintType(paramDest, type, false, true);
3339                   Compiler_Warning($"incompatible parameter %s (expected %s)\n", paramSource.name, type);
3340
3341                   if(paramDestType != paramDest)
3342                      FreeType(paramDestType);
3343                   return false;
3344                }
3345                if(paramDestType != paramDest)
3346                   FreeType(paramDestType);
3347             }
3348
3349             paramSource = paramSource.next;
3350          }
3351          if(paramSource)
3352          {
3353             Compiler_Error($"too many parameters\n");
3354             return false;
3355          }
3356          return true;
3357       }
3358       else if((dest.kind == functionType || (dest.kind == pointerType && dest.type.kind == functionType) || dest.kind == methodType) && (source.kind == pointerType && source.type.kind == voidType))
3359       {
3360          return true;
3361       }
3362       else if((dest.kind == pointerType || dest.kind == arrayType) &&
3363          (source.kind == arrayType || source.kind == pointerType))
3364       {
3365          // Pointers to pointer is incompatible with non normal/nohead classes
3366          if(!(dest.type && dest.type.kind == pointerType && source.type.kind == classType && source.type._class &&
3367             source.type._class.registered && (source.type._class.registered.type != normalClass && source.type._class.registered.type != noHeadClass) && !source.type.byReference))
3368          {
3369             ComputeTypeSize(source.type);
3370             ComputeTypeSize(dest.type);
3371             if(source.type.size == dest.type.size && MatchTypes(source.type, dest.type, null, null, null, true, true, false, false, warnConst))
3372                return true;
3373          }
3374       }
3375    }
3376    return false;
3377 }
3378
3379 static void FreeConvert(Conversion convert)
3380 {
3381    if(convert.resultType)
3382       FreeType(convert.resultType);
3383 }
3384
3385 bool MatchWithEnums_NameSpace(NameSpace nameSpace, Expression sourceExp, Type dest,
3386                               char * string, OldList conversions)
3387 {
3388    BTNamedLink link;
3389
3390    for(link = (BTNamedLink)nameSpace.classes.first; link; link = (BTNamedLink)((BTNode)link).next)
3391    {
3392       Class _class = link.data;
3393       if(_class.type == enumClass)
3394       {
3395          OldList converts { };
3396          Type type { };
3397          type.kind = classType;
3398
3399          if(!_class.symbol)
3400             _class.symbol = FindClass(_class.fullName);
3401          type._class = _class.symbol;
3402
3403          if(MatchTypes(type, dest, &converts, null, null, dest.kind != classType || !dest._class || strcmp(dest._class.string, "bool"),
3404                false, false, false, false))
3405          {
3406             NamedLink64 value;
3407             Class enumClass = eSystem_FindClass(privateModule, "enum");
3408             if(enumClass)
3409             {
3410                Class baseClass;
3411                for(baseClass = _class ; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
3412                {
3413                   EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
3414                   for(value = e.values.first; value; value = value.next)
3415                   {
3416                      if(!strcmp(value.name, string))
3417                         break;
3418                   }
3419                   if(value)
3420                   {
3421                      FreeType(sourceExp.expType);
3422
3423                      sourceExp.isConstant = true;
3424                      sourceExp.expType = MkClassType(baseClass.fullName);
3425                      if(inCompiler || inPreCompiler || inDebugger)
3426                      {
3427                         char constant[256];
3428                         FreeExpContents(sourceExp);
3429
3430                         sourceExp.type = constantExp;
3431                         if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "short") || !strcmp(baseClass.dataTypeString, "char"))
3432                            sprintf(constant, FORMAT64D, value.data);
3433                         else
3434                            sprintf(constant, FORMAT64HEXLL, value.data);
3435                         sourceExp.constant = CopyString(constant);
3436                         //for(;baseClass.base && baseClass.base.type != systemClass; baseClass = baseClass.base);
3437                      }
3438
3439                      while(converts.first)
3440                      {
3441                         Conversion convert = converts.first;
3442                         converts.Remove(convert);
3443                         conversions.Add(convert);
3444                      }
3445                      delete type;
3446                      return true;
3447                   }
3448                }
3449             }
3450          }
3451          if(converts.first)
3452             converts.Free(FreeConvert);
3453          delete type;
3454       }
3455    }
3456    for(nameSpace = (NameSpace *)nameSpace.nameSpaces.first; nameSpace != null; nameSpace = (NameSpace *)((BTNode)nameSpace).next)
3457       if(MatchWithEnums_NameSpace(nameSpace, sourceExp, dest, string, conversions))
3458          return true;
3459    return false;
3460 }
3461
3462 public bool ModuleVisibility(Module searchIn, Module searchFor)
3463 {
3464    SubModule subModule;
3465
3466    if(searchFor == searchIn)
3467       return true;
3468
3469    for(subModule = searchIn.modules.first; subModule; subModule = subModule.next)
3470    {
3471       if(subModule.importMode == publicAccess || searchIn == searchIn.application)
3472       {
3473          if(ModuleVisibility(subModule.module, searchFor))
3474             return true;
3475       }
3476    }
3477    return false;
3478 }
3479
3480 bool MatchWithEnums_Module(Module mainModule, Expression sourceExp, Type dest, char * string, OldList conversions)
3481 {
3482    Module module;
3483
3484    if(MatchWithEnums_NameSpace(mainModule.application.systemNameSpace, sourceExp, dest, string, conversions))
3485       return true;
3486    if(MatchWithEnums_NameSpace(mainModule.application.privateNameSpace, sourceExp, dest, string, conversions))
3487       return true;
3488    if(MatchWithEnums_NameSpace(mainModule.application.publicNameSpace, sourceExp, dest, string, conversions))
3489       return true;
3490
3491    for(module = mainModule.application.allModules.first; module; module = module.next)
3492    {
3493       if(ModuleVisibility(mainModule, module) && MatchWithEnums_NameSpace(module.publicNameSpace, sourceExp, dest, string, conversions))
3494          return true;
3495    }
3496    return false;
3497 }
3498
3499 bool MatchTypeExpression(Expression sourceExp, Type dest, OldList conversions, bool skipUnitBla, bool warnConst)
3500 {
3501    Type source;
3502    Type realDest = dest;
3503    Type backupSourceExpType = null;
3504    Expression nbExp = GetNonBracketsExp(sourceExp);
3505    Expression computedExp = nbExp;
3506    dest.refCount++;
3507
3508    if(sourceExp.isConstant && sourceExp.type != constantExp && sourceExp.type != identifierExp && sourceExp.type != castExp &&
3509       dest.kind == classType && dest._class && dest._class.registered && dest._class.registered.type == enumClass)
3510    {
3511       computedExp = CopyExpression(nbExp);        // Keep the original expression, but compute for checking enum ranges
3512       ComputeExpression(computedExp /*sourceExp*/);
3513    }
3514
3515    source = sourceExp.expType;
3516
3517    if(dest.kind == pointerType && sourceExp.type == constantExp && !strtoul(sourceExp.constant, null, 0))
3518    {
3519       if(computedExp != nbExp)
3520       {
3521          FreeExpression(computedExp);
3522          computedExp = nbExp;
3523       }
3524       FreeType(dest);
3525       return true;
3526    }
3527
3528    if(!skipUnitBla && source && dest && source.kind == classType && dest.kind == classType)
3529    {
3530        if(source._class && source._class.registered && source._class.registered.type == unitClass)
3531        {
3532           Class sourceBase, destBase;
3533           for(sourceBase = source._class.registered;
3534               sourceBase && sourceBase.base && sourceBase.base.type != systemClass;
3535               sourceBase = sourceBase.base);
3536           for(destBase = dest._class.registered;
3537               destBase && destBase.base && destBase.base.type != systemClass;
3538               destBase = destBase.base);
3539           //if(source._class.registered == dest._class.registered)
3540           if(sourceBase == destBase)
3541           {
3542             if(computedExp != nbExp)
3543             {
3544                FreeExpression(computedExp);
3545                computedExp = nbExp;
3546             }
3547             FreeType(dest);
3548             return true;
3549          }
3550       }
3551    }
3552
3553    if(source)
3554    {
3555       OldList * specs;
3556       bool flag = false;
3557       int64 value = MAXINT;
3558
3559       source.refCount++;
3560
3561       if(computedExp.type == constantExp)
3562       {
3563          if(source.isSigned)
3564             value = strtoll(computedExp.constant, null, 0);
3565          else
3566             value = strtoull(computedExp.constant, null, 0);
3567       }
3568       else if(computedExp.type == opExp && sourceExp.op.op == '-' && !computedExp.op.exp1 && computedExp.op.exp2 && computedExp.op.exp2.type == constantExp)
3569       {
3570          if(source.isSigned)
3571             value = -strtoll(computedExp.op.exp2.constant, null, 0);
3572          else
3573             value = -strtoull(computedExp.op.exp2.constant, null, 0);
3574       }
3575       if(computedExp != nbExp)
3576       {
3577          FreeExpression(computedExp);
3578          computedExp = nbExp;
3579       }
3580
3581       if(dest.kind != classType && source.kind == classType && source._class && source._class.registered &&
3582          !strcmp(source._class.registered.fullName, "unichar" /*"ecere::com::unichar"*/))
3583       {
3584          FreeType(source);
3585          source = Type { kind = intType, isSigned = false, refCount = 1 };
3586       }
3587
3588       if(dest.kind == classType)
3589       {
3590          Class _class = dest._class ? dest._class.registered : null;
3591
3592          if(_class && _class.type == unitClass)
3593          {
3594             if(source.kind != classType)
3595             {
3596                Type tempType { };
3597                Type tempDest, tempSource;
3598
3599                for(; _class.base.type != systemClass; _class = _class.base);
3600                tempSource = dest;
3601                tempDest = tempType;
3602
3603                tempType.kind = classType;
3604                if(!_class.symbol)
3605                   _class.symbol = FindClass(_class.fullName);
3606
3607                tempType._class = _class.symbol;
3608                tempType.truth = dest.truth;
3609                if(tempType._class)
3610                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3611
3612                // NOTE: To handle bad warnings on int64 vs 32 bit eda::Id incompatibilities
3613                backupSourceExpType = sourceExp.expType;
3614                if(dest.passAsTemplate)
3615                {
3616                   // Don't carry passAsTemplate
3617                   sourceExp.expType = { };
3618                   CopyTypeInto(sourceExp.expType, dest);
3619                   sourceExp.expType.passAsTemplate = false;
3620                }
3621                else
3622                {
3623                   sourceExp.expType = dest;
3624                   dest.refCount++;
3625                }
3626                //sourceExp.expType = MkClassType(_class.fullName);
3627                flag = true;
3628
3629                delete tempType;
3630             }
3631          }
3632
3633
3634          // Why wasn't there something like this?
3635          if(_class && _class.type == bitClass && source.kind != classType)
3636          {
3637             if(!dest._class.registered.dataType)
3638                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3639             if(MatchTypes(source, dest._class.registered.dataType, conversions, null, null, true, true, false, false, warnConst))
3640             {
3641                FreeType(source);
3642                FreeType(sourceExp.expType);
3643                source = sourceExp.expType = MkClassType(dest._class.string);
3644                source.refCount++;
3645
3646                //source.kind = classType;
3647                //source._class = dest._class;
3648             }
3649          }
3650
3651          // Adding two enumerations
3652          /*
3653          if(_class && _class.type == enumClass && source.kind == classType && source._class && source._class.registered && source._class.registered.type == enumClass)
3654          {
3655             if(!source._class.registered.dataType)
3656                source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3657             if(!dest._class.registered.dataType)
3658                dest._class.registered.dataType = ProcessTypeString(dest._class.registered.dataTypeString, false);
3659
3660             if(MatchTypes(source._class.registered.dataType, dest._class.registered.dataType, conversions, null, null, true, false, false))
3661             {
3662                FreeType(source);
3663                source = sourceExp.expType = MkClassType(dest._class.string);
3664                source.refCount++;
3665
3666                //source.kind = classType;
3667                //source._class = dest._class;
3668             }
3669          }*/
3670
3671          if(_class && !strcmp(_class.fullName, "ecere::com::Class") && source.kind == pointerType && source.type && source.type.kind == charType && sourceExp.type == stringExp)
3672          {
3673             OldList * specs = MkList();
3674             Declarator decl;
3675             char string[1024];
3676
3677             ReadString(string, sourceExp.string);
3678             decl = SpecDeclFromString(string, specs, null);
3679
3680             FreeExpContents(sourceExp);
3681             FreeType(sourceExp.expType);
3682
3683             sourceExp.type = classExp;
3684             sourceExp._classExp.specifiers = specs;
3685             sourceExp._classExp.decl = decl;
3686             sourceExp.expType = dest;
3687             dest.refCount++;
3688
3689             FreeType(source);
3690             FreeType(dest);
3691             if(backupSourceExpType) FreeType(backupSourceExpType);
3692             return true;
3693          }
3694       }
3695       else if(source.kind == classType)
3696       {
3697          Class _class = source._class ? source._class.registered : null;
3698
3699          if(_class && (_class.type == unitClass || /*!strcmp(_class.fullName, "bool") || _class.type == enumClass || */_class.type == bitClass ))  // TOCHECK: enumClass, bitClass is new here...
3700          {
3701             /*
3702             if(dest.kind != classType)
3703             {
3704                // Testing this simpler piece of code... (Broke Units Conversion to no unit Logic)
3705                if(!source._class.registered.dataType)
3706                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3707
3708                FreeType(dest);
3709                dest = MkClassType(source._class.string);
3710                //if(MatchTypes(source._class.registered.dataType, dest, conversions, null, null, true, false, false))
3711                //   dest = MkClassType(source._class.string);
3712             }
3713             */
3714
3715             if(dest.kind != classType)
3716             {
3717                Type tempType { };
3718                Type tempDest, tempSource;
3719
3720                if(!source._class.registered.dataType)
3721                   source._class.registered.dataType = ProcessTypeString(source._class.registered.dataTypeString, false);
3722
3723                for(; _class.base.type != systemClass; _class = _class.base);
3724                tempDest = source;
3725                tempSource = tempType;
3726                tempType.kind = classType;
3727                tempType._class = FindClass(_class.fullName);
3728                tempType.truth = source.truth;
3729                tempType.classObjectType = source.classObjectType;
3730
3731                if(tempType._class)
3732                   MatchTypes(tempSource, tempDest, conversions, null, null, true, true, false, false, warnConst);
3733
3734                // PUT THIS BACK TESTING UNITS?
3735                if(conversions && conversions.last)
3736                {
3737                   ((Conversion)(conversions.last)).resultType = dest;
3738                   dest.refCount++;
3739                }
3740
3741                FreeType(sourceExp.expType);
3742                sourceExp.expType = MkClassType(_class.fullName);
3743                sourceExp.expType.truth = source.truth;
3744                sourceExp.expType.classObjectType = source.classObjectType;
3745
3746                // *** This if was commented out, put it back because "int a =^ Destroy()" shows up bool enum values in autocomplete ***
3747
3748                if(!sourceExp.destType)
3749                {
3750                   FreeType(sourceExp.destType);
3751                   sourceExp.destType = sourceExp.expType;
3752                   if(sourceExp.expType)
3753                      sourceExp.expType.refCount++;
3754                }
3755                //flag = true;
3756                //source = _class.dataType;
3757
3758
3759                // TOCHECK: TESTING THIS NEW CODE
3760                if(!_class.dataType)
3761                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3762                FreeType(dest);
3763                dest = MkClassType(source._class.string);
3764                dest.truth = source.truth;
3765                dest.classObjectType = source.classObjectType;
3766
3767                FreeType(source);
3768                source = _class.dataType;
3769                source.refCount++;
3770
3771                delete tempType;
3772             }
3773          }
3774       }
3775
3776       if(!flag)
3777       {
3778          if(MatchTypes(source, dest, conversions, null, null, true, true, false, false, warnConst))
3779          {
3780             FreeType(source);
3781             FreeType(dest);
3782             return true;
3783          }
3784       }
3785
3786       // Implicit Casts
3787       /*
3788       if(source.kind == classType)
3789       {
3790          Class _class = source._class.registered;
3791          if(_class.type == unitClass)
3792          {
3793             if(!_class.dataType)
3794                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3795             source = _class.dataType;
3796          }
3797       }*/
3798
3799       if(dest.kind == classType)
3800       {
3801          Class _class = dest._class ? dest._class.registered : null;
3802          bool fittingValue = false;
3803          if(_class && _class.type == enumClass)
3804          {
3805             Class enumClass = eSystem_FindClass(privateModule, "enum");
3806             EnumClassData c = ACCESS_CLASSDATA(_class, enumClass);
3807             if(c && value >= 0 && value <= c.largest)
3808                fittingValue = true;
3809          }
3810
3811          if(_class && !dest.truth && (_class.type == unitClass || fittingValue ||
3812             (/*_class.type == enumClass*/_class.type != structClass && !value && source.kind == intType) || _class.type == bitClass))   // TOCHECK: enumClass, bitClass is new here...
3813          {
3814             if(_class.type == normalClass || _class.type == noHeadClass)
3815             {
3816                Expression newExp { };
3817                *newExp = *sourceExp;
3818                if(sourceExp.destType) sourceExp.destType.refCount++;
3819                if(sourceExp.expType)  sourceExp.expType.refCount++;
3820                sourceExp.type = castExp;
3821                sourceExp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
3822                sourceExp.cast.exp = newExp;
3823                FreeType(sourceExp.expType);
3824                sourceExp.expType = null;
3825                ProcessExpressionType(sourceExp);
3826
3827                // In Debugger, this helps with addresses (e.g. null pointers) that end up casted to a void *: keeps a classType instead of a pointerType
3828                if(!inCompiler)
3829                {
3830                   FreeType(sourceExp.expType);
3831                   sourceExp.expType = dest;
3832                }
3833
3834                FreeType(source);
3835                if(inCompiler) FreeType(dest);
3836
3837                if(backupSourceExpType) FreeType(backupSourceExpType);
3838                return true;
3839             }
3840
3841             if(!_class.dataType)
3842                _class.dataType = ProcessTypeString(_class.dataTypeString, false);
3843             FreeType(dest);
3844             dest = _class.dataType;
3845             dest.refCount++;
3846          }
3847
3848          // Accept lower precision types for units, since we want to keep the unit type
3849          if(dest.kind == doubleType &&
3850             (source.kind == doubleType || source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType ||
3851              source.kind == charType || source.kind == _BoolType))
3852          {
3853             specs = MkListOne(MkSpecifier(DOUBLE));
3854          }
3855          else if(dest.kind == floatType &&
3856             (source.kind == floatType || dest.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3857             source.kind == _BoolType || source.kind == doubleType))
3858          {
3859             specs = MkListOne(MkSpecifier(FLOAT));
3860          }
3861          else if(dest.kind == int64Type && (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == charType ||
3862             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3863          {
3864             specs = MkList();
3865             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3866             ListAdd(specs, MkSpecifier(INT64));
3867          }
3868          else if(dest.kind == intType && (source.kind == intType || source.kind == shortType || source.kind == charType ||
3869             source.kind == _BoolType || source.kind == floatType || source.kind == doubleType))
3870          {
3871             specs = MkList();
3872             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3873             ListAdd(specs, MkSpecifier(INT));
3874          }
3875          else if(dest.kind == shortType && (source.kind == shortType || source.kind == charType || source.kind == _BoolType || source.kind == intType ||
3876             source.kind == floatType || source.kind == doubleType))
3877          {
3878             specs = MkList();
3879             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3880             ListAdd(specs, MkSpecifier(SHORT));
3881          }
3882          else if(dest.kind == charType && (source.kind == charType || source.kind == _BoolType || source.kind == shortType || source.kind == intType ||
3883             source.kind == floatType || source.kind == doubleType))
3884          {
3885             specs = MkList();
3886             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3887             ListAdd(specs, MkSpecifier(CHAR));
3888          }
3889          else
3890          {
3891             FreeType(source);
3892             FreeType(dest);
3893             if(backupSourceExpType)
3894             {
3895                // Failed to convert: revert previous exp type
3896                if(sourceExp.expType) FreeType(sourceExp.expType);
3897                sourceExp.expType = backupSourceExpType;
3898             }
3899             return false;
3900          }
3901       }
3902       else if(dest.kind == doubleType &&
3903          (source.kind == doubleType || source.kind == floatType || source.kind == int64Type || source.kind == intType || source.kind == enumType || source.kind == shortType ||
3904           source.kind == _BoolType || source.kind == charType))
3905       {
3906          specs = MkListOne(MkSpecifier(DOUBLE));
3907       }
3908       else if(dest.kind == floatType &&
3909          (source.kind == floatType || source.kind == enumType || source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3910       {
3911          specs = MkListOne(MkSpecifier(FLOAT));
3912       }
3913       else if(dest.kind == _BoolType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3914          (value == 1 || value == 0))
3915       {
3916          specs = MkList();
3917          ListAdd(specs, MkSpecifier(BOOL));
3918       }
3919       else if(dest.kind == charType && (source.kind == _BoolType || source.kind == charType || source.kind == enumType || source.kind == shortType || source.kind == intType) &&
3920          (dest.isSigned ? (value >= -128 && value <= 127) : (value >= 0 && value <= 255)))
3921       {
3922          if(source.kind == intType)
3923             return true;
3924          else
3925          {
3926             specs = MkList();
3927             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3928             ListAdd(specs, MkSpecifier(CHAR));
3929          }
3930       }
3931       else if(dest.kind == shortType && (source.kind == enumType || source.kind == _BoolType || source.kind == charType || source.kind == shortType ||
3932          (source.kind == intType && (dest.isSigned ? (value >= -32768 && value <= 32767) : (value >= 0 && value <= 65535)))))
3933       {
3934          if(source.kind == intType)
3935             return true;
3936          else
3937          {
3938             specs = MkList();
3939             if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3940             ListAdd(specs, MkSpecifier(SHORT));
3941          }
3942       }
3943       else if(dest.kind == intType && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType))
3944       {
3945          specs = MkList();
3946          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3947          ListAdd(specs, MkSpecifier(INT));
3948       }
3949       else if(dest.kind == int64Type && (source.kind == enumType || source.kind == shortType || source.kind == _BoolType || source.kind == charType || source.kind == intType || source.kind == int64Type))
3950       {
3951          specs = MkList();
3952          if(!dest.isSigned) ListAdd(specs, MkSpecifier(UNSIGNED));
3953          ListAdd(specs, MkSpecifier(INT64));
3954       }
3955       else if(dest.kind == enumType &&
3956          (source.kind == int64Type || source.kind == intType || source.kind == shortType || source.kind == _BoolType || source.kind == charType))
3957       {
3958          specs = MkListOne(MkEnum(MkIdentifier(dest.enumName), null));
3959       }
3960       else
3961       {
3962          FreeType(source);
3963          FreeType(dest);
3964          if(backupSourceExpType)
3965          {
3966             // Failed to convert: revert previous exp type
3967             if(sourceExp.expType) FreeType(sourceExp.expType);
3968             sourceExp.expType = backupSourceExpType;
3969          }
3970          return false;
3971       }
3972
3973       if(!flag && !sourceExp.opDestType)
3974       {
3975          Expression newExp { };
3976          *newExp = *sourceExp;
3977          newExp.prev = null;
3978          newExp.next = null;
3979          if(sourceExp.destType) sourceExp.destType.refCount++;
3980          if(sourceExp.expType)  sourceExp.expType.refCount++;
3981
3982          sourceExp.type = castExp;
3983          if(realDest.kind == classType)
3984          {
3985             sourceExp.cast.typeName = QMkClass(realDest._class.string, null);
3986             FreeList(specs, FreeSpecifier);
3987          }
3988          else
3989             sourceExp.cast.typeName = MkTypeName(specs, null);
3990          if(newExp.type == opExp)
3991          {
3992             sourceExp.cast.exp = MkExpBrackets(MkListOne(newExp));
3993          }
3994          else
3995             sourceExp.cast.exp = newExp;
3996
3997          FreeType(sourceExp.expType);
3998          sourceExp.expType = null;
3999          ProcessExpressionType(sourceExp);
4000       }
4001       else
4002          FreeList(specs, FreeSpecifier);
4003
4004       FreeType(dest);
4005       FreeType(source);
4006       if(backupSourceExpType) FreeType(backupSourceExpType);
4007
4008       return true;
4009    }
4010    else
4011    {
4012       if(computedExp != nbExp)
4013       {
4014          FreeExpression(computedExp);
4015          computedExp = nbExp;
4016       }
4017
4018       while((sourceExp.type == bracketsExp || sourceExp.type == extensionExpressionExp) && sourceExp.list) sourceExp = sourceExp.list->last;
4019       if(sourceExp.type == identifierExp)
4020       {
4021          Identifier id = sourceExp.identifier;
4022          if(dest.kind == classType)
4023          {
4024             if(dest._class && dest._class.registered && dest._class.registered.type == enumClass)
4025             {
4026                Class _class = dest._class.registered;
4027                Class enumClass = eSystem_FindClass(privateModule, "enum");
4028                if(enumClass)
4029                {
4030                   for( ; _class && _class.type == ClassType::enumClass; _class = _class.base)
4031                   {
4032                      NamedLink64 value;
4033                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4034                      for(value = e.values.first; value; value = value.next)
4035                      {
4036                         if(!strcmp(value.name, id.string))
4037                            break;
4038                      }
4039                      if(value)
4040                      {
4041                         FreeType(sourceExp.expType);
4042
4043                         sourceExp.isConstant = true;
4044                         sourceExp.expType = MkClassType(_class.fullName);
4045                         if(inCompiler || inPreCompiler || inDebugger)
4046                         {
4047                            FreeExpContents(sourceExp);
4048
4049                            sourceExp.type = constantExp;
4050                            if(_class.dataTypeString && (!strcmp(_class.dataTypeString, "int") || !strcmp(_class.dataTypeString, "int64") || !strcmp(_class.dataTypeString, "short") || !strcmp(_class.dataTypeString, "char"))) // _class cannot be null here!
4051                               sourceExp.constant = PrintInt64(value.data);
4052                            else
4053                               sourceExp.constant = PrintUInt64(value.data);
4054                            //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
4055                         }
4056                         FreeType(dest);
4057                         return true;
4058                      }
4059                   }
4060                }
4061             }
4062          }
4063
4064          // Loop through all enum classes
4065          if(dest.classObjectType != typedObject && dest.kind == classType /*!= ellipsisType */&& MatchWithEnums_Module(privateModule, sourceExp, dest, id.string, conversions))
4066          {
4067             FreeType(dest);
4068             return true;
4069          }
4070       }
4071       FreeType(dest);
4072    }
4073    return false;
4074 }
4075
4076 #define TERTIARY(o, name, m, t, p) \
4077    static bool name(Expression exp, Operand op1, Operand op2, Operand op3)   \
4078    {                                                              \
4079       exp.type = constantExp;                                    \
4080       exp.string = p(op1.m ? op2.m : op3.m);                     \
4081       if(!exp.expType) \
4082          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4083       return true;                                                \
4084    }
4085
4086 #define BINARY(o, name, m, t, p) \
4087    static bool name(Expression exp, Operand op1, Operand op2)   \
4088    {                                                              \
4089       t value2 = op2.m;                                           \
4090       exp.type = constantExp;                                    \
4091       exp.string = p((t)(op1.m o value2));                     \
4092       if(!exp.expType) \
4093          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4094       return true;                                                \
4095    }
4096
4097 #define BINARY_DIVIDEINT(o, name, m, t, p) \
4098    static bool name(Expression exp, Operand op1, Operand op2)   \
4099    {                                                              \
4100       t value2 = op2.m;                                           \
4101       exp.type = constantExp;                                    \
4102       exp.string = p(value2 ? ((t)(op1.m o value2)) : 0);             \
4103       if(!exp.expType) \
4104          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4105       return true;                                                \
4106    }
4107
4108 #define BINARY_DIVIDEREAL(o, name, m, t, p) \
4109    static bool name(Expression exp, Operand op1, Operand op2)   \
4110    {                                                              \
4111       t value2 = op2.m;                                           \
4112       exp.type = constantExp;                                    \
4113       exp.string = p((t)(op1.m o value2));             \
4114       if(!exp.expType) \
4115          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4116       return true;                                                \
4117    }
4118
4119 #define UNARY(o, name, m, t, p) \
4120    static bool name(Expression exp, Operand op1)                \
4121    {                                                              \
4122       exp.type = constantExp;                                    \
4123       exp.string = p((t)(o op1.m));                                   \
4124       if(!exp.expType) \
4125          { exp.expType = op1.type; if(op1.type) op1.type.refCount++; } \
4126       return true;                                                \
4127    }
4128
4129 #define OPERATOR_ALL(macro, o, name) \
4130    macro(o, Int##name, i, int, PrintInt) \
4131    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4132    macro(o, Int64##name, i64, int64, PrintInt64) \
4133    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4134    macro(o, Short##name, s, short, PrintShort) \
4135    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4136    macro(o, Char##name, c, char, PrintChar) \
4137    macro(o, UChar##name, uc, unsigned char, PrintUChar) \
4138    macro(o, Float##name, f, float, PrintFloat) \
4139    macro(o, Double##name, d, double, PrintDouble)
4140
4141 #define OPERATOR_INTTYPES(macro, o, name) \
4142    macro(o, Int##name, i, int, PrintInt) \
4143    macro(o, UInt##name, ui, unsigned int, PrintUInt) \
4144    macro(o, Int64##name, i64, int64, PrintInt64) \
4145    macro(o, UInt64##name, ui64, uint64, PrintUInt64) \
4146    macro(o, Short##name, s, short, PrintShort) \
4147    macro(o, UShort##name, us, unsigned short, PrintUShort) \
4148    macro(o, Char##name, c, char, PrintChar) \
4149    macro(o, UChar##name, uc, unsigned char, PrintUChar)
4150
4151 #define OPERATOR_REALTYPES(macro, o, name) \
4152    macro(o, Float##name, f, float, PrintFloat) \
4153    macro(o, Double##name, d, double, PrintDouble)
4154
4155 // binary arithmetic
4156 OPERATOR_ALL(BINARY, +, Add)
4157 OPERATOR_ALL(BINARY, -, Sub)
4158 OPERATOR_ALL(BINARY, *, Mul)
4159 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /, Div)
4160 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /, Div)
4161 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %, Mod)
4162
4163 // unary arithmetic
4164 OPERATOR_ALL(UNARY, -, Neg)
4165
4166 // unary arithmetic increment and decrement
4167 OPERATOR_ALL(UNARY, ++, Inc)
4168 OPERATOR_ALL(UNARY, --, Dec)
4169
4170 // binary arithmetic assignment
4171 OPERATOR_ALL(BINARY, =, Asign)
4172 OPERATOR_ALL(BINARY, +=, AddAsign)
4173 OPERATOR_ALL(BINARY, -=, SubAsign)
4174 OPERATOR_ALL(BINARY, *=, MulAsign)
4175 OPERATOR_INTTYPES(BINARY_DIVIDEINT, /=, DivAsign)
4176 OPERATOR_REALTYPES(BINARY_DIVIDEREAL, /=, DivAsign)
4177 OPERATOR_INTTYPES(BINARY_DIVIDEINT, %=, ModAsign)
4178
4179 // binary bitwise
4180 OPERATOR_INTTYPES(BINARY, &, BitAnd)
4181 OPERATOR_INTTYPES(BINARY, |, BitOr)
4182 OPERATOR_INTTYPES(BINARY, ^, BitXor)
4183 OPERATOR_INTTYPES(BINARY, <<, LShift)
4184 OPERATOR_INTTYPES(BINARY, >>, RShift)
4185
4186 // unary bitwise
4187 OPERATOR_INTTYPES(UNARY, ~, BitNot)
4188
4189 // binary bitwise assignment
4190 OPERATOR_INTTYPES(BINARY, &=, AndAsign)
4191 OPERATOR_INTTYPES(BINARY, |=, OrAsign)
4192 OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
4193 OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
4194 OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
4195
4196 // unary logical negation
4197 OPERATOR_INTTYPES(UNARY, !, Not)
4198
4199 // binary logical equality
4200 OPERATOR_ALL(BINARY, ==, Equ)
4201 OPERATOR_ALL(BINARY, !=, Nqu)
4202
4203 // binary logical
4204 OPERATOR_ALL(BINARY, &&, And)
4205 OPERATOR_ALL(BINARY, ||, Or)
4206
4207 // binary logical relational
4208 OPERATOR_ALL(BINARY, >, Grt)
4209 OPERATOR_ALL(BINARY, <, Sma)
4210 OPERATOR_ALL(BINARY, >=, GrtEqu)
4211 OPERATOR_ALL(BINARY, <=, SmaEqu)
4212
4213 // tertiary condition operator
4214 OPERATOR_INTTYPES(TERTIARY, ?, Cond)
4215
4216 //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
4217 #define OPERATOR_TABLE_ALL(name, type) \
4218     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, type##Mod, \
4219                           type##Neg, \
4220                           type##Inc, type##Dec, \
4221                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, type##ModAsign, \
4222                           type##BitAnd, type##BitOr, type##BitXor, type##LShift, type##RShift, \
4223                           type##BitNot, \
4224                           type##AndAsign, type##OrAsign, type##XorAsign, type##LShiftAsign, type##RShiftAsign, \
4225                           type##Not, \
4226                           type##Equ, type##Nqu, \
4227                           type##And, type##Or, \
4228                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu, type##Cond \
4229                         }; \
4230
4231 #define OPERATOR_TABLE_INTTYPES(name, type) \
4232     OpTable name##Ops = { type##Add, type##Sub, type##Mul, type##Div, null, \
4233                           type##Neg, \
4234                           type##Inc, type##Dec, \
4235                           type##Asign, type##AddAsign, type##SubAsign, type##MulAsign, type##DivAsign, null, \
4236                           null, null, null, null, null, \
4237                           null, \
4238                           null, null, null, null, null, \
4239                           null, \
4240                           type##Equ, type##Nqu, \
4241                           type##And, type##Or, \
4242                           type##Grt, type##Sma, type##GrtEqu, type##SmaEqu \
4243                         }; \
4244
4245 OPERATOR_TABLE_ALL(int, Int)
4246 OPERATOR_TABLE_ALL(uint, UInt)
4247 OPERATOR_TABLE_ALL(int64, Int64)
4248 OPERATOR_TABLE_ALL(uint64, UInt64)
4249 OPERATOR_TABLE_ALL(short, Short)
4250 OPERATOR_TABLE_ALL(ushort, UShort)
4251 OPERATOR_TABLE_INTTYPES(float, Float)
4252 OPERATOR_TABLE_INTTYPES(double, Double)
4253 OPERATOR_TABLE_ALL(char, Char)
4254 OPERATOR_TABLE_ALL(uchar, UChar)
4255
4256 //OpTable intOps =    {    IntAdd,    IntSub,    IntMul,    IntDiv,    IntMod,    IntExp,    IntNot,    IntBwn,    IntOr,    IntAnd,    IntEqu,    IntNqu,    IntGrt,    IntSma,    IntGrtEqu,    IntSmaEqu,    IntNeg,    IntLBitSft,    IntRBitSft };
4257 //OpTable uintOps =   {   UIntAdd,   UIntSub,   UIntMul,   UIntDiv,   UIntMod,   UIntExp,   UIntNot,   UIntBwn,   UIntOr,   UIntAnd,   UIntEqu,   UIntNqu,   UIntGrt,   UIntSma,   UIntGrtEqu,   UIntSmaEqu,   UIntNeg,   UIntLBitSft,   UIntRBitSft };
4258 //OpTable shortOps =  {  ShortAdd,  ShortSub,  ShortMul,  ShortDiv,  ShortMod,  ShortExp,  ShortNot,  ShortBwn,  ShortOr,  ShortAnd,  ShortEqu,  ShortNqu,  ShortGrt,  ShortSma,  ShortGrtEqu,  ShortSmaEqu,  ShortNeg,  ShortLBitSft,  ShortRBitSft };
4259 //OpTable ushortOps = { UShortAdd, UShortSub, UShortMul, UShortDiv, UShortMod, UShortExp, UShortNot, UShortBwn, UShortOr, UShortAnd, UShortEqu, UShortNqu, UShortGrt, UShortSma, UShortGrtEqu, UShortSmaEqu, UShortNeg, UShortLBitSft, UShortRBitSft };
4260 //OpTable floatOps =  {  FloatAdd,  FloatSub,  FloatMul,  FloatDiv,      null,      null,      null,      null,     null,      null,  FloatEqu,  FloatNqu,  FloatGrt,  FloatSma,  FloatGrtEqu,  FloatSmaEqu,  FloatNeg,          null,          null };
4261 //OpTable doubleOps = { DoubleAdd, DoubleSub, DoubleMul, DoubleDiv,      null,      null,      null,      null,     null,      null, DoubleEqu, DoubleNqu, DoubleGrt, DoubleSma, DoubleGrtEqu, DoubleSmaEqu, DoubleNeg,          null,          null };
4262 //OpTable charOps =   {   CharAdd,   CharSub,   CharMul,   CharDiv,   CharMod,   CharExp,   CharNot,   CharBwn,   CharOr,   CharAnd,   CharEqu,   CharNqu,   CharGrt,   CharSma,   CharGrtEqu,   CharSmaEqu,   CharNeg,   CharLBitSft,   CharRBitSft };
4263 //OpTable ucharOps =  {  UCharAdd,  UCharSub,  UCharMul,  UCharDiv,  UCharMod,  UCharExp,  UCharNot,  UCharBwn,  UCharOr,  UCharAnd,  UCharEqu,  UCharNqu,  UCharGrt,  UCharSma,  UCharGrtEqu,  UCharSmaEqu,  UCharNeg,  UCharLBitSft,  UCharRBitSft };
4264
4265 public void ReadString(char * output,  char * string)
4266 {
4267    int len = strlen(string);
4268    int c,d = 0;
4269    bool quoted = false, escaped = false;
4270    for(c = 0; c<len; c++)
4271    {
4272       char ch = string[c];
4273       if(escaped)
4274       {
4275          switch(ch)
4276          {
4277             case 'n': output[d] = '\n'; break;
4278             case 't': output[d] = '\t'; break;
4279             case 'a': output[d] = '\a'; break;
4280             case 'b': output[d] = '\b'; break;
4281             case 'f': output[d] = '\f'; break;
4282             case 'r': output[d] = '\r'; break;
4283             case 'v': output[d] = '\v'; break;
4284             case '\\': output[d] = '\\'; break;
4285             case '\"': output[d] = '\"'; break;
4286             case '\'': output[d] = '\''; break;
4287             default: output[d] = ch;
4288          }
4289          d++;
4290          escaped = false;
4291       }
4292       else
4293       {
4294          if(ch == '\"')
4295             quoted ^= true;
4296          else if(quoted)
4297          {
4298             if(ch == '\\')
4299                escaped = true;
4300             else
4301                output[d++] = ch;
4302          }
4303       }
4304    }
4305    output[d] = '\0';
4306 }
4307
4308 // String Unescape Copy
4309
4310 // TOFIX: THIS DOESN'T HANDLE NUMERIC ESCAPE CODES (OCTAL/HEXADECIMAL...)?
4311 // This is the same as ReadString above (which also misses numeric escape codes) except it doesn't handle external quotes
4312 public int UnescapeString(char * d, char * s, int len)
4313 {
4314    int j = 0, k = 0;
4315    char ch;
4316    while(j < len && (ch = s[j]))
4317    {
4318       switch(ch)
4319       {
4320          case '\\':
4321             switch((ch = s[++j]))
4322             {
4323                case 'n': d[k] = '\n'; break;
4324                case 't': d[k] = '\t'; break;
4325                case 'a': d[k] = '\a'; break;
4326                case 'b': d[k] = '\b'; break;
4327                case 'f': d[k] = '\f'; break;
4328                case 'r': d[k] = '\r'; break;
4329                case 'v': d[k] = '\v'; break;
4330                case '\\': d[k] = '\\'; break;
4331                case '\"': d[k] = '\"'; break;
4332                case '\'': d[k] = '\''; break;
4333                default: d[k] = '\\'; d[k] = ch;
4334             }
4335             break;
4336          default:
4337             d[k] = ch;
4338       }
4339       j++, k++;
4340    }
4341    d[k] = '\0';
4342    return k;
4343 }
4344
4345 public char * OffsetEscapedString(char * s, int len, int offset)
4346 {
4347    char ch;
4348    int j = 0, k = 0;
4349    while(j < len && k < offset && (ch = s[j]))
4350    {
4351       if(ch == '\\') ++j;
4352       j++, k++;
4353    }
4354    return (k == offset) ? s + j : null;
4355 }
4356
4357 public Operand GetOperand(Expression exp)
4358 {
4359    Operand op { };
4360    Type type = exp.expType;
4361    if(type)
4362    {
4363       while(type.kind == classType &&
4364          type._class.registered && (type._class.registered.type == bitClass || type._class.registered.type == unitClass || type._class.registered.type == enumClass))
4365       {
4366          if(!type._class.registered.dataType)
4367             type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
4368          type = type._class.registered.dataType;
4369
4370       }
4371       if(exp.type == stringExp && op.kind == pointerType)
4372       {
4373          op.ui64 = (uint64)(uintptr)exp.string;
4374          op.kind = pointerType;
4375          op.ops = uint64Ops;
4376       }
4377       else if(exp.isConstant && exp.type == constantExp)
4378       {
4379          op.kind = type.kind;
4380          op.type = type;
4381
4382          switch(op.kind)
4383          {
4384             case _BoolType:
4385             case charType:
4386             {
4387                if(exp.constant[0] == '\'')
4388                {
4389                   op.c = exp.constant[1];
4390                   op.ops = charOps;
4391                }
4392                else if(type.isSigned)
4393                {
4394                   op.c = (char)strtol(exp.constant, null, 0);
4395                   op.ops = charOps;
4396                }
4397                else
4398                {
4399                   op.uc = (unsigned char)strtoul(exp.constant, null, 0);
4400                   op.ops = ucharOps;
4401                }
4402                break;
4403             }
4404             case shortType:
4405                if(exp.constant[0] == '\'')
4406                {
4407                   op.s = exp.constant[1];
4408                   op.ops = shortOps;
4409                }
4410                else if(type.isSigned)
4411                {
4412                   op.s = (short)strtol(exp.constant, null, 0);
4413                   op.ops = shortOps;
4414                }
4415                else
4416                {
4417                   op.us = (unsigned short)strtoul(exp.constant, null, 0);
4418                   op.ops = ushortOps;
4419                }
4420                break;
4421             case intType:
4422             case longType:
4423                if(exp.constant[0] == '\'')
4424                {
4425                   op.i = exp.constant[1];
4426                   op.ops = intOps;
4427                }
4428                else if(type.isSigned)
4429                {
4430                   op.i = (int)strtol(exp.constant, null, 0);
4431                   op.ops = intOps;
4432                }
4433                else
4434                {
4435                   op.ui = (unsigned int)strtoul(exp.constant, null, 0);
4436                   op.ops = uintOps;
4437                }
4438                op.kind = intType;
4439                break;
4440             case int64Type:
4441                if(type.isSigned)
4442                {
4443                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4444                   op.ops = int64Ops;
4445                }
4446                else
4447                {
4448                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4449                   op.ops = uint64Ops;
4450                }
4451                op.kind = int64Type;
4452                break;
4453             case intPtrType:
4454                if(type.isSigned)
4455                {
4456                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4457                   op.ops = int64Ops;
4458                }
4459                else
4460                {
4461                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4462                   op.ops = uint64Ops;
4463                }
4464                op.kind = int64Type;
4465                break;
4466             case intSizeType:
4467                if(type.isSigned)
4468                {
4469                   op.i64 = (int64)_strtoi64(exp.constant, null, 0);
4470                   op.ops = int64Ops;
4471                }
4472                else
4473                {
4474                   op.ui64 = (uint64)_strtoui64(exp.constant, null, 0);
4475                   op.ops = uint64Ops;
4476                }
4477                op.kind = int64Type;
4478                break;
4479             case floatType:
4480                if(!strcmp(exp.constant, "inf")) op.f = float::inf();
4481                else if(!strcmp(exp.constant, "-inf")) op.f = -float::inf();
4482                else if(!strcmp(exp.constant, "nan")) op.f = float::nan();
4483                else if(!strcmp(exp.constant, "-nan")) op.f = -float::nan();
4484                else
4485                   op.f = (float)strtod(exp.constant, null);
4486                op.ops = floatOps;
4487                break;
4488             case doubleType:
4489                if(!strcmp(exp.constant, "inf")) op.d = double::inf();
4490                else if(!strcmp(exp.constant, "-inf")) op.d = -double::inf();
4491                else if(!strcmp(exp.constant, "nan")) op.d = double::nan();
4492                else if(!strcmp(exp.constant, "-nan")) op.d = -double::nan();
4493                else
4494                   op.d = (double)strtod(exp.constant, null);
4495                op.ops = doubleOps;
4496                break;
4497             //case classType:    For when we have operator overloading...
4498             // Pointer additions
4499             //case functionType:
4500             case arrayType:
4501             case pointerType:
4502             case classType:
4503                op.ui64 = _strtoui64(exp.constant, null, 0);
4504                op.kind = pointerType;
4505                op.ops = uint64Ops;
4506                // op.ptrSize =
4507                break;
4508          }
4509       }
4510    }
4511    return op;
4512 }
4513
4514 static int64 GetEnumValue(Class _class, void * ptr)
4515 {
4516    int64 v = 0;
4517    switch(_class.typeSize)
4518    {
4519       case 8:
4520          if(!strcmp(_class.dataTypeString, "uint64"))
4521             v = (int64)*(uint64 *)ptr;
4522          else
4523             v = (int64)*(int64 *)ptr;
4524          break;
4525       case 4:
4526          if(!strcmp(_class.dataTypeString, "uint"))
4527             v = (int64)*(uint *)ptr;
4528          else
4529             v = (int64)*(int *)ptr;
4530          break;
4531       case 2:
4532          if(!strcmp(_class.dataTypeString, "uint16"))
4533             v = (int64)*(uint16 *)ptr;
4534          else
4535             v = (int64)*(short *)ptr;
4536          break;
4537       case 1:
4538          if(!strcmp(_class.dataTypeString, "byte"))
4539             v = (int64)*(byte *)ptr;
4540          else
4541             v = (int64)*(char *)ptr;
4542          break;
4543    }
4544    return v;
4545 }
4546
4547 static __attribute__((unused)) void UnusedFunction()
4548 {
4549    int a;
4550    a.OnGetString(0,0,0);
4551 }
4552 default:
4553 extern int __ecereVMethodID_class_OnGetString;
4554 public:
4555
4556 static void PopulateInstanceProcessMember(Instantiation inst, OldList * memberList, DataMember parentDataMember, uint offset)
4557 {
4558    DataMember dataMember;
4559    for(dataMember = parentDataMember.members.first; dataMember; dataMember = dataMember.next)
4560    {
4561       if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4562          PopulateInstanceProcessMember(inst, memberList, dataMember, offset + dataMember.offset);
4563       else
4564       {
4565          Expression exp { };
4566          MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4567          Type type;
4568          void * ptr = inst.data + dataMember.offset + offset;
4569          char * result = null;
4570          exp.loc = member.loc = inst.loc;
4571          ((Identifier)member.identifiers->first).loc = inst.loc;
4572
4573          if(!dataMember.dataType)
4574             dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4575          type = dataMember.dataType;
4576          if(type.kind == classType)
4577          {
4578             Class _class = type._class.registered;
4579             if(_class.type == enumClass)
4580             {
4581                Class enumClass = eSystem_FindClass(privateModule, "enum");
4582                if(enumClass)
4583                {
4584                   EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4585                   NamedLink64 item;
4586                   for(item = e.values.first; item; item = item.next)
4587                   {
4588                      if(item.data == GetEnumValue(_class, ptr))
4589                      {
4590                         result = item.name;
4591                         break;
4592                      }
4593                   }
4594                   if(result)
4595                   {
4596                      exp.identifier = MkIdentifier(result);
4597                      exp.type = identifierExp;
4598                      exp.destType = MkClassType(_class.fullName);
4599                      ProcessExpressionType(exp);
4600                   }
4601                }
4602             }
4603             if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4604             {
4605                if(!_class.dataType)
4606                   _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4607                type = _class.dataType;
4608             }
4609          }
4610          if(!result)
4611          {
4612             switch(type.kind)
4613             {
4614                case floatType:
4615                {
4616                   FreeExpContents(exp);
4617
4618                   exp.constant = PrintFloat(*(float*)ptr);
4619                   exp.type = constantExp;
4620                   break;
4621                }
4622                case doubleType:
4623                {
4624                   FreeExpContents(exp);
4625
4626                   exp.constant = PrintDouble(*(double*)ptr);
4627                   exp.type = constantExp;
4628                   break;
4629                }
4630                case intType:
4631                {
4632                   FreeExpContents(exp);
4633
4634                   exp.constant = PrintInt(*(int*)ptr);
4635                   exp.type = constantExp;
4636                   break;
4637                }
4638                case int64Type:
4639                {
4640                   FreeExpContents(exp);
4641
4642                   exp.constant = PrintInt64(*(int64*)ptr);
4643                   exp.type = constantExp;
4644                   break;
4645                }
4646                case intPtrType:
4647                {
4648                   FreeExpContents(exp);
4649                   // TODO: This should probably use proper type
4650                   exp.constant = PrintInt64((int64)*(intptr*)ptr);
4651                   exp.type = constantExp;
4652                   break;
4653                }
4654                case intSizeType:
4655                {
4656                   FreeExpContents(exp);
4657                   // TODO: This should probably use proper type
4658                   exp.constant = PrintInt64((int64)*(intsize*)ptr);
4659                   exp.type = constantExp;
4660                   break;
4661                }
4662                default:
4663                   Compiler_Error($"Unhandled type populating instance\n");
4664             }
4665          }
4666          ListAdd(memberList, member);
4667       }
4668
4669       if(parentDataMember.type == unionMember)
4670          break;
4671    }
4672 }
4673
4674 void PopulateInstance(Instantiation inst)
4675 {
4676    Symbol classSym = inst._class.symbol; // FindClass(inst._class.name);
4677    Class _class = classSym.registered;
4678    DataMember dataMember;
4679    OldList * memberList = MkList();
4680    // Added this check and ->Add to prevent memory leaks on bad code
4681    if(!inst.members)
4682       inst.members = MkListOne(MkMembersInitList(memberList));
4683    else
4684       inst.members->Add(MkMembersInitList(memberList));
4685    for(dataMember = _class.membersAndProperties.first; dataMember; dataMember = dataMember.next)
4686    {
4687       if(!dataMember.isProperty)
4688       {
4689          if(!dataMember.name && (dataMember.type == structMember || dataMember.type == unionMember))
4690             PopulateInstanceProcessMember(inst, memberList, dataMember, dataMember.offset);
4691          else
4692          {
4693             Expression exp { };
4694             MemberInit member = MkMemberInit(MkListOne(MkIdentifier(dataMember.name)), MkInitializerAssignment(exp));
4695             Type type;
4696             void * ptr = inst.data + dataMember.offset;
4697             char * result = null;
4698
4699             exp.loc = member.loc = inst.loc;
4700             ((Identifier)member.identifiers->first).loc = inst.loc;
4701
4702             if(!dataMember.dataType)
4703                dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4704             type = dataMember.dataType;
4705             if(type.kind == classType)
4706             {
4707                Class _class = type._class.registered;
4708                if(_class.type == enumClass)
4709                {
4710                   Class enumClass = eSystem_FindClass(privateModule, "enum");
4711                   if(enumClass)
4712                   {
4713                      EnumClassData e = ACCESS_CLASSDATA(_class, enumClass);
4714                      NamedLink64 item;
4715                      for(item = e.values.first; item; item = item.next)
4716                      {
4717                         if(item.data == GetEnumValue(_class, ptr))
4718                         {
4719                            result = item.name;
4720                            break;
4721                         }
4722                      }
4723                   }
4724                   if(result)
4725                   {
4726                      exp.identifier = MkIdentifier(result);
4727                      exp.type = identifierExp;
4728                      exp.destType = MkClassType(_class.fullName);
4729                      ProcessExpressionType(exp);
4730                   }
4731                }
4732                if(_class.type == enumClass || _class.type == unitClass || _class.type == bitClass)
4733                {
4734                   if(!_class.dataType)
4735                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4736                   type = _class.dataType;
4737                }
4738             }
4739             if(!result)
4740             {
4741                switch(type.kind)
4742                {
4743                   case floatType:
4744                   {
4745                      exp.constant = PrintFloat(*(float*)ptr);
4746                      exp.type = constantExp;
4747                      break;
4748                   }
4749                   case doubleType:
4750                   {
4751                      exp.constant = PrintDouble(*(double*)ptr);
4752                      exp.type = constantExp;
4753                      break;
4754                   }
4755                   case intType:
4756                   {
4757                      exp.constant = PrintInt(*(int*)ptr);
4758                      exp.type = constantExp;
4759                      break;
4760                   }
4761                   case int64Type:
4762                   {
4763                      exp.constant = PrintInt64(*(int64*)ptr);
4764                      exp.type = constantExp;
4765                      break;
4766                   }
4767                   case intPtrType:
4768                   {
4769                      exp.constant = PrintInt64((int64)*(intptr*)ptr);
4770                      exp.type = constantExp;
4771                      break;
4772                   }
4773                   default:
4774                      Compiler_Error($"Unhandled type populating instance\n");
4775                }
4776             }
4777             ListAdd(memberList, member);
4778          }
4779       }
4780    }
4781 }
4782
4783 void ComputeInstantiation(Expression exp)
4784 {
4785    Instantiation inst = exp.instance;
4786    MembersInit members;
4787    Symbol classSym = inst._class ? inst._class.symbol : null; // FindClass(inst._class.name);
4788    Class _class = classSym ? classSym.registered : null;
4789    DataMember curMember = null;
4790    Class curClass = null;
4791    DataMember subMemberStack[256];
4792    int subMemberStackPos = 0;
4793    uint64 bits = 0;
4794
4795    if(_class && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass ))
4796    {
4797       // Don't recompute the instantiation...
4798       // Non Simple classes will have become constants by now
4799       if(inst.data)
4800          return;
4801
4802       if(_class.type == normalClass || _class.type == noHeadClass)
4803       {
4804          inst.data = (byte *)eInstance_New(_class);
4805          if(_class.type == normalClass)
4806             ((Instance)inst.data)._refCount++;
4807       }
4808       else
4809          inst.data = new0 byte[_class.structSize];
4810    }
4811
4812    if(inst.members)
4813    {
4814       for(members = inst.members->first; members; members = members.next)
4815       {
4816          switch(members.type)
4817          {
4818             case dataMembersInit:
4819             {
4820                if(members.dataMembers)
4821                {
4822                   MemberInit member;
4823                   for(member = members.dataMembers->first; member; member = member.next)
4824                   {
4825                      Identifier ident = member.identifiers ? member.identifiers->first : null;
4826                      bool found = false;
4827
4828                      Property prop = null;
4829                      DataMember dataMember = null;
4830                      uint dataMemberOffset;
4831
4832                      if(!ident)
4833                      {
4834                         eClass_FindNextMember(_class, &curClass, &curMember, subMemberStack, &subMemberStackPos);
4835                         if(curMember)
4836                         {
4837                            if(curMember.isProperty)
4838                               prop = (Property)curMember;
4839                            else
4840                            {
4841                               dataMember = curMember;
4842
4843                               // CHANGED THIS HERE
4844                               eClass_FindDataMemberAndOffset(_class, dataMember.name, &dataMemberOffset, privateModule, null, null);
4845
4846                               // 2013/17/29 -- It seems that this was missing here!
4847                               if(_class.type == normalClass)
4848                                  dataMemberOffset += _class.base.structSize;
4849                               // dataMemberOffset = dataMember.offset;
4850                            }
4851                            found = true;
4852                         }
4853                      }
4854                      else
4855                      {
4856                         prop = eClass_FindProperty(_class, ident.string, privateModule);
4857                         if(prop)
4858                         {
4859                            found = true;
4860                            if(prop.memberAccess == publicAccess)
4861                            {
4862                               curMember = (DataMember)prop;
4863                               curClass = prop._class;
4864                            }
4865                         }
4866                         else
4867                         {
4868                            DataMember _subMemberStack[256];
4869                            int _subMemberStackPos = 0;
4870
4871                            // FILL MEMBER STACK
4872                            dataMember = eClass_FindDataMemberAndOffset(_class, ident.string, &dataMemberOffset, privateModule, _subMemberStack, &_subMemberStackPos);
4873
4874                            if(dataMember)
4875                            {
4876                               found = true;
4877                               if(dataMember.memberAccess == publicAccess)
4878                               {
4879                                  curMember = dataMember;
4880                                  curClass = dataMember._class;
4881                                  memcpy(subMemberStack, _subMemberStack, sizeof(DataMember) * _subMemberStackPos);
4882                                  subMemberStackPos = _subMemberStackPos;
4883                               }
4884                            }
4885                         }
4886                      }
4887
4888                      if(found && member.initializer && member.initializer.type == expInitializer)
4889                      {
4890                         Expression value = member.initializer.exp;
4891                         Type type = null;
4892                         bool deepMember = false;
4893                         if(prop)
4894                         {
4895                            type = prop.dataType;
4896                         }
4897                         else if(dataMember)
4898                         {
4899                            if(!dataMember.dataType)
4900                               dataMember.dataType = ProcessTypeString(dataMember.dataTypeString, false);
4901
4902                            type = dataMember.dataType;
4903                         }
4904
4905                         if(ident && ident.next)
4906                         {
4907                            deepMember = true;
4908
4909                            // for(; ident && type; ident = ident.next)
4910                            for(ident = ident.next; ident && type; ident = ident.next)
4911                            {
4912                               if(type.kind == classType)
4913                               {
4914                                  prop = eClass_FindProperty(type._class.registered,
4915                                     ident.string, privateModule);
4916                                  if(prop)
4917                                     type = prop.dataType;
4918                                  else
4919                                  {
4920                                     dataMember = eClass_FindDataMemberAndOffset(type._class.registered,
4921                                        ident.string, &dataMemberOffset, privateModule, null, null);
4922                                     if(dataMember)
4923                                        type = dataMember.dataType;
4924                                  }
4925                               }
4926                               else if(type.kind == structType || type.kind == unionType)
4927                               {
4928                                  Type memberType;
4929                                  for(memberType = type.members.first; memberType; memberType = memberType.next)
4930                                  {
4931                                     if(!strcmp(memberType.name, ident.string))
4932                                     {
4933                                        type = memberType;
4934                                        break;
4935                                     }
4936                                  }
4937                               }
4938                            }
4939                         }
4940                         if(value)
4941                         {
4942                            FreeType(value.destType);
4943                            value.destType = type;
4944                            if(type) type.refCount++;
4945                            ComputeExpression(value);
4946                         }
4947                         if(!deepMember && type && value && (_class.type == structClass || _class.type == normalClass || _class.type == noHeadClass /*&& value.expType.kind == type.kind*/))
4948                         {
4949                            if(type.kind == classType)
4950                            {
4951                               Class _class = type._class.registered;
4952                               if(_class && (_class.type == bitClass || _class.type == unitClass || _class.type == enumClass))
4953                               {
4954                                  if(!_class.dataType)
4955                                     _class.dataType = ProcessTypeString(_class.dataTypeString, false);
4956                                  type = _class.dataType;
4957                               }
4958                            }
4959
4960                            if(dataMember)
4961                            {
4962                               void * ptr = inst.data + dataMemberOffset;
4963
4964                               if(value.type == constantExp)
4965                               {
4966                                  switch(type.kind)
4967                                  {
4968                                     case intType:
4969                                     {
4970                                        GetInt(value, (int*)ptr);
4971                                        break;
4972                                     }
4973                                     case int64Type:
4974                                     {
4975                                        GetInt64(value, (int64*)ptr);
4976                                        break;
4977                                     }
4978                                     case intPtrType:
4979                                     {
4980                                        GetIntPtr(value, (intptr*)ptr);
4981                                        break;
4982                                     }
4983                                     case intSizeType:
4984                                     {
4985                                        GetIntSize(value, (intsize*)ptr);
4986                                        break;
4987                                     }
4988                                     case floatType:
4989                                     {
4990                                        GetFloat(value, (float*)ptr);
4991                                        break;
4992                                     }
4993                                     case doubleType:
4994                                     {
4995                                        GetDouble(value, (double *)ptr);
4996                                        break;
4997                                     }
4998                                  }
4999                               }
5000                               else if(value.type == instanceExp)
5001                               {
5002                                  if(type.kind == classType)
5003                                  {
5004                                     Class _class = type._class.registered;
5005                                     if(_class.type == structClass)
5006                                     {
5007                                        ComputeTypeSize(type);
5008                                        if(value.instance.data)
5009                                           memcpy(ptr, value.instance.data, type.size);
5010                                     }
5011                                  }
5012                               }
5013                            }
5014                            else if(prop && prop.Set != (void *)(intptr)1)
5015                            {
5016                               if(value.type == instanceExp && value.instance.data)
5017                               {
5018                                  if(type.kind == classType)
5019                                  {
5020                                     Class _class = type._class.registered;
5021                                     if(_class && (_class.type != normalClass || eClass_IsDerived(((Instance)value.instance.data)._class, _class)))
5022                                     {
5023                                        void (*Set)(void *, void *) = (void *)prop.Set;
5024                                        Set(inst.data, value.instance.data);
5025                                        PopulateInstance(inst);
5026                                     }
5027                                  }
5028                               }
5029                               else if(value.type == constantExp)
5030                               {
5031                                  switch(type.kind)
5032                                  {
5033                                     case doubleType:
5034                                     {
5035                                        void (*Set)(void *, double) = (void *)prop.Set;
5036                                        Set(inst.data, strtod(value.constant, null) );
5037                                        break;
5038                                     }
5039                                     case floatType:
5040                                     {
5041                                        void (*Set)(void *, float) = (void *)prop.Set;
5042                                        Set(inst.data, (float)(strtod(value.constant, null)));
5043                                        break;
5044                                     }
5045                                     case intType:
5046                                     {
5047                                        void (*Set)(void *, int) = (void *)prop.Set;
5048                                        Set(inst.data, (int)strtol(value.constant, null, 0));
5049                                        break;
5050                                     }
5051                                     case int64Type:
5052                                     {
5053                                        void (*Set)(void *, int64) = (void *)prop.Set;
5054                                        Set(inst.data, _strtoi64(value.constant, null, 0));
5055                                        break;
5056                                     }
5057                                     case intPtrType:
5058                                     {
5059                                        void (*Set)(void *, intptr) = (void *)prop.Set;
5060                                        Set(inst.data, (intptr)_strtoi64(value.constant, null, 0));
5061                                        break;
5062                                     }
5063                                     case intSizeType:
5064                                     {
5065                                        void (*Set)(void *, intsize) = (void *)prop.Set;
5066                                        Set(inst.data, (intsize)_strtoi64(value.constant, null, 0));
5067                                        break;
5068                                     }
5069                                  }
5070                               }
5071                               else if(value.type == stringExp)
5072                               {
5073                                  char temp[1024];
5074                                  ReadString(temp, value.string);
5075                                  ((void (*)(void *, void *))(void *)prop.Set)(inst.data, temp);
5076                               }
5077                            }
5078                         }
5079                         else if(!deepMember && type && _class.type == unitClass)
5080                         {
5081                            if(prop)
5082                            {
5083                               // Only support converting units to units for now...
5084                               if(value.type == constantExp)
5085                               {
5086                                  if(type.kind == classType)
5087                                  {
5088                                     Class _class = type._class.registered;
5089                                     if(_class.type == unitClass)
5090                                     {
5091                                        if(!_class.dataType)
5092                                           _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5093                                        type = _class.dataType;
5094                                     }
5095                                  }
5096                                  // TODO: Assuming same base type for units...
5097                                  switch(type.kind)
5098                                  {
5099                                     case floatType:
5100                                     {
5101                                        float fValue;
5102                                        float (*Set)(float) = (void *)prop.Set;
5103                                        GetFloat(member.initializer.exp, &fValue);
5104                                        exp.constant = PrintFloat(Set(fValue));
5105                                        exp.type = constantExp;
5106                                        break;
5107                                     }
5108                                     case doubleType:
5109                                     {
5110                                        double dValue;
5111                                        double (*Set)(double) = (void *)prop.Set;
5112                                        GetDouble(member.initializer.exp, &dValue);
5113                                        exp.constant = PrintDouble(Set(dValue));
5114                                        exp.type = constantExp;
5115                                        break;
5116                                     }
5117                                  }
5118                               }
5119                            }
5120                         }
5121                         else if(!deepMember && type && _class.type == bitClass)
5122                         {
5123                            if(prop)
5124                            {
5125                               if(value.type == instanceExp && value.instance.data)
5126                               {
5127                                  unsigned int (*Set)(void *) = (void *)prop.Set;
5128                                  bits = Set(value.instance.data);
5129                               }
5130                               else if(value.type == constantExp)
5131                               {
5132                               }
5133                            }
5134                            else if(dataMember)
5135                            {
5136                               BitMember bitMember = (BitMember) dataMember;
5137                               Type type;
5138                               uint64 part = 0;
5139                               bits = (bits & ~bitMember.mask);
5140                               if(!bitMember.dataType)
5141                                  bitMember.dataType = ProcessTypeString(bitMember.dataTypeString, false);
5142                               type = bitMember.dataType;
5143                               if(type.kind == classType && type._class && type._class.registered)
5144                               {
5145                                  if(!type._class.registered.dataType)
5146                                     type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
5147                                  type = type._class.registered.dataType;
5148                               }
5149                               switch(type.kind)
5150                               {
5151                                  case _BoolType:
5152                                  case charType:       { byte v; type.isSigned ? GetChar(value, (char *)&v) : GetUChar(value, &v); part = (uint64)v; break; }
5153                                  case shortType:      { uint16 v; type.isSigned ? GetShort(value, (short *)&v) : GetUShort(value, &v); part = (uint64)v; break; }
5154                                  case intType:
5155                                  case longType:       { uint v; type.isSigned ? GetInt(value, (int *)&v) : GetUInt(value, &v); part = (uint64)v; break; }
5156                                  case int64Type:      { uint64 v; type.isSigned ? GetInt64(value, (int64 *)&v) : GetUInt64(value, &v); part = (uint64)v; break; }
5157                                  case intPtrType:     { uintptr v; type.isSigned ? GetIntPtr(value, (intptr *)&v) : GetUIntPtr(value, &v); part = (uint64)v; break; }
5158                                  case intSizeType:    { uintsize v; type.isSigned ? GetIntSize(value, (intsize *)&v) : GetUIntSize(value, &v); part = (uint64)v; break; }
5159                               }
5160                               bits |= part << bitMember.pos;
5161                            }
5162                         }
5163                      }
5164                      else
5165                      {
5166                         if(_class && _class.type == unitClass)
5167                         {
5168                            ComputeExpression(member.initializer.exp);
5169                            exp.constant = member.initializer.exp.constant;
5170                            exp.type = constantExp;
5171
5172                            member.initializer.exp.constant = null;
5173                         }
5174                      }
5175                   }
5176                }
5177                break;
5178             }
5179          }
5180       }
5181    }
5182    if(_class && _class.type == bitClass)
5183    {
5184       exp.constant = PrintHexUInt(bits);
5185       exp.type = constantExp;
5186    }
5187    if(exp.type != instanceExp)
5188    {
5189       FreeInstance(inst);
5190    }
5191 }
5192
5193 static bool Promote(Operand op, TypeKind kind, bool isSigned)
5194 {
5195    bool result = false;
5196    switch(kind)
5197    {
5198       case shortType:
5199          if(op.kind == charType || op.kind == enumType || op.kind == _BoolType)
5200             result = isSigned ? GetOpShort(op, &op.s) : GetOpUShort(op, &op.us);
5201          break;
5202       case intType:
5203       case longType:
5204          if(op.kind == charType || op.kind == shortType || op.kind == enumType || op.kind == _BoolType)
5205             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5206          break;
5207       case int64Type:
5208          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5209             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5210             result = isSigned ? GetOpInt64(op, &op.i64) : GetOpUInt64(op, &op.ui64);
5211          break;
5212       case floatType:
5213          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType ||
5214             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5215             result = GetOpFloat(op, &op.f);
5216          break;
5217       case doubleType:
5218          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType ||
5219             op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5220             result = GetOpDouble(op, &op.d);
5221          break;
5222       case pointerType:
5223          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5224             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5225             result = GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5226          break;
5227       case enumType:
5228          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == int64Type || op.kind == longType || op.kind == floatType || op.kind == doubleType ||
5229             op.kind == pointerType || op.kind == enumType || op.kind == intPtrType || op.kind == intSizeType || op.kind == _BoolType)
5230             result = isSigned ? GetOpInt(op, &op.i) : GetOpUInt(op, &op.ui);
5231          break;
5232       case intPtrType:
5233          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5234             result = isSigned ? GetOpInt64 /*GetOpIntPtr*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntPtr*/(op, &op.ui64);
5235          break;
5236       case intSizeType:
5237          if(op.kind == charType || op.kind == shortType || op.kind == intType || op.kind == longType || op.kind == enumType || op.kind == _BoolType)
5238             result = isSigned ? GetOpInt64 /*GetOpIntSize*/(op, &op.i64) : GetOpUInt64 /*GetOpUIntSize*/(op, &op.ui64);
5239          break;
5240    }
5241    return result;
5242 }
5243
5244 void CallOperator(Expression exp, Expression exp1, Expression exp2, Operand op1, Operand op2)
5245 {
5246    if(exp.op.op == SIZEOF)
5247    {
5248       FreeExpContents(exp);
5249       exp.type = constantExp;
5250       exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5251    }
5252    else
5253    {
5254       if(!exp.op.exp1)
5255       {
5256          switch(exp.op.op)
5257          {
5258             // unary arithmetic
5259             case '+':
5260             {
5261                // Provide default unary +
5262                Expression exp2 = exp.op.exp2;
5263                exp.op.exp2 = null;
5264                FreeExpContents(exp);
5265                FreeType(exp.expType);
5266                FreeType(exp.destType);
5267                *exp = *exp2;
5268                delete exp2;
5269                break;
5270             }
5271             case '-':
5272                if(op1.ops.Neg) { FreeExpContents(exp); op1.ops.Neg(exp, op1); }
5273                break;
5274             // unary arithmetic increment and decrement
5275                   //OPERATOR_ALL(UNARY, ++, Inc)
5276                   //OPERATOR_ALL(UNARY, --, Dec)
5277             // unary bitwise
5278             case '~':
5279                if(op1.ops.BitNot) { FreeExpContents(exp); op1.ops.BitNot(exp, op1); }
5280                break;
5281             // unary logical negation
5282             case '!':
5283                if(op1.ops.Not) { FreeExpContents(exp); op1.ops.Not(exp, op1); }
5284                break;
5285          }
5286       }
5287       else
5288       {
5289          if(op1 && op2 && op1.type && op2.type && op1.kind != op2.kind)
5290          {
5291             if(Promote(op2, op1.kind, op1.type.isSigned))
5292                op2.kind = op1.kind, op2.ops = op1.ops;
5293             else if(Promote(op1, op2.kind, op2.type.isSigned))
5294                op1.kind = op2.kind, op1.ops = op2.ops;
5295          }
5296          switch(exp.op.op)
5297          {
5298             // binary arithmetic
5299             case '+':
5300                if(op1.ops.Add) { FreeExpContents(exp); op1.ops.Add(exp, op1, op2); }
5301                break;
5302             case '-':
5303                if(op1.ops.Sub) { FreeExpContents(exp); op1.ops.Sub(exp, op1, op2); }
5304                break;
5305             case '*':
5306                if(op1.ops.Mul) { FreeExpContents(exp); op1.ops.Mul(exp, op1, op2); }
5307                break;
5308             case '/':
5309                if(op1.ops.Div) { FreeExpContents(exp); op1.ops.Div(exp, op1, op2); }
5310                break;
5311             case '%':
5312                if(op1.ops.Mod) { FreeExpContents(exp); op1.ops.Mod(exp, op1, op2); }
5313                break;
5314             // binary arithmetic assignment
5315                   //OPERATOR_ALL(BINARY, =, Asign)
5316                   //OPERATOR_ALL(BINARY, +=, AddAsign)
5317                   //OPERATOR_ALL(BINARY, -=, SubAsign)
5318                   //OPERATOR_ALL(BINARY, *=, MulAsign)
5319                   //OPERATOR_ALL(BINARY, /=, DivAsign)
5320                   //OPERATOR_ALL(BINARY, %=, ModAsign)
5321             // binary bitwise
5322             case '&':
5323                if(exp.op.exp2)
5324                {
5325                   if(op1.ops.BitAnd) { FreeExpContents(exp); op1.ops.BitAnd(exp, op1, op2); }
5326                }
5327                break;
5328             case '|':
5329                if(op1.ops.BitOr) { FreeExpContents(exp); op1.ops.BitOr(exp, op1, op2); }
5330                break;
5331             case '^':
5332                if(op1.ops.BitXor) { FreeExpContents(exp); op1.ops.BitXor(exp, op1, op2); }
5333                break;
5334             case LEFT_OP:
5335                if(op1.ops.LShift) { FreeExpContents(exp); op1.ops.LShift(exp, op1, op2); }
5336                break;
5337             case RIGHT_OP:
5338                if(op1.ops.RShift) { FreeExpContents(exp); op1.ops.RShift(exp, op1, op2); }
5339                break;
5340             // binary bitwise assignment
5341                   //OPERATOR_INTTYPES(BINARY, &=, AndAsign)
5342                   //OPERATOR_INTTYPES(BINARY, |=, OrAsign)
5343                   //OPERATOR_INTTYPES(BINARY, ^=, XorAsign)
5344                   //OPERATOR_INTTYPES(BINARY, <<=, LShiftAsign)
5345                   //OPERATOR_INTTYPES(BINARY, >>=, RShiftAsign)
5346             // binary logical equality
5347             case EQ_OP:
5348                if(op1.ops.Equ) { FreeExpContents(exp); op1.ops.Equ(exp, op1, op2); }
5349                break;
5350             case NE_OP:
5351                if(op1.ops.Nqu) { FreeExpContents(exp); op1.ops.Nqu(exp, op1, op2); }
5352                break;
5353             // binary logical
5354             case AND_OP:
5355                if(op1.ops.And) { FreeExpContents(exp); op1.ops.And(exp, op1, op2); }
5356                break;
5357             case OR_OP:
5358                if(op1.ops.Or) { FreeExpContents(exp); op1.ops.Or(exp, op1, op2); }
5359                break;
5360             // binary logical relational
5361             case '>':
5362                if(op1.ops.Grt) { FreeExpContents(exp); op1.ops.Grt(exp, op1, op2); }
5363                break;
5364             case '<':
5365                if(op1.ops.Sma) { FreeExpContents(exp); op1.ops.Sma(exp, op1, op2); }
5366                break;
5367             case GE_OP:
5368                if(op1.ops.GrtEqu) { FreeExpContents(exp); op1.ops.GrtEqu(exp, op1, op2); }
5369                break;
5370             case LE_OP:
5371                if(op1.ops.SmaEqu) { FreeExpContents(exp); op1.ops.SmaEqu(exp, op1, op2); }
5372                break;
5373          }
5374       }
5375    }
5376 }
5377
5378 void ComputeExpression(Expression exp)
5379 {
5380 #ifdef _DEBUG
5381    char expString[10240];
5382    expString[0] = '\0';
5383    PrintExpression(exp, expString);
5384 #endif
5385
5386    switch(exp.type)
5387    {
5388       case identifierExp:
5389       {
5390          Identifier id = exp.identifier;
5391          if(id && exp.isConstant && !inCompiler && !inPreCompiler && !inDebugger)
5392          {
5393             Class c = (exp.expType && exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
5394             if(c && c.type == enumClass)
5395             {
5396                Class enumClass = eSystem_FindClass(privateModule, "enum");
5397                if(enumClass)
5398                {
5399                   NamedLink64 value;
5400                   EnumClassData e = ACCESS_CLASSDATA(c, enumClass);
5401                   for(value = e.values.first; value; value = value.next)
5402                   {
5403                      if(!strcmp(value.name, id.string))
5404                         break;
5405                   }
5406                   if(value)
5407                   {
5408                      const String dts = c.dataTypeString;
5409                      FreeExpContents(exp);
5410                      exp.type = constantExp;
5411                      exp.constant = (dts && (!strcmp(dts, "int") || !strcmp(dts, "int64") || !strcmp(dts, "short") || !strcmp(dts, "char"))) ? PrintInt64(value.data) : PrintUInt64(value.data);
5412                   }
5413                }
5414             }
5415          }
5416          break;
5417       }
5418       case instanceExp:
5419       {
5420          ComputeInstantiation(exp);
5421          break;
5422       }
5423       /*
5424       case constantExp:
5425          break;
5426       */
5427       case opExp:
5428       {
5429          Expression exp1, exp2 = null;
5430          Operand op1 { };
5431          Operand op2 { };
5432
5433          // We don't care about operations with only exp2 (INC_OP, DEC_OP...)
5434          if(exp.op.exp2)
5435          {
5436             Expression e = exp.op.exp2;
5437
5438             while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
5439             {
5440                if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
5441                {
5442                   if(e.type == extensionCompoundExp)
5443                      e = ((Statement)e.compound.compound.statements->last).expressions->last;
5444                   else
5445                      e = e.list->last;
5446                }
5447             }
5448             if(exp.op.op == TokenType::sizeOf && e && e.expType)
5449             {
5450                if(e.type == stringExp && e.string)
5451                {
5452                   char * string = e.string;
5453                   int len = strlen(string);
5454                   char * tmp = new char[len-2+1];
5455                   len = UnescapeString(tmp, string + 1, len - 2);
5456                   delete tmp;
5457                   FreeExpContents(exp);
5458                   exp.type = constantExp;
5459                   exp.constant = PrintUInt(len + 1);
5460                }
5461                else
5462                {
5463                   Type type = e.expType;
5464                   type.refCount++;
5465                   FreeExpContents(exp);
5466                   exp.type = constantExp;
5467                   exp.constant = PrintUInt(ComputeTypeSize(type));
5468                   FreeType(type);
5469                }
5470                break;
5471             }
5472             else
5473                ComputeExpression(exp.op.exp2);
5474          }
5475          if(exp.op.exp1)
5476          {
5477             ComputeExpression(exp.op.exp1);
5478             exp1 = exp.op.exp1;
5479             exp2 = exp.op.exp2;
5480             op1 = GetOperand(exp1);
5481             if(op1.type) op1.type.refCount++;
5482             if(exp2)
5483             {
5484                op2 = GetOperand(exp2);
5485                if(op2.type) op2.type.refCount++;
5486             }
5487          }
5488          else
5489          {
5490             exp1 = exp.op.exp2;
5491             op1 = GetOperand(exp1);
5492             if(op1.type) op1.type.refCount++;
5493          }
5494
5495          CallOperator(exp, exp1, exp2, op1, op2);
5496          /*
5497          switch(exp.op.op)
5498          {
5499             // Unary operators
5500             case '&':
5501                // Also binary
5502                if(exp.op.exp1 && exp.op.exp2)
5503                {
5504                   // Binary And
5505                   if(op1.ops.BitAnd)
5506                   {
5507                      FreeExpContents(exp);
5508                      op1.ops.BitAnd(exp, op1, op2);
5509                   }
5510                }
5511                break;
5512             case '*':
5513                if(exp.op.exp1)
5514                {
5515                   if(op1.ops.Mul)
5516                   {
5517                      FreeExpContents(exp);
5518                      op1.ops.Mul(exp, op1, op2);
5519                   }
5520                }
5521                break;
5522             case '+':
5523                if(exp.op.exp1)
5524                {
5525                   if(op1.ops.Add)
5526                   {
5527                      FreeExpContents(exp);
5528                      op1.ops.Add(exp, op1, op2);
5529                   }
5530                }
5531                else
5532                {
5533                   // Provide default unary +
5534                   Expression exp2 = exp.op.exp2;
5535                   exp.op.exp2 = null;
5536                   FreeExpContents(exp);
5537                   FreeType(exp.expType);
5538                   FreeType(exp.destType);
5539
5540                   *exp = *exp2;
5541                   delete exp2;
5542                }
5543                break;
5544             case '-':
5545                if(exp.op.exp1)
5546                {
5547                   if(op1.ops.Sub)
5548                   {
5549                      FreeExpContents(exp);
5550                      op1.ops.Sub(exp, op1, op2);
5551                   }
5552                }
5553                else
5554                {
5555                   if(op1.ops.Neg)
5556                   {
5557                      FreeExpContents(exp);
5558                      op1.ops.Neg(exp, op1);
5559                   }
5560                }
5561                break;
5562             case '~':
5563                if(op1.ops.BitNot)
5564                {
5565                   FreeExpContents(exp);
5566                   op1.ops.BitNot(exp, op1);
5567                }
5568                break;
5569             case '!':
5570                if(op1.ops.Not)
5571                {
5572                   FreeExpContents(exp);
5573                   op1.ops.Not(exp, op1);
5574                }
5575                break;
5576             // Binary only operators
5577             case '/':
5578                if(op1.ops.Div)
5579                {
5580                   FreeExpContents(exp);
5581                   op1.ops.Div(exp, op1, op2);
5582                }
5583                break;
5584             case '%':
5585                if(op1.ops.Mod)
5586                {
5587                   FreeExpContents(exp);
5588                   op1.ops.Mod(exp, op1, op2);
5589                }
5590                break;
5591             case LEFT_OP:
5592                break;
5593             case RIGHT_OP:
5594                break;
5595             case '<':
5596                if(exp.op.exp1)
5597                {
5598                   if(op1.ops.Sma)
5599                   {
5600                      FreeExpContents(exp);
5601                      op1.ops.Sma(exp, op1, op2);
5602                   }
5603                }
5604                break;
5605             case '>':
5606                if(exp.op.exp1)
5607                {
5608                   if(op1.ops.Grt)
5609                   {
5610                      FreeExpContents(exp);
5611                      op1.ops.Grt(exp, op1, op2);
5612                   }
5613                }
5614                break;
5615             case LE_OP:
5616                if(exp.op.exp1)
5617                {
5618                   if(op1.ops.SmaEqu)
5619                   {
5620                      FreeExpContents(exp);
5621                      op1.ops.SmaEqu(exp, op1, op2);
5622                   }
5623                }
5624                break;
5625             case GE_OP:
5626                if(exp.op.exp1)
5627                {
5628                   if(op1.ops.GrtEqu)
5629                   {
5630                      FreeExpContents(exp);
5631                      op1.ops.GrtEqu(exp, op1, op2);
5632                   }
5633                }
5634                break;
5635             case EQ_OP:
5636                if(exp.op.exp1)
5637                {
5638                   if(op1.ops.Equ)
5639                   {
5640                      FreeExpContents(exp);
5641                      op1.ops.Equ(exp, op1, op2);
5642                   }
5643                }
5644                break;
5645             case NE_OP:
5646                if(exp.op.exp1)
5647                {
5648                   if(op1.ops.Nqu)
5649                   {
5650                      FreeExpContents(exp);
5651                      op1.ops.Nqu(exp, op1, op2);
5652                   }
5653                }
5654                break;
5655             case '|':
5656                if(op1.ops.BitOr)
5657                {
5658                   FreeExpContents(exp);
5659                   op1.ops.BitOr(exp, op1, op2);
5660                }
5661                break;
5662             case '^':
5663                if(op1.ops.BitXor)
5664                {
5665                   FreeExpContents(exp);
5666                   op1.ops.BitXor(exp, op1, op2);
5667                }
5668                break;
5669             case AND_OP:
5670                break;
5671             case OR_OP:
5672                break;
5673             case SIZEOF:
5674                FreeExpContents(exp);
5675                exp.type = constantExp;
5676                exp.constant = PrintUInt(ComputeTypeSize(op1.type));
5677                break;
5678          }
5679          */
5680          if(op1.type) FreeType(op1.type);
5681          if(op2.type) FreeType(op2.type);
5682          break;
5683       }
5684       case bracketsExp:
5685       case extensionExpressionExp:
5686       {
5687          Expression e, n;
5688          for(e = exp.list->first; e; e = n)
5689          {
5690             n = e.next;
5691             if(!n)
5692             {
5693                OldList * list = exp.list;
5694                Expression prev = exp.prev;
5695                Expression next = exp.next;
5696                ComputeExpression(e);
5697                //FreeExpContents(exp);
5698                FreeType(exp.expType);
5699                FreeType(exp.destType);
5700                *exp = *e;
5701                exp.prev = prev;
5702                exp.next = next;
5703                delete e;
5704                delete list;
5705             }
5706             else
5707             {
5708                FreeExpression(e);
5709             }
5710          }
5711          break;
5712       }
5713       /*
5714
5715       case ExpIndex:
5716       {
5717          Expression e;
5718          exp.isConstant = true;
5719
5720          ComputeExpression(exp.index.exp);
5721          if(!exp.index.exp.isConstant)
5722             exp.isConstant = false;
5723
5724          for(e = exp.index.index->first; e; e = e.next)
5725          {
5726             ComputeExpression(e);
5727             if(!e.next)
5728             {
5729                // Check if this type is int
5730             }
5731             if(!e.isConstant)
5732                exp.isConstant = false;
5733          }
5734          exp.expType = Dereference(exp.index.exp.expType);
5735          break;
5736       }
5737       */
5738       case memberExp:
5739       {
5740          Expression memberExp = exp.member.exp;
5741          Identifier memberID = exp.member.member;
5742
5743          Type type;
5744          ComputeExpression(exp.member.exp);
5745          type = exp.member.exp.expType;
5746          if(type)
5747          {
5748             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);
5749             Property prop = null;
5750             DataMember member = null;
5751             Class convertTo = null;
5752             if(type.kind == subClassType && exp.member.exp.type == classExp)
5753                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
5754
5755             if(!_class)
5756             {
5757                char string[256];
5758                Symbol classSym;
5759                string[0] = '\0';
5760                PrintTypeNoConst(type, string, false, true);
5761                classSym = FindClass(string);
5762                _class = classSym ? classSym.registered : null;
5763             }
5764
5765             if(exp.member.member)
5766             {
5767                prop = eClass_FindProperty(_class, exp.member.member.string, privateModule);
5768                if(!prop)
5769                   member = eClass_FindDataMember(_class, exp.member.member.string, privateModule, null, null);
5770             }
5771             if(!prop && !member && _class && exp.member.member)
5772             {
5773                Symbol classSym = FindClass(exp.member.member.string);
5774                convertTo = _class;
5775                _class = classSym ? classSym.registered : null;
5776                prop = eClass_FindProperty(_class, convertTo.fullName, privateModule);
5777             }
5778
5779             if(prop)
5780             {
5781                if(prop.compiled)
5782                {
5783                   Type type = prop.dataType;
5784                   // TODO: Assuming same base type for units...
5785                   if(_class.type == unitClass)
5786                   {
5787                      if(type.kind == classType)
5788                      {
5789                         Class _class = type._class.registered;
5790                         if(_class.type == unitClass)
5791                         {
5792                            if(!_class.dataType)
5793                               _class.dataType = ProcessTypeString(_class.dataTypeString, false);
5794                            type = _class.dataType;
5795                         }
5796                      }
5797                      switch(type.kind)
5798                      {
5799                         case floatType:
5800                         {
5801                            float value;
5802                            float (*Get)(float) = (void *)prop.Get;
5803                            GetFloat(exp.member.exp, &value);
5804                            exp.constant = PrintFloat(Get ? Get(value) : value);
5805                            exp.type = constantExp;
5806                            break;
5807                         }
5808                         case doubleType:
5809                         {
5810                            double value;
5811                            double (*Get)(double);
5812                            GetDouble(exp.member.exp, &value);
5813
5814                            if(convertTo)
5815                               Get = (void *)prop.Set;
5816                            else
5817                               Get = (void *)prop.Get;
5818                            exp.constant = PrintDouble(Get ? Get(value) : value);
5819                            exp.type = constantExp;
5820                            break;
5821                         }
5822                      }
5823                   }
5824                   else
5825                   {
5826                      if(convertTo)
5827                      {
5828                         Expression value = exp.member.exp;
5829                         Type type;
5830                         if(!prop.dataType)
5831                            ProcessPropertyType(prop);
5832
5833                         type = prop.dataType;
5834                         if(!type)
5835                         {
5836                             // printf("Investigate this\n");
5837                         }
5838                         else if(_class.type == structClass)
5839                         {
5840                            switch(type.kind)
5841                            {
5842                               case classType:
5843                               {
5844                                  Class propertyClass = type._class.registered;
5845                                  if(propertyClass.type == structClass && value.type == instanceExp)
5846                                  {
5847                                     void (*Set)(void *, void *) = (void *)prop.Set;
5848                                     exp.instance = Instantiation { };
5849                                     exp.instance.data = new0 byte[_class.structSize];
5850                                     exp.instance._class = MkSpecifierName(_class.fullName);
5851                                     exp.instance.loc = exp.loc;
5852                                     exp.type = instanceExp;
5853                                     Set(exp.instance.data, value.instance.data);
5854                                     PopulateInstance(exp.instance);
5855                                  }
5856                                  break;
5857                               }
5858                               case intType:
5859                               {
5860                                  int intValue;
5861                                  void (*Set)(void *, int) = (void *)prop.Set;
5862
5863                                  exp.instance = Instantiation { };
5864                                  exp.instance.data = new0 byte[_class.structSize];
5865                                  exp.instance._class = MkSpecifierName(_class.fullName);
5866                                  exp.instance.loc = exp.loc;
5867                                  exp.type = instanceExp;
5868
5869                                  GetInt(value, &intValue);
5870
5871                                  Set(exp.instance.data, intValue);
5872                                  PopulateInstance(exp.instance);
5873                                  break;
5874                               }
5875                               case int64Type:
5876                               {
5877                                  int64 intValue;
5878                                  void (*Set)(void *, int64) = (void *)prop.Set;
5879
5880                                  exp.instance = Instantiation { };
5881                                  exp.instance.data = new0 byte[_class.structSize];
5882                                  exp.instance._class = MkSpecifierName/*MkClassName*/(_class.fullName);
5883                                  exp.instance.loc = exp.loc;
5884                                  exp.type = instanceExp;
5885
5886                                  GetInt64(value, &intValue);
5887
5888                                  Set(exp.instance.data, intValue);
5889                                  PopulateInstance(exp.instance);
5890                                  break;
5891                               }
5892                               case intPtrType:
5893                               {
5894                                  // TOFIX:
5895                                  intptr intValue;
5896                                  void (*Set)(void *, intptr) = (void *)prop.Set;
5897
5898                                  exp.instance = Instantiation { };
5899                                  exp.instance.data = new0 byte[_class.structSize];
5900                                  exp.instance._class = MkSpecifierName(_class.fullName);
5901                                  exp.instance.loc = exp.loc;
5902                                  exp.type = instanceExp;
5903
5904                                  GetIntPtr(value, &intValue);
5905
5906                                  Set(exp.instance.data, intValue);
5907                                  PopulateInstance(exp.instance);
5908                                  break;
5909                               }
5910                               case intSizeType:
5911                               {
5912                                  // TOFIX:
5913                                  intsize intValue;
5914                                  void (*Set)(void *, intsize) = (void *)prop.Set;
5915
5916                                  exp.instance = Instantiation { };
5917                                  exp.instance.data = new0 byte[_class.structSize];
5918                                  exp.instance._class = MkSpecifierName(_class.fullName);
5919                                  exp.instance.loc = exp.loc;
5920                                  exp.type = instanceExp;
5921
5922                                  GetIntSize(value, &intValue);
5923
5924                                  Set(exp.instance.data, intValue);
5925                                  PopulateInstance(exp.instance);
5926                                  break;
5927                               }
5928                               case floatType:
5929                               {
5930                                  float floatValue;
5931                                  void (*Set)(void *, float) = (void *)prop.Set;
5932
5933                                  exp.instance = Instantiation { };
5934                                  exp.instance.data = new0 byte[_class.structSize];
5935                                  exp.instance._class = MkSpecifierName(_class.fullName);
5936                                  exp.instance.loc = exp.loc;
5937                                  exp.type = instanceExp;
5938
5939                                  GetFloat(value, &floatValue);
5940
5941                                  Set(exp.instance.data, floatValue);
5942                                  PopulateInstance(exp.instance);
5943                                  break;
5944                               }
5945                               case doubleType:
5946                               {
5947                                  double doubleValue;
5948                                  void (*Set)(void *, double) = (void *)prop.Set;
5949
5950                                  exp.instance = Instantiation { };
5951                                  exp.instance.data = new0 byte[_class.structSize];
5952                                  exp.instance._class = MkSpecifierName(_class.fullName);
5953                                  exp.instance.loc = exp.loc;
5954                                  exp.type = instanceExp;
5955
5956                                  GetDouble(value, &doubleValue);
5957
5958                                  Set(exp.instance.data, doubleValue);
5959                                  PopulateInstance(exp.instance);
5960                                  break;
5961                               }
5962                            }
5963                         }
5964                         else if(_class.type == bitClass)
5965                         {
5966                            switch(type.kind)
5967                            {
5968                               case classType:
5969                               {
5970                                  Class propertyClass = type._class.registered;
5971                                  if(propertyClass.type == structClass && value.instance.data)
5972                                  {
5973                                     unsigned int (*Set)(void *) = (void *)prop.Set;
5974                                     unsigned int bits = Set(value.instance.data);
5975                                     exp.constant = PrintHexUInt(bits);
5976                                     exp.type = constantExp;
5977                                     break;
5978                                  }
5979                                  else if(_class.type == bitClass)
5980                                  {
5981                                     unsigned int value;
5982                                     unsigned int (*Set)(unsigned int) = (void *)prop.Set;
5983                                     unsigned int bits;
5984
5985                                     GetUInt(exp.member.exp, &value);
5986                                     bits = Set(value);
5987                                     exp.constant = PrintHexUInt(bits);
5988                                     exp.type = constantExp;
5989                                  }
5990                               }
5991                            }
5992                         }
5993                      }
5994                      else
5995                      {
5996                         if(_class.type == bitClass)
5997                         {
5998                            unsigned int value;
5999                            GetUInt(exp.member.exp, &value);
6000
6001                            switch(type.kind)
6002                            {
6003                               case classType:
6004                               {
6005                                  Class _class = type._class.registered;
6006                                  if(_class.type == structClass)
6007                                  {
6008                                     void (*Get)(unsigned int, void *) = (void *)prop.Get;
6009
6010                                     exp.instance = Instantiation { };
6011                                     exp.instance.data = new0 byte[_class.structSize];
6012                                     exp.instance._class = MkSpecifierName(_class.fullName);
6013                                     exp.instance.loc = exp.loc;
6014                                     //exp.instance.fullSet = true;
6015                                     exp.type = instanceExp;
6016                                     Get(value, exp.instance.data);
6017                                     PopulateInstance(exp.instance);
6018                                  }
6019                                  else if(_class.type == bitClass)
6020                                  {
6021                                     unsigned int (*Get)(unsigned int) = (void *)prop.Get;
6022                                     uint64 bits = Get(value);
6023                                     exp.constant = PrintHexUInt64(bits);
6024                                     exp.type = constantExp;
6025                                  }
6026                                  break;
6027                               }
6028                            }
6029                         }
6030                         else if(_class.type == structClass)
6031                         {
6032                            byte * value = (exp.member.exp.type == instanceExp ) ? exp.member.exp.instance.data : null;
6033                            switch(type.kind)
6034                            {
6035                               case classType:
6036                               {
6037                                  Class _class = type._class.registered;
6038                                  if(_class.type == structClass && value)
6039                                  {
6040                                     void (*Get)(void *, void *) = (void *)prop.Get;
6041
6042                                     exp.instance = Instantiation { };
6043                                     exp.instance.data = new0 byte[_class.structSize];
6044                                     exp.instance._class = MkSpecifierName(_class.fullName);
6045                                     exp.instance.loc = exp.loc;
6046                                     //exp.instance.fullSet = true;
6047                                     exp.type = instanceExp;
6048                                     Get(value, exp.instance.data);
6049                                     PopulateInstance(exp.instance);
6050                                  }
6051                                  break;
6052                               }
6053                            }
6054                         }
6055                         /*else
6056                         {
6057                            char * value = exp.member.exp.instance.data;
6058                            switch(type.kind)
6059                            {
6060                               case classType:
6061                               {
6062                                  Class _class = type._class.registered;
6063                                  if(_class.type == normalClass)
6064                                  {
6065                                     void *(*Get)(void *) = (void *)prop.Get;
6066
6067                                     exp.instance = Instantiation { };
6068                                     exp.instance._class = MkSpecifierName(_class.fullName); //MkClassName(_class.fullName);
6069                                     exp.type = instanceExp;
6070                                     exp.instance.data = Get(value, exp.instance.data);
6071                                  }
6072                                  break;
6073                               }
6074                            }
6075                         }
6076                         */
6077                      }
6078                   }
6079                }
6080                else
6081                {
6082                   exp.isConstant = false;
6083                }
6084             }
6085             else if(member)
6086             {
6087             }
6088          }
6089
6090          if(exp.type != ExpressionType::memberExp)
6091          {
6092             FreeExpression(memberExp);
6093             FreeIdentifier(memberID);
6094          }
6095          break;
6096       }
6097       case typeSizeExp:
6098       {
6099          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
6100          FreeExpContents(exp);
6101          exp.constant = PrintUInt(ComputeTypeSize(type));
6102          exp.type = constantExp;
6103          FreeType(type);
6104          break;
6105       }
6106       case classSizeExp:
6107       {
6108          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
6109          if(classSym && classSym.registered)
6110          {
6111             if(classSym.registered.fixed)
6112             {
6113                FreeSpecifier(exp._class);
6114                exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
6115                exp.type = constantExp;
6116             }
6117             else
6118             {
6119                char className[1024];
6120                strcpy(className, "__ecereClass_");
6121                FullClassNameCat(className, classSym.string, true);
6122
6123                DeclareClass(curExternal, classSym, className);
6124
6125                FreeExpContents(exp);
6126                exp.type = pointerExp;
6127                exp.member.exp = MkExpIdentifier(MkIdentifier(className));
6128                exp.member.member = MkIdentifier("structSize");
6129             }
6130          }
6131          break;
6132       }
6133       case castExp:
6134       //case constantExp:
6135       {
6136          Type type;
6137          Expression e = exp;
6138          if(exp.type == castExp)
6139          {
6140             if(exp.cast.exp)
6141                ComputeExpression(exp.cast.exp);
6142             e = exp.cast.exp;
6143          }
6144          if(e && exp.expType)
6145          {
6146             /*if(exp.destType)
6147                type = exp.destType;
6148             else*/
6149                type = exp.expType;
6150             if(type.kind == classType)
6151             {
6152                Class _class = type._class.registered;
6153                if(_class && (_class.type == unitClass || _class.type == bitClass))
6154                {
6155                   if(!_class.dataType)
6156                      _class.dataType = ProcessTypeString(_class.dataTypeString, false);
6157                   type = _class.dataType;
6158                }
6159             }
6160
6161             switch(type.kind)
6162             {
6163                case _BoolType:
6164                case charType:
6165                   if(type.isSigned)
6166                   {
6167                      char value = 0;
6168                      if(GetChar(e, &value))
6169                      {
6170                         FreeExpContents(exp);
6171                         exp.constant = PrintChar(value);
6172                         exp.type = constantExp;
6173                      }
6174                   }
6175                   else
6176                   {
6177                      unsigned char value = 0;
6178                      if(GetUChar(e, &value))
6179                      {
6180                         FreeExpContents(exp);
6181                         exp.constant = PrintUChar(value);
6182                         exp.type = constantExp;
6183                      }
6184                   }
6185                   break;
6186                case shortType:
6187                   if(type.isSigned)
6188                   {
6189                      short value = 0;
6190                      if(GetShort(e, &value))
6191                      {
6192                         FreeExpContents(exp);
6193                         exp.constant = PrintShort(value);
6194                         exp.type = constantExp;
6195                      }
6196                   }
6197                   else
6198                   {
6199                      unsigned short value = 0;
6200                      if(GetUShort(e, &value))
6201                      {
6202                         FreeExpContents(exp);
6203                         exp.constant = PrintUShort(value);
6204                         exp.type = constantExp;
6205                      }
6206                   }
6207                   break;
6208                case intType:
6209                   if(type.isSigned)
6210                   {
6211                      int value = 0;
6212                      if(GetInt(e, &value))
6213                      {
6214                         FreeExpContents(exp);
6215                         exp.constant = PrintInt(value);
6216                         exp.type = constantExp;
6217                      }
6218                   }
6219                   else
6220                   {
6221                      unsigned int value = 0;
6222                      if(GetUInt(e, &value))
6223                      {
6224                         FreeExpContents(exp);
6225                         exp.constant = PrintUInt(value);
6226                         exp.type = constantExp;
6227                      }
6228                   }
6229                   break;
6230                case int64Type:
6231                   if(type.isSigned)
6232                   {
6233                      int64 value = 0;
6234                      if(GetInt64(e, &value))
6235                      {
6236                         FreeExpContents(exp);
6237                         exp.constant = PrintInt64(value);
6238                         exp.type = constantExp;
6239                      }
6240                   }
6241                   else
6242                   {
6243                      uint64 value = 0;
6244                      if(GetUInt64(e, &value))
6245                      {
6246                         FreeExpContents(exp);
6247                         exp.constant = PrintUInt64(value);
6248                         exp.type = constantExp;
6249                      }
6250                   }
6251                   break;
6252                case intPtrType:
6253                   if(type.isSigned)
6254                   {
6255                      intptr value = 0;
6256                      if(GetIntPtr(e, &value))
6257                      {
6258                         FreeExpContents(exp);
6259                         exp.constant = PrintInt64((int64)value);
6260                         exp.type = constantExp;
6261                      }
6262                   }
6263                   else
6264                   {
6265                      uintptr value = 0;
6266                      if(GetUIntPtr(e, &value))
6267                      {
6268                         FreeExpContents(exp);
6269                         exp.constant = PrintUInt64((uint64)value);
6270                         exp.type = constantExp;
6271                      }
6272                   }
6273                   break;
6274                case intSizeType:
6275                   if(type.isSigned)
6276                   {
6277                      intsize value = 0;
6278                      if(GetIntSize(e, &value))
6279                      {
6280                         FreeExpContents(exp);
6281                         exp.constant = PrintInt64((int64)value);
6282                         exp.type = constantExp;
6283                      }
6284                   }
6285                   else
6286                   {
6287                      uintsize value = 0;
6288                      if(GetUIntSize(e, &value))
6289                      {
6290                         FreeExpContents(exp);
6291                         exp.constant = PrintUInt64((uint64)value);
6292                         exp.type = constantExp;
6293                      }
6294                   }
6295                   break;
6296                case floatType:
6297                {
6298                   float value = 0;
6299                   if(GetFloat(e, &value))
6300                   {
6301                      FreeExpContents(exp);
6302                      exp.constant = PrintFloat(value);
6303                      exp.type = constantExp;
6304                   }
6305                   break;
6306                }
6307                case doubleType:
6308                {
6309                   double value = 0;
6310                   if(GetDouble(e, &value))
6311                   {
6312                      FreeExpContents(exp);
6313                      exp.constant = PrintDouble(value);
6314                      exp.type = constantExp;
6315                   }
6316                   break;
6317                }
6318             }
6319          }
6320          break;
6321       }
6322       case conditionExp:
6323       {
6324          Operand op1 { };
6325          Operand op2 { };
6326          Operand op3 { };
6327
6328          if(exp.cond.exp)
6329             // Caring only about last expression for now...
6330             ComputeExpression(exp.cond.exp->last);
6331          if(exp.cond.elseExp)
6332             ComputeExpression(exp.cond.elseExp);
6333          if(exp.cond.cond)
6334             ComputeExpression(exp.cond.cond);
6335
6336          op1 = GetOperand(exp.cond.cond);
6337          if(op1.type) op1.type.refCount++;
6338          op2 = GetOperand(exp.cond.exp->last);
6339          if(op2.type) op2.type.refCount++;
6340          op3 = GetOperand(exp.cond.elseExp);
6341          if(op3.type) op3.type.refCount++;
6342
6343          if(op1.ops.Cond) { FreeExpContents(exp); op1.ops.Cond(exp, op1, op2, op3); }
6344          if(op1.type) FreeType(op1.type);
6345          if(op2.type) FreeType(op2.type);
6346          if(op3.type) FreeType(op3.type);
6347          break;
6348       }
6349    }
6350 }
6351
6352 static bool CheckExpressionType(Expression exp, Type destType, bool skipUnitBla, bool warnConst)
6353 {
6354    bool result = true;
6355    if(destType)
6356    {
6357       OldList converts { };
6358       Conversion convert;
6359
6360       if(destType.kind == voidType)
6361          return false;
6362
6363       if(!MatchTypeExpression(exp, destType, &converts, skipUnitBla, warnConst))
6364          result = false;
6365       if(converts.count)
6366       {
6367          // for(convert = converts.last; convert; convert = convert.prev)
6368          for(convert = converts.first; convert; convert = convert.next)
6369          {
6370             bool empty = !(convert.isGet ? (void *)convert.convert.Get : (void *)convert.convert.Set);
6371             if(!empty)
6372             {
6373                Expression newExp { };
6374                ClassObjectType objectType = exp.expType ? exp.expType.classObjectType : none;
6375
6376                // TODO: Check this...
6377                *newExp = *exp;
6378                newExp.prev = null;
6379                newExp.next = null;
6380                newExp.destType = null;
6381
6382                if(convert.isGet)
6383                {
6384                   // [exp].ColorRGB
6385                   exp.type = memberExp;
6386                   exp.addedThis = true;
6387                   exp.member.exp = newExp;
6388                   FreeType(exp.member.exp.expType);
6389
6390                   exp.member.exp.expType = MkClassType(convert.convert._class.fullName);
6391                   exp.member.exp.expType.classObjectType = objectType;
6392                   exp.member.member = MkIdentifier(convert.convert.dataTypeString);
6393                   exp.member.memberType = propertyMember;
6394                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6395                   // TESTING THIS... for (int)degrees
6396                   exp.needCast = true;
6397                   if(exp.expType) exp.expType.refCount++;
6398                   ApplyAnyObjectLogic(exp.member.exp);
6399                }
6400                else
6401                {
6402
6403                   /*if(exp.isConstant)
6404                   {
6405                      // Color { ColorRGB = [exp] };
6406                      exp.type = instanceExp;
6407                      exp.instance = MkInstantiation(MkSpecifierName((convert.convert._class.fullName), //MkClassName(convert.convert._class.fullName),
6408                         null, MkListOne(MkMembersInitList(MkListOne(MkMemberInit(
6409                         MkListOne(MkIdentifier(convert.convert.dataTypeString)), newExp)))));
6410                   }
6411                   else*/
6412                   {
6413                      // If not constant, don't turn it yet into an instantiation
6414                      // (Go through the deep members system first)
6415                      exp.type = memberExp;
6416                      exp.addedThis = true;
6417                      exp.member.exp = newExp;
6418
6419                      // ADDED THIS HERE TO SOLVE PROPERTY ISSUES WITH NOHEAD CLASSES
6420                      if(/*!notByReference && */newExp.expType && newExp.expType.kind == classType && newExp.expType._class && newExp.expType._class.registered &&
6421                         newExp.expType._class.registered.type == noHeadClass)
6422                      {
6423                         newExp.byReference = true;
6424                      }
6425
6426                      FreeType(exp.member.exp.expType);
6427                      /*exp.member.exp.expType = convert.convert.dataType;
6428                      if(convert.convert.dataType) convert.convert.dataType.refCount++;*/
6429                      exp.member.exp.expType = null;
6430                      if(convert.convert.dataType)
6431                      {
6432                         exp.member.exp.expType = { };
6433                         CopyTypeInto(exp.member.exp.expType, convert.convert.dataType);
6434                         exp.member.exp.expType.refCount = 1;
6435                         exp.member.exp.expType.classObjectType = objectType;
6436                         ApplyAnyObjectLogic(exp.member.exp);
6437                      }
6438
6439                      exp.member.member = MkIdentifier(convert.convert._class.fullName);
6440                      exp.member.memberType = reverseConversionMember;
6441                      exp.expType = convert.resultType ? convert.resultType :
6442                         MkClassType(convert.convert._class.fullName);
6443                      exp.needCast = true;
6444                      if(convert.resultType) convert.resultType.refCount++;
6445                   }
6446                }
6447             }
6448             else
6449             {
6450                FreeType(exp.expType);
6451                if(convert.isGet)
6452                {
6453                   exp.expType = convert.resultType ? convert.resultType : convert.convert.dataType;
6454                   if(exp.destType.casted)
6455                      exp.needCast = true;
6456                   if(exp.expType) exp.expType.refCount++;
6457                }
6458                else
6459                {
6460                   exp.expType = convert.resultType ? convert.resultType : MkClassType(convert.convert._class.fullName);
6461                   if(exp.destType.casted)
6462                      exp.needCast = true;
6463                   if(convert.resultType)
6464                      convert.resultType.refCount++;
6465                }
6466             }
6467          }
6468          if(exp.isConstant && inCompiler)
6469             ComputeExpression(exp);
6470
6471          converts.Free(FreeConvert);
6472       }
6473
6474       if(!result && exp.expType && converts.count)      // TO TEST: Added converts.count here to avoid a double warning with function type
6475       {
6476          result = MatchTypes(exp.expType, exp.destType, null, null, null, true, true, false, false, warnConst);
6477       }
6478       if(!result && exp.expType && exp.destType)
6479       {
6480          if((exp.destType.kind == classType && exp.expType.kind == pointerType &&
6481              exp.expType.type.kind == classType && exp.expType.type._class == exp.destType._class && exp.destType._class.registered && exp.destType._class.registered.type == structClass) ||
6482             (exp.expType.kind == classType && exp.destType.kind == pointerType &&
6483             exp.destType.type.kind == classType && exp.destType.type._class == exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass))
6484             result = true;
6485       }
6486    }
6487    // if(result) CheckTemplateTypes(exp);
6488    return result;
6489 }
6490
6491 void CheckTemplateTypes(Expression exp)
6492 {
6493    /*
6494    bool et = exp.expType ? exp.expType.passAsTemplate : false;
6495    bool dt = exp.destType ? exp.destType.passAsTemplate : false;
6496    */
6497    Expression nbExp = GetNonBracketsExp(exp);
6498    if(exp.destType && exp.destType.passAsTemplate && exp.expType && exp.expType.kind != templateType && !exp.expType.passAsTemplate &&
6499       (nbExp == exp || nbExp.type != castExp))
6500    {
6501       Expression newExp { };
6502       Context context;
6503       TypeKind kind = exp.expType.kind;
6504       *newExp = *exp;
6505       if(exp.destType) exp.destType.refCount++;
6506       if(exp.expType)  exp.expType.refCount++;
6507       newExp.prev = null;
6508       newExp.next = null;
6509
6510       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6511       {
6512          Class c = exp.expType._class.registered;
6513          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6514          {
6515             if(!c.dataType)
6516                c.dataType = ProcessTypeString(c.dataTypeString, false);
6517             kind = c.dataType.kind;
6518          }
6519       }
6520
6521       switch(kind)
6522       {
6523          case doubleType:
6524             if(exp.destType.classObjectType)
6525             {
6526                // We need to pass the address, just pass it along (Undo what was done above)
6527                if(exp.destType) exp.destType.refCount--;
6528                if(exp.expType)  exp.expType.refCount--;
6529                delete newExp;
6530             }
6531             else
6532             {
6533                // If we're looking for value:
6534                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6535                OldList * specs;
6536                OldList * unionDefs = MkList();
6537                OldList * statements = MkList();
6538                context = PushContext();
6539                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6540                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6541                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6542                exp.type = extensionCompoundExp;
6543                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6544                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")), '=', newExp))));
6545                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")))));
6546                exp.compound.compound.context = context;
6547                PopContext(context);
6548             }
6549             break;
6550          default:
6551             exp.type = castExp;
6552             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6553             if((exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass) || exp.expType.isPointerType)
6554                exp.cast.exp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), MkExpBrackets(MkListOne(newExp)));
6555             else
6556                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6557             exp.needCast = true;
6558             break;
6559       }
6560    }
6561    else if(exp.expType && exp.expType.passAsTemplate && exp.destType && exp.usage.usageGet && exp.destType.kind != templateType && !exp.destType.passAsTemplate)
6562    {
6563       Expression newExp { };
6564       Context context;
6565       TypeKind kind = exp.expType.kind;
6566       *newExp = *exp;
6567       if(exp.destType) exp.destType.refCount++;
6568       if(exp.expType)  exp.expType.refCount++;
6569       newExp.prev = null;
6570       newExp.next = null;
6571
6572       if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered)
6573       {
6574          Class c = exp.expType._class.registered;
6575          if(c.type == bitClass || c.type == enumClass || c.type == unitClass)
6576          {
6577             if(!c.dataType)
6578                c.dataType = ProcessTypeString(c.dataTypeString, false);
6579             kind = c.dataType.kind;
6580          }
6581       }
6582
6583       switch(kind)
6584       {
6585          case doubleType:
6586             if(exp.destType.classObjectType)
6587             {
6588                // We need to pass the address, just pass it along (Undo what was done above)
6589                if(exp.destType) exp.destType.refCount--;
6590                if(exp.expType)  exp.expType.refCount--;
6591                delete newExp;
6592             }
6593             else
6594             {
6595                // If we're looking for value:
6596                // ({ union { double d; uint64 i; } u; u.i = [newExp]; u.d; })
6597                OldList * specs;
6598                OldList * unionDefs = MkList();
6599                OldList * statements = MkList();
6600                context = PushContext();
6601                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifier(DOUBLE)), MkListOne(MkDeclaratorIdentifier(MkIdentifier("d"))), null)));
6602                ListAdd(unionDefs, MkClassDefDeclaration(MkStructDeclaration(MkListOne(MkSpecifierName("uint64")), MkListOne(MkDeclaratorIdentifier(MkIdentifier("i"))), null)));
6603                specs = MkListOne(MkStructOrUnion(unionSpecifier, null, unionDefs ));
6604                exp.type = extensionCompoundExp;
6605                exp.compound = MkCompoundStmt(MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internal_union")), null)))),statements);
6606                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("i")), '=', newExp))));
6607                ListAdd(statements, MkExpressionStmt(MkListOne(MkExpMember(MkExpIdentifier(MkIdentifier("__internal_union")), MkIdentifier("d")))));
6608                exp.compound.compound.context = context;
6609                PopContext(context);
6610             }
6611             break;
6612          case classType:
6613          {
6614             if(exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type == structClass)
6615             {
6616                exp.type = bracketsExp;
6617
6618                newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6619                exp.list = MkListOne(MkExpOp(null, '*', MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)),
6620                   MkDeclaratorPointer(MkPointer(null, null), null)), newExp)));
6621                ProcessExpressionType(exp.list->first);
6622                break;
6623             }
6624             else
6625             {
6626                exp.type = bracketsExp;
6627                if(exp.expType.isPointerType)
6628                {
6629                   exp.needTemplateCast = 2;
6630                   newExp.needCast = true;
6631                   newExp.needTemplateCast = 2;
6632                   newExp = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), newExp);
6633                }
6634
6635                exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(exp.expType._class.string)), null), newExp));
6636                exp.needTemplateCast = 2;
6637                newExp.needCast = true;
6638                newExp.needTemplateCast = 2;
6639                ProcessExpressionType(exp.list->first);
6640                break;
6641             }
6642          }
6643          default:
6644          {
6645             if(exp.expType.kind == templateType)
6646             {
6647                Type type = ProcessTemplateParameterType(exp.expType.templateParameter);
6648                if(type)
6649                {
6650                   FreeType(exp.destType);
6651                   FreeType(exp.expType);
6652                   delete newExp;
6653                   break;
6654                }
6655             }
6656             /*if(newExp.type == memberExp && newExp.member.memberType == dataMember)
6657             {
6658                // When was this required?    Removed to address using templated values to pass to printf()
6659                exp.type = opExp;
6660                exp.op.op = '*';
6661                exp.op.exp1 = null;
6662                exp.op.exp2 = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uint64")), MkDeclaratorPointer(MkPointer(null, null), null)),
6663                   MkExpBrackets(MkListOne(MkExpOp(null, '&', newExp))));
6664             }
6665             else*/
6666             {
6667                char typeString[1024];
6668                Declarator decl;
6669                OldList * specs = MkList();
6670                typeString[0] = '\0';
6671                PrintType(exp.expType, typeString, false, false);
6672                decl = SpecDeclFromString(typeString, specs, null);
6673
6674                exp.type = castExp;
6675                //exp.cast.typeName = MkTypeName(MkListOne(MkSpecifierName("uint64")), null);
6676                exp.cast.typeName = MkTypeName(specs, decl);
6677                exp.cast.exp = MkExpBrackets(MkListOne(newExp));
6678                exp.cast.exp.needCast = true;
6679                exp.needTemplateCast = 2;
6680                newExp.needTemplateCast = 2;
6681             }
6682             break;
6683          }
6684       }
6685    }
6686 }
6687 // TODO: The Symbol tree should be reorganized by namespaces
6688 // Name Space:
6689 //    - Tree of all symbols within (stored without namespace)
6690 //    - Tree of sub-namespaces
6691
6692 static Symbol ScanWithNameSpace(BinaryTree tree, const char * nameSpace, const char * name)
6693 {
6694    int nsLen = strlen(nameSpace);
6695    Symbol symbol;
6696    // Start at the name space prefix
6697    for(symbol = (Symbol)tree.FindPrefix(nameSpace); symbol; symbol = (Symbol)((BTNode)symbol).next)
6698    {
6699       char * s = symbol.string;
6700       if(!strncmp(s, nameSpace, nsLen))
6701       {
6702          // This supports e.g. matching ecere::Socket to ecere::net::Socket
6703          int c;
6704          char * namePart;
6705          for(c = strlen(s)-1; c >= 0; c--)
6706             if(s[c] == ':')
6707                break;
6708
6709          namePart = s+c+1;
6710          if(!strcmp(namePart, name))
6711          {
6712             // TODO: Error on ambiguity
6713             return symbol;
6714          }
6715       }
6716       else
6717          break;
6718    }
6719    return null;
6720 }
6721
6722 static Symbol FindWithNameSpace(BinaryTree tree, const char * name)
6723 {
6724    int c;
6725    char nameSpace[1024];
6726    const char * namePart;
6727    bool gotColon = false;
6728
6729    nameSpace[0] = '\0';
6730    for(c = strlen(name)-1; c >= 0; c--)
6731       if(name[c] == ':')
6732       {
6733          gotColon = true;
6734          break;
6735       }
6736
6737    namePart = name+c+1;
6738    while(c >= 0 && name[c] == ':') c--;
6739    if(c >= 0)
6740    {
6741       // Try an exact match first
6742       Symbol symbol = (Symbol)tree.FindString(name);
6743       if(symbol)
6744          return symbol;
6745
6746       // Namespace specified
6747       memcpy(nameSpace, name, c + 1);
6748       nameSpace[c+1] = 0;
6749
6750       return ScanWithNameSpace(tree, nameSpace, namePart);
6751    }
6752    else if(gotColon)
6753    {
6754       // Looking for a global symbol, e.g. ::Sleep()
6755       Symbol symbol = (Symbol)tree.FindString(namePart);
6756       return symbol;
6757    }
6758    else
6759    {
6760       // Name only (no namespace specified)
6761       Symbol symbol = (Symbol)tree.FindString(namePart);
6762       if(symbol)
6763          return symbol;
6764       return ScanWithNameSpace(tree, "", namePart);
6765    }
6766    return null;
6767 }
6768
6769 /*static */Symbol FindSymbol(const char * name, Context startContext, Context endContext, bool isStruct, bool globalNameSpace)
6770 {
6771 #ifdef _DEBUG
6772    //Time startTime = GetTime();
6773 #endif
6774    // Optimize this later? Do this before/less?
6775    Context ctx;
6776    Symbol symbol = null;
6777
6778    // First, check if the identifier is declared inside the function
6779    //for(ctx = curContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6780
6781    for(ctx = startContext; ctx /*!= topContext.parent */&& !symbol; ctx = ctx.parent)
6782    {
6783       if(ctx == globalContext && !globalNameSpace && ctx.hasNameSpace)
6784       {
6785          symbol = null;
6786          if(thisNameSpace)
6787          {
6788             char curName[1024];
6789             strcpy(curName, thisNameSpace);
6790             strcat(curName, "::");
6791             strcat(curName, name);
6792             // Try to resolve in current namespace first
6793             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, curName);
6794          }
6795          if(!symbol)
6796             symbol = FindWithNameSpace(isStruct ? ctx.structSymbols : ctx.symbols, name);
6797       }
6798       else
6799          symbol = (Symbol)(isStruct ? ctx.structSymbols : ctx.symbols).FindString(name);
6800
6801       if(symbol || ctx == endContext) break;
6802    }
6803    if(inCompiler && symbol && ctx == globalContext && symbol.pointerExternal && curExternal && symbol.pointerExternal != curExternal)
6804       curExternal.CreateUniqueEdge(symbol.pointerExternal, symbol.pointerExternal.type == functionExternal);
6805 #ifdef _DEBUG
6806    //findSymbolTotalTime += GetTime() - startTime;
6807 #endif
6808    return symbol;
6809 }
6810
6811 static void GetTypeSpecs(Type type, OldList * specs)
6812 {
6813    if(!type.isSigned && type.kind != intPtrType && type.kind != intSizeType) ListAdd(specs, MkSpecifier(UNSIGNED));
6814    switch(type.kind)
6815    {
6816       case classType:
6817       {
6818          if(type._class.registered)
6819          {
6820             if(!type._class.registered.dataType)
6821                type._class.registered.dataType = ProcessTypeString(type._class.registered.dataTypeString, false);
6822             GetTypeSpecs(type._class.registered.dataType, specs);
6823          }
6824          break;
6825       }
6826       case doubleType: ListAdd(specs, MkSpecifier(DOUBLE)); break;
6827       case floatType: ListAdd(specs, MkSpecifier(FLOAT)); break;
6828       case charType: ListAdd(specs, MkSpecifier(CHAR)); break;
6829       case _BoolType: ListAdd(specs, MkSpecifier(_BOOL)); break;
6830       case shortType: ListAdd(specs, MkSpecifier(SHORT)); break;
6831       case int64Type: ListAdd(specs, MkSpecifier(INT64)); break;
6832       case intPtrType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intptr" : "uintptr")); break;
6833       case intSizeType: ListAdd(specs, MkSpecifierName(type.isSigned ? "intsize" : "uintsize")); break;
6834       case intType:
6835       default:
6836          ListAdd(specs, MkSpecifier(INT)); break;
6837    }
6838 }
6839
6840 static void PrintArraySize(Type arrayType, char * string)
6841 {
6842    char size[256];
6843    size[0] = '\0';
6844    strcat(size, "[");
6845    if(arrayType.enumClass)
6846       strcat(size, arrayType.enumClass.string);
6847    else if(arrayType.arraySizeExp)
6848       PrintExpression(arrayType.arraySizeExp, size);
6849    strcat(size, "]");
6850    strcat(string, size);
6851 }
6852
6853 // WARNING : This function expects a null terminated string since it recursively concatenate...
6854 static void PrintTypeSpecs(Type type, char * string, bool fullName, bool printConst)
6855 {
6856    if(type)
6857    {
6858       if(printConst && type.constant)
6859          strcat(string, "const ");
6860       switch(type.kind)
6861       {
6862          case classType:
6863          {
6864             Symbol c = type._class;
6865             bool isObjectBaseClass = !c || !c.string || !strcmp(c.string, "class");
6866             // TODO: typed_object does not fully qualify the type, as it may have taken up an actual class (Stored in _class) from overriding
6867             //       look into merging with thisclass ?
6868             if(type.classObjectType == typedObject && isObjectBaseClass)
6869                strcat(string, "typed_object");
6870             else if(type.classObjectType == anyObject && isObjectBaseClass)
6871                strcat(string, "any_object");
6872             else
6873             {
6874                if(c && c.string)
6875                   strcat(string, (fullName || !c.registered) ? c.string : c.registered.name);
6876             }
6877             if(type.byReference)
6878                strcat(string, " &");
6879             break;
6880          }
6881          case voidType: strcat(string, "void"); break;
6882          case intType:  strcat(string, type.isSigned ? "int" : "uint"); break;
6883          case int64Type:  strcat(string, type.isSigned ? "int64" : "uint64"); break;
6884          case intPtrType:  strcat(string, type.isSigned ? "intptr" : "uintptr"); break;
6885          case intSizeType:  strcat(string, type.isSigned ? "intsize" : "uintsize"); break;
6886          case charType: strcat(string, type.isSigned ? "char" : "byte"); break;
6887          case _BoolType: strcat(string, "_Bool"); break;
6888          case shortType: strcat(string, type.isSigned ? "short" : "uint16"); break;
6889          case floatType: strcat(string, "float"); break;
6890          case doubleType: strcat(string, "double"); break;
6891          case structType:
6892             if(type.enumName)
6893             {
6894                strcat(string, "struct ");
6895                strcat(string, type.enumName);
6896             }
6897             else if(type.typeName)
6898                strcat(string, type.typeName);
6899             else
6900             {
6901                Type member;
6902                strcat(string, "struct { ");
6903                for(member = type.members.first; member; member = member.next)
6904                {
6905                   PrintType(member, string, true, fullName);
6906                   strcat(string,"; ");
6907                }
6908                strcat(string,"}");
6909             }
6910             break;
6911          case unionType:
6912             if(type.enumName)
6913             {
6914                strcat(string, "union ");
6915                strcat(string, type.enumName);
6916             }
6917             else if(type.typeName)
6918                strcat(string, type.typeName);
6919             else
6920             {
6921                strcat(string, "union ");
6922                strcat(string,"(unnamed)");
6923             }
6924             break;
6925          case enumType:
6926             if(type.enumName)
6927             {
6928                strcat(string, "enum ");
6929                strcat(string, type.enumName);
6930             }
6931             else if(type.typeName)
6932                strcat(string, type.typeName);
6933             else
6934                strcat(string, "int"); // "enum");
6935             break;
6936          case ellipsisType:
6937             strcat(string, "...");
6938             break;
6939          case subClassType:
6940             strcat(string, "subclass(");
6941             strcat(string, type._class ? type._class.string : "int");
6942             strcat(string, ")");
6943             break;
6944          case templateType:
6945             strcat(string, type.templateParameter.identifier.string);
6946             break;
6947          case thisClassType:
6948             strcat(string, "thisclass");
6949             break;
6950          case vaListType:
6951             strcat(string, "__builtin_va_list");
6952             break;
6953       }
6954    }
6955 }
6956
6957 static void PrintName(Type type, char * string, bool fullName)
6958 {
6959    if(type.name && type.name[0])
6960    {
6961       if(fullName)
6962          strcat(string, type.name);
6963       else
6964       {
6965          char * name = RSearchString(type.name, "::", strlen(type.name), true, false);
6966          if(name) name += 2; else name = type.name;
6967          strcat(string, name);
6968       }
6969    }
6970 }
6971
6972 static void PrintAttribs(Type type, char * string)
6973 {
6974    if(type)
6975    {
6976       if(type.dllExport)   strcat(string, "dllexport ");
6977       if(type.attrStdcall) strcat(string, "stdcall ");
6978    }
6979 }
6980
6981 static void PrePrintType(Type type, char * string, bool fullName, Type parentType, bool printConst)
6982 {
6983    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
6984    {
6985       if((type.kind == functionType || type.kind == methodType) && (!parentType || parentType.kind != pointerType))
6986          PrintAttribs(type, string);
6987       if(printConst && type.constant && (type.kind == functionType || type.kind == methodType))
6988          strcat(string, " const");
6989       PrePrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName, type, printConst);
6990       if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
6991          strcat(string, " (");
6992       if(type.kind == pointerType)
6993       {
6994          if(type.type.kind == functionType || type.type.kind == methodType)
6995             PrintAttribs(type.type, string);
6996       }
6997       if(type.kind == pointerType)
6998       {
6999          if(type.type.kind == functionType || type.type.kind == methodType || type.type.kind == arrayType)
7000             strcat(string, "*");
7001          else
7002             strcat(string, " *");
7003       }
7004       if(printConst && type.constant && type.kind == pointerType)
7005          strcat(string, " const");
7006    }
7007    else
7008       PrintTypeSpecs(type, string, fullName, printConst);
7009 }
7010
7011 static void PostPrintType(Type type, char * string, bool fullName)
7012 {
7013    if(type.kind == pointerType && (type.type.kind == arrayType || type.type.kind == functionType || type.type.kind == methodType))
7014       strcat(string, ")");
7015    if(type.kind == arrayType)
7016       PrintArraySize(type, string);
7017    else if(type.kind == functionType)
7018    {
7019       Type param;
7020       strcat(string, "(");
7021       for(param = type.params.first; param; param = param.next)
7022       {
7023          PrintType(param, string, true, fullName);
7024          if(param.next) strcat(string, ", ");
7025       }
7026       strcat(string, ")");
7027    }
7028    if(type.kind == arrayType || type.kind == pointerType || type.kind == functionType || type.kind == methodType)
7029       PostPrintType(type.kind == methodType ? type.method.dataType : type.type, string, fullName);
7030 }
7031
7032 // *****
7033 // TODO: Add a max buffer size to avoid overflows. This function is used with static size char arrays.
7034 // *****
7035 static void _PrintType(Type type, char * string, bool printName, bool fullName, bool printConst)
7036 {
7037    PrePrintType(type, string, fullName, null, printConst);
7038
7039    if(type.thisClass || (printName && type.name && type.name[0]))
7040       strcat(string, " ");
7041    if(/*(type.kind == methodType || type.kind == functionType) && */(type.thisClass || type.staticMethod))
7042    {
7043       Symbol _class = type.thisClass;
7044       if((type.classObjectType == typedObject || type.classObjectType == classPointer) || (_class && !strcmp(_class.string, "class")))
7045       {
7046          if(type.classObjectType == classPointer)
7047             strcat(string, "class");
7048          else
7049             strcat(string, type.byReference ? "typed_object&" : "typed_object");
7050       }
7051       else if(_class && _class.string)
7052       {
7053          String s = _class.string;
7054          if(fullName)
7055             strcat(string, s);
7056          else
7057          {
7058             char * name = RSearchString(s, "::", strlen(s), true, false);
7059             if(name) name += 2; else name = s;
7060             strcat(string, name);
7061          }
7062       }
7063       strcat(string, "::");
7064    }
7065
7066    if(printName && type.name)
7067       PrintName(type, string, fullName);
7068    PostPrintType(type, string, fullName);
7069    if(type.bitFieldCount)
7070    {
7071       char count[100];
7072       sprintf(count, ":%d", type.bitFieldCount);
7073       strcat(string, count);
7074    }
7075 }
7076
7077 void PrintType(Type type, char * string, bool printName, bool fullName)
7078 {
7079    _PrintType(type, string, printName, fullName, true);
7080 }
7081
7082 void PrintTypeNoConst(Type type, char * string, bool printName, bool fullName)
7083 {
7084    _PrintType(type, string, printName, fullName, false);
7085 }
7086
7087 static Type FindMember(Type type, char * string)
7088 {
7089    Type memberType;
7090    for(memberType = type.members.first; memberType; memberType = memberType.next)
7091    {
7092       if(!memberType.name)
7093       {
7094          Type subType = FindMember(memberType, string);
7095          if(subType)
7096             return subType;
7097       }
7098       else if(!strcmp(memberType.name, string))
7099          return memberType;
7100    }
7101    return null;
7102 }
7103
7104 Type FindMemberAndOffset(Type type, char * string, uint * offset)
7105 {
7106    Type memberType;
7107    for(memberType = type.members.first; memberType; memberType = memberType.next)
7108    {
7109       if(!memberType.name)
7110       {
7111          Type subType = FindMember(memberType, string);
7112          if(subType)
7113          {
7114             *offset += memberType.offset;
7115             return subType;
7116          }
7117       }
7118       else if(!strcmp(memberType.name, string))
7119       {
7120          *offset += memberType.offset;
7121          return memberType;
7122       }
7123    }
7124    return null;
7125 }
7126
7127 public bool GetParseError() { return parseError; }
7128
7129 Expression ParseExpressionString(char * expression)
7130 {
7131    parseError = false;
7132
7133    fileInput = TempFile { };
7134    fileInput.Write(expression, 1, strlen(expression));
7135    fileInput.Seek(0, start);
7136
7137    echoOn = false;
7138    parsedExpression = null;
7139    resetScanner();
7140    expression_yyparse();
7141    delete fileInput;
7142
7143    return parsedExpression;
7144 }
7145
7146 static bool ResolveIdWithClass(Expression exp, Class _class, bool skipIDClassCheck)
7147 {
7148    Identifier id = exp.identifier;
7149    Method method = null;
7150    Property prop = null;
7151    DataMember member = null;
7152    ClassProperty classProp = null;
7153
7154    if(_class && _class.type == enumClass)
7155    {
7156       NamedLink64 value = null;
7157       Class enumClass = eSystem_FindClass(privateModule, "enum");
7158       if(enumClass)
7159       {
7160          Class baseClass;
7161          for(baseClass = _class; baseClass && baseClass.type == ClassType::enumClass; baseClass = baseClass.base)
7162          {
7163             EnumClassData e = ACCESS_CLASSDATA(baseClass, enumClass);
7164             for(value = e.values.first; value; value = value.next)
7165             {
7166                if(!strcmp(value.name, id.string))
7167                   break;
7168             }
7169             if(value)
7170             {
7171                exp.isConstant = true;
7172                if(inCompiler || inPreCompiler || inDebugger)
7173                {
7174                   char constant[256];
7175                   FreeExpContents(exp);
7176
7177                   exp.type = constantExp;
7178                   if(!strcmp(baseClass.dataTypeString, "int") || !strcmp(baseClass.dataTypeString, "int64") || !strcmp(baseClass.dataTypeString, "char") || !strcmp(baseClass.dataTypeString, "short"))
7179                      sprintf(constant, FORMAT64D, value.data);
7180                   else
7181                      sprintf(constant, FORMAT64HEX, value.data);
7182                   exp.constant = CopyString(constant);
7183                }
7184                //for(;_class.base && _class.base.type != systemClass; _class = _class.base);
7185                exp.expType = MkClassType(baseClass.fullName);
7186                break;
7187             }
7188          }
7189       }
7190       if(value)
7191          return true;
7192    }
7193    if((method = eClass_FindMethod(_class, id.string, privateModule)))
7194    {
7195       ProcessMethodType(method);
7196       exp.expType = Type
7197       {
7198          refCount = 1;
7199          kind = methodType;
7200          method = method;
7201          // Crash here?
7202          // TOCHECK: Put it back to what it was...
7203          // methodClass = _class;
7204          methodClass = (skipIDClassCheck || (id && id._class)) ? _class : null;
7205       };
7206       //id._class = null;
7207       return true;
7208    }
7209    else if((prop = eClass_FindProperty(_class, id.string, privateModule)))
7210    {
7211       if(!prop.dataType)
7212          ProcessPropertyType(prop);
7213       exp.expType = prop.dataType;
7214       if(prop.dataType) prop.dataType.refCount++;
7215       return true;
7216    }
7217    else if((member = eClass_FindDataMember(_class, id.string, privateModule, null, null)))
7218    {
7219       if(!member.dataType)
7220          member.dataType = ProcessTypeString(member.dataTypeString, false);
7221       exp.expType = member.dataType;
7222       if(member.dataType) member.dataType.refCount++;
7223       return true;
7224    }
7225    else if((classProp = eClass_FindClassProperty(_class, id.string)))
7226    {
7227       if(!classProp.dataType)
7228          classProp.dataType = ProcessTypeString(classProp.dataTypeString, false);
7229
7230       if(classProp.constant)
7231       {
7232          FreeExpContents(exp);
7233
7234          exp.isConstant = true;
7235          if(classProp.dataType.kind == pointerType && classProp.dataType.type.kind == charType)
7236          {
7237             //char constant[256];
7238             exp.type = stringExp;
7239             exp.constant = QMkString((char *)(uintptr)classProp.Get(_class));
7240          }
7241          else
7242          {
7243             char constant[256];
7244             exp.type = constantExp;
7245             sprintf(constant, "%d", (int)classProp.Get(_class));
7246             exp.constant = CopyString(constant);
7247          }
7248       }
7249       else
7250       {
7251          // TO IMPLEMENT...
7252       }
7253
7254       exp.expType = classProp.dataType;
7255       if(classProp.dataType) classProp.dataType.refCount++;
7256       return true;
7257    }
7258    return false;
7259 }
7260
7261 static GlobalData ScanGlobalData(NameSpace nameSpace, char * name)
7262 {
7263    BinaryTree * tree = &nameSpace.functions;
7264    GlobalData data = (GlobalData)tree->FindString(name);
7265    NameSpace * child;
7266    if(!data)
7267    {
7268       for(child = (NameSpace *)nameSpace.nameSpaces.first; child; child = (NameSpace *)((BTNode)child).next)
7269       {
7270          data = ScanGlobalData(child, name);
7271          if(data)
7272             break;
7273       }
7274    }
7275    return data;
7276 }
7277
7278 static GlobalData FindGlobalData(char * name)
7279 {
7280    int start = 0, c;
7281    NameSpace * nameSpace;
7282    nameSpace = globalData;
7283    for(c = 0; name[c]; c++)
7284    {
7285       if(name[c] == '.' || (name[c] == ':' && name[c+1] == ':'))
7286       {
7287          NameSpace * newSpace;
7288          char * spaceName = new char[c - start + 1];
7289          strncpy(spaceName, name + start, c - start);
7290          spaceName[c-start] = '\0';
7291          newSpace = (NameSpace *)nameSpace->nameSpaces.FindString(spaceName);
7292          delete spaceName;
7293          if(!newSpace)
7294             return null;
7295          nameSpace = newSpace;
7296          if(name[c] == ':') c++;
7297          start = c+1;
7298       }
7299    }
7300    if(c - start)
7301    {
7302       return ScanGlobalData(nameSpace, name + start);
7303    }
7304    return null;
7305 }
7306
7307 static int definedExpStackPos;
7308 static void * definedExpStack[512];
7309
7310 // This function makes checkedExp equivalent to newExp, ending up freeing newExp
7311 void ReplaceExpContents(Expression checkedExp, Expression newExp)
7312 {
7313    Expression prev = checkedExp.prev, next = checkedExp.next;
7314
7315    FreeExpContents(checkedExp);
7316    FreeType(checkedExp.expType);
7317    FreeType(checkedExp.destType);
7318
7319    *checkedExp = *newExp;
7320
7321    delete newExp;
7322
7323    checkedExp.prev = prev;
7324    checkedExp.next = next;
7325 }
7326
7327 void ApplyAnyObjectLogic(Expression e)
7328 {
7329    Type destType = /*(e.destType && e.destType.kind == ellipsisType) ? ellipsisDestType : */e.destType;
7330 #ifdef _DEBUG
7331    char debugExpString[4096];
7332    debugExpString[0] = '\0';
7333    PrintExpression(e, debugExpString);
7334 #endif
7335
7336    if(destType && (/*destType.classObjectType == ClassObjectType::typedObject || */destType.classObjectType == anyObject))
7337    {
7338       //if(e.destType && e.destType.kind == ellipsisType) usedEllipsis = true;
7339       //ellipsisDestType = destType;
7340       if(e && e.expType)
7341       {
7342          Type type = e.expType;
7343          Class _class = null;
7344          //Type destType = e.destType;
7345
7346          if(type.kind == classType && type._class && type._class.registered)
7347          {
7348             _class = type._class.registered;
7349          }
7350          else if(type.kind == subClassType)
7351          {
7352             _class = FindClass("ecere::com::Class").registered;
7353          }
7354          else
7355          {
7356             char string[1024] = "";
7357             Symbol classSym;
7358
7359             PrintTypeNoConst(type, string, false, true);
7360             classSym = FindClass(string);
7361             if(classSym) _class = classSym.registered;
7362          }
7363
7364          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...
7365             (!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))) ||
7366             destType.byReference)))
7367          {
7368             if(!_class || strcmp(_class.fullName, "char *"))     // TESTING THIS WITH NEW String class...
7369             {
7370                Expression checkedExp = e, newExp;
7371
7372                while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7373                {
7374                   if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7375                   {
7376                      if(checkedExp.type == extensionCompoundExp)
7377                      {
7378                         checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7379                      }
7380                      else
7381                         checkedExp = checkedExp.list->last;
7382                   }
7383                   else if(checkedExp.type == castExp)
7384                      checkedExp = checkedExp.cast.exp;
7385                }
7386
7387                if(checkedExp && checkedExp.type == opExp && checkedExp.op.op == '*' && !checkedExp.op.exp1)
7388                {
7389                   newExp = checkedExp.op.exp2;
7390                   checkedExp.op.exp2 = null;
7391                   FreeExpContents(checkedExp);
7392
7393                   if(e.expType && e.expType.passAsTemplate)
7394                   {
7395                      char size[100];
7396                      ComputeTypeSize(e.expType);
7397                      sprintf(size, "%d", e.expType.size);   // Potential 32/64 Bootstrap issue
7398                      newExp = MkExpBrackets(MkListOne(MkExpOp(MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)),
7399                         MkDeclaratorPointer(MkPointer(null, null), null)), newExp), '+',
7400                            MkExpCall(MkExpIdentifier(MkIdentifier("__ENDIAN_PAD")), MkListOne(MkExpConstant(size))))));
7401                   }
7402
7403                   ReplaceExpContents(checkedExp, newExp);
7404                   e.byReference = true;
7405                }
7406                else if(!e.byReference || (_class && _class.type == noHeadClass))     // TESTING THIS HERE...
7407                {
7408                   Expression checkedExp; //, newExp;
7409
7410                   {
7411                      // TODO: Move code from debugTools.ec for hasAddress flag, this is just temporary
7412                      bool hasAddress =
7413                         e.type == identifierExp ||
7414                         (e.type == ExpressionType::memberExp && e.member.memberType == dataMember) ||
7415                         (e.type == ExpressionType::pointerExp && e.member.memberType == dataMember) ||
7416                         (e.type == opExp && !e.op.exp1 && e.op.op == '*') ||
7417                         e.type == indexExp;
7418
7419                      if(_class && _class.type != noHeadClass && _class.type != normalClass && _class.type != structClass && !hasAddress)
7420                      {
7421                         Context context = PushContext();
7422                         Declarator decl;
7423                         OldList * specs = MkList();
7424                         char typeString[1024];
7425                         Expression newExp { };
7426
7427                         typeString[0] = '\0';
7428                         *newExp = *e;
7429
7430                         //if(e.destType) e.destType.refCount++;
7431                         // if(exp.expType) exp.expType.refCount++;
7432                         newExp.prev = null;
7433                         newExp.next = null;
7434                         newExp.expType = null;
7435
7436                         PrintTypeNoConst(e.expType, typeString, false, true);
7437                         decl = SpecDeclFromString(typeString, specs, null);
7438                         newExp.destType = ProcessType(specs, decl);
7439
7440                         curContext = context;
7441
7442                         // We need a current compound for this
7443                         if(curCompound)
7444                         {
7445                            char name[100];
7446                            OldList * stmts = MkList();
7447                            e.type = extensionCompoundExp;
7448                            sprintf(name, "__internalValue%03X", internalValueCounter++);
7449                            if(!curCompound.compound.declarations)
7450                               curCompound.compound.declarations = MkList();
7451                            curCompound.compound.declarations->Insert(null, MkDeclaration(specs, MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(name)), null))));
7452                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(MkIdentifier(name)), '=', newExp))));
7453                            ListAdd(stmts, MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier(name)))));
7454                            e.compound = MkCompoundStmt(null, stmts);
7455                         }
7456                         else
7457                            printf("libec: compiler error, curCompound is null in ApplyAnyObjectLogic\n");
7458
7459                         /*
7460                         e.compound = MkCompoundStmt(
7461                            MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(
7462                               MkDeclaratorIdentifier(MkIdentifier("__internalValue")), MkInitializerAssignment(newExp))))),
7463
7464                            MkListOne(MkExpressionStmt(MkListOne(MkExpIdentifier(MkIdentifier("__internalValue"))))));
7465                         */
7466
7467                         {
7468                            Type type = e.destType;
7469                            e.destType = { };
7470                            CopyTypeInto(e.destType, type);
7471                            e.destType.refCount = 1;
7472                            e.destType.classObjectType = none;
7473                            FreeType(type);
7474                         }
7475
7476                         e.compound.compound.context = context;
7477                         PopContext(context);
7478                         curContext = context.parent;
7479                      }
7480                   }
7481
7482                   // TODO: INTEGRATE THIS WITH VERSION ABOVE WHICH WAS ADDED TO ENCOMPASS OTHER CASE (*pointer)
7483                   checkedExp = e;
7484                   while(((checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp) && checkedExp.list) || checkedExp.type == castExp)
7485                   {
7486                      if(checkedExp.type == bracketsExp || checkedExp.type == extensionExpressionExp || checkedExp.type == extensionCompoundExp)
7487                      {
7488                         if(checkedExp.type == extensionCompoundExp)
7489                         {
7490                            checkedExp = ((Statement)checkedExp.compound.compound.statements->last).expressions->last;
7491                         }
7492                         else
7493                            checkedExp = checkedExp.list->last;
7494                      }
7495                      else if(checkedExp.type == castExp)
7496                         checkedExp = checkedExp.cast.exp;
7497                   }
7498                   {
7499                      Expression operand { };
7500                      operand = *checkedExp;
7501                      checkedExp.Clear();
7502                      checkedExp.destType = ProcessTypeString("void *", false);
7503                      checkedExp.expType = checkedExp.destType;
7504                      checkedExp.destType.refCount++;
7505
7506                      checkedExp.type = opExp;
7507                      checkedExp.op.op = '&';
7508                      checkedExp.op.exp1 = null;
7509                      checkedExp.op.exp2 = operand;
7510
7511                      //newExp = MkExpOp(null, '&', checkedExp);
7512                   }
7513                   //ReplaceExpContents(checkedExp, newExp);
7514                }
7515             }
7516          }
7517       }
7518    }
7519    {
7520       // If expression type is a simple class, make it an address
7521       // FixReference(e, true);
7522    }
7523 //#if 0
7524    if((!destType || destType.kind == ellipsisType || destType.kind == voidType) && e.expType && (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7525       (e.expType.byReference || (e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7526          (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass ) )))
7527    {
7528       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"))
7529       {
7530          return;  // LEAVE THIS CASE (typed_object & :: methods 's this) TO PASS 2 FOR NOW
7531       }
7532       else
7533       {
7534          Expression thisExp { };
7535
7536          *thisExp = *e;
7537          thisExp.prev = null;
7538          thisExp.next = null;
7539          e.Clear();
7540
7541          e.type = bracketsExp;
7542          e.list = MkListOne(MkExpOp(null, '*', thisExp.type == identifierExp ? thisExp : MkExpBrackets(MkListOne(thisExp))));
7543          if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && thisExp.expType._class.registered.type == noHeadClass)
7544             ((Expression)e.list->first).byReference = true;
7545
7546          /*if(thisExp.expType.kind == classType && thisExp.expType._class && thisExp.expType._class.registered && !strcmp(thisExp.expType._class.registered.name, "class"))
7547          {
7548             e.expType = thisExp.expType;
7549             e.expType.refCount++;
7550          }
7551          else*/
7552          {
7553             e.expType = { };
7554             CopyTypeInto(e.expType, thisExp.expType);
7555             e.expType.byReference = false;
7556             e.expType.refCount = 1;
7557
7558             if(e.expType.kind == classType && e.expType._class && e.expType._class.registered &&
7559                (e.expType._class.registered.type == bitClass || e.expType._class.registered.type == enumClass || e.expType._class.registered.type == unitClass))
7560             {
7561                e.expType.classObjectType = none;
7562             }
7563          }
7564       }
7565    }
7566 // TOFIX: Try this for a nice IDE crash!
7567 //#endif
7568    // The other way around
7569    else
7570 //#endif
7571    if(destType && e.expType &&
7572          //e.expType.kind == classType && e.expType._class && e.expType._class.registered && !strcmp(e.expType._class.registered.name, "class") &&
7573          (e.expType.classObjectType == anyObject || e.expType.classObjectType == typedObject) &&
7574          !destType.classObjectType && /*(destType.kind != pointerType || !destType.type || destType.type.kind != voidType) &&*/ destType.kind != voidType)
7575    {
7576       if(destType.kind == ellipsisType)
7577       {
7578          Compiler_Error($"Unspecified type\n");
7579       }
7580       else if(!(destType.truth && e.expType.kind == classType && e.expType._class && e.expType._class.registered && e.expType._class.registered.type == structClass))
7581       {
7582          bool byReference = e.expType.byReference;
7583          Expression thisExp { };
7584          Declarator decl;
7585          OldList * specs = MkList();
7586          char typeString[1024]; // Watch buffer overruns
7587          Type type;
7588          ClassObjectType backupClassObjectType;
7589          bool backupByReference;
7590
7591          if(e.expType.kind == classType && e.expType._class && e.expType._class.registered && strcmp(e.expType._class.registered.name, "class"))
7592             type = e.expType;
7593          else
7594             type = destType;
7595
7596          backupClassObjectType = type.classObjectType;
7597          backupByReference = type.byReference;
7598
7599          type.classObjectType = none;
7600          type.byReference = false;
7601
7602          typeString[0] = '\0';
7603          PrintType(type, typeString, false, true);
7604          decl = SpecDeclFromString(typeString, specs, null);
7605
7606          type.classObjectType = backupClassObjectType;
7607          type.byReference = backupByReference;
7608
7609          *thisExp = *e;
7610          thisExp.prev = null;
7611          thisExp.next = null;
7612          e.Clear();
7613
7614          if( ( type.kind == classType && type._class && type._class.registered &&
7615                    (type._class.registered.type == systemClass || type._class.registered.type == bitClass ||
7616                     type._class.registered.type == enumClass || type._class.registered.type == unitClass) ) ||
7617              (type.kind != pointerType && type.kind != intPtrType && type.kind != arrayType && type.kind != classType) ||
7618              (!destType.byReference && byReference && (destType.kind != pointerType || type.kind != pointerType)))
7619          {
7620             bool passAsTemplate = thisExp.destType.passAsTemplate;
7621             Type t;
7622
7623             destType.refCount++;
7624
7625             e.type = opExp;
7626             e.op.op = '*';
7627             e.op.exp1 = null;
7628             e.op.exp2 = MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), thisExp);
7629
7630             t = { };
7631             CopyTypeInto(t, thisExp.destType);
7632             t.passAsTemplate = false;
7633             FreeType(thisExp.destType);
7634             thisExp.destType = t;
7635
7636             t = { };
7637             CopyTypeInto(t, destType);
7638             t.passAsTemplate = passAsTemplate;
7639             FreeType(destType);
7640             destType = t;
7641             destType.refCount = 0;
7642
7643             e.expType = { };
7644             CopyTypeInto(e.expType, type);
7645             if(type.passAsTemplate)
7646             {
7647                e.expType.classObjectType = none;
7648                e.expType.passAsTemplate = false;
7649             }
7650             e.expType.byReference = false;
7651             e.expType.refCount = 1;
7652          }
7653          else
7654          {
7655             e.type = castExp;
7656             e.cast.typeName = MkTypeName(specs, decl);
7657             e.cast.exp = thisExp;
7658             e.byReference = true;
7659             e.expType = type;
7660             type.refCount++;
7661          }
7662
7663          if(e.destType)
7664             FreeType(e.destType);
7665
7666          e.destType = destType;
7667          destType.refCount++;
7668       }
7669    }
7670 }
7671
7672 void ApplyLocation(Expression exp, Location loc)
7673 {
7674    exp.loc = loc;
7675    switch(exp.type)
7676    {
7677       case opExp:
7678          if(exp.op.exp1) ApplyLocation(exp.op.exp1, loc);
7679          if(exp.op.exp2) ApplyLocation(exp.op.exp2, loc);
7680          break;
7681       case bracketsExp:
7682          if(exp.list)
7683          {
7684             Expression e;
7685             for(e = exp.list->first; e; e = e.next)
7686                ApplyLocation(e, loc);
7687          }
7688          break;
7689       case indexExp:
7690          if(exp.index.index)
7691          {
7692             Expression e;
7693             for(e = exp.index.index->first; e; e = e.next)
7694                ApplyLocation(e, loc);
7695          }
7696          if(exp.index.exp)
7697             ApplyLocation(exp.index.exp, loc);
7698          break;
7699       case callExp:
7700          if(exp.call.arguments)
7701          {
7702             Expression arg;
7703             for(arg = exp.call.arguments->first; arg; arg = arg.next)
7704                ApplyLocation(arg, loc);
7705          }
7706          if(exp.call.exp)
7707             ApplyLocation(exp.call.exp, loc);
7708          break;
7709       case memberExp:
7710       case pointerExp:
7711          if(exp.member.exp)
7712             ApplyLocation(exp.member.exp, loc);
7713          break;
7714       case castExp:
7715          if(exp.cast.exp)
7716             ApplyLocation(exp.cast.exp, loc);
7717          break;
7718       case conditionExp:
7719          if(exp.cond.exp)
7720          {
7721             Expression e;
7722             for(e = exp.cond.exp->first; e; e = e.next)
7723                ApplyLocation(e, loc);
7724          }
7725          if(exp.cond.cond)
7726             ApplyLocation(exp.cond.cond, loc);
7727          if(exp.cond.elseExp)
7728             ApplyLocation(exp.cond.elseExp, loc);
7729          break;
7730       case vaArgExp:
7731          if(exp.vaArg.exp)
7732             ApplyLocation(exp.vaArg.exp, loc);
7733          break;
7734       default:
7735          break;
7736    }
7737 }
7738
7739 void ProcessExpressionType(Expression exp)
7740 {
7741    bool unresolved = false;
7742    Location oldyylloc = yylloc;
7743    bool notByReference = false;
7744 #ifdef _DEBUG
7745    char debugExpString[4096];
7746    debugExpString[0] = '\0';
7747    PrintExpression(exp, debugExpString);
7748 #endif
7749    if(!exp || exp.expType)
7750       return;
7751
7752    //eSystem_Logf("%s\n", expString);
7753
7754    // Testing this here
7755    yylloc = exp.loc;
7756    switch(exp.type)
7757    {
7758       case identifierExp:
7759       {
7760          Identifier id = exp.identifier;
7761          if(!id || !topContext) return;
7762
7763          // DOING THIS LATER NOW...
7764          if(id._class && id._class.name)
7765          {
7766             id.classSym = id._class.symbol; // FindClass(id._class.name);
7767             /* TODO: Name Space Fix ups
7768             if(!id.classSym)
7769                id.nameSpace = eSystem_FindNameSpace(privateModule, id._class.name);
7770             */
7771          }
7772
7773          /* WHY WAS THIS COMMENTED OUT? if(!strcmp(id.string, "__thisModule"))
7774          {
7775             exp.expType = ProcessTypeString("Module", true);
7776             break;
7777          }
7778          else */
7779          if(!strcmp(id.string, "__runtimePlatform"))
7780          {
7781             exp.expType = ProcessTypeString("ecere::com::Platform", true);
7782             break;
7783          }
7784          else if(strstr(id.string, "__ecereClass") == id.string)
7785          {
7786             exp.expType = ProcessTypeString("ecere::com::Class", true);
7787             break;
7788          }
7789          else if(id._class && (id.classSym || (id._class.name && !strcmp(id._class.name, "property"))))
7790          {
7791             // Added this here as well
7792             ReplaceClassMembers(exp, thisClass);
7793             if(exp.type != identifierExp)
7794             {
7795                ProcessExpressionType(exp);
7796                break;
7797             }
7798
7799             if(id.classSym && ResolveIdWithClass(exp, id.classSym.registered, false))
7800                break;
7801          }
7802          else
7803          {
7804             Symbol symbol = FindSymbol(id.string, curContext, topContext /*exp.destType ? topContext : globalContext*/, false, id._class && id._class.name == null);
7805             // Enums should be resolved here (Special pass in opExp to fix identifiers not seen as enum on the first pass)
7806             if(!symbol/* && exp.destType*/)
7807             {
7808                if(exp.destType && CheckExpressionType(exp, exp.destType, false, false))
7809                   break;
7810                else
7811                {
7812                   if(thisClass)
7813                   {
7814                      ReplaceClassMembers(exp, thisClass ? thisClass : currentClass);
7815                      if(exp.type != identifierExp)
7816                      {
7817                         ProcessExpressionType(exp);
7818                         break;
7819                      }
7820                   }
7821                   // Static methods called from inside the _class
7822                   else if(currentClass && !id._class)
7823                   {
7824                      if(ResolveIdWithClass(exp, currentClass, true))
7825                         break;
7826                   }
7827                   symbol = FindSymbol(id.string, topContext.parent, globalContext, false, id._class && id._class.name == null);
7828                }
7829             }
7830
7831             // If we manage to resolve this symbol
7832             if(symbol)
7833             {
7834                Type type = symbol.type;
7835                Class _class = (type && type.kind == classType && type._class) ? type._class.registered : null;
7836
7837                if(_class && !strcmp(id.string, "this") && !type.classObjectType)
7838                {
7839                   Context context = SetupTemplatesContext(_class);
7840                   type = ReplaceThisClassType(_class);
7841                   FinishTemplatesContext(context);
7842                   if(type) type.refCount = 0;   // We'll be incrementing it right below...
7843                }
7844
7845                FreeSpecifier(id._class);
7846                id._class = null;
7847                delete id.string;
7848                id.string = CopyString(symbol.string);
7849
7850                id.classSym = null;
7851                exp.expType = type;
7852                if(type)
7853                   type.refCount++;
7854
7855                                                 // Commented this out, it was making non-constant enum parameters seen as constant
7856                                                 // enums should have been resolved by ResolveIdWithClass, changed to constantExp and marked as constant
7857                if(type && (type.kind == enumType /*|| (_class && _class.type == enumClass)*/))
7858                   // Add missing cases here... enum Classes...
7859                   exp.isConstant = true;
7860
7861                // TOCHECK: Why was !strcmp(id.string, "this") commented out?
7862                if(symbol.isParam || !strcmp(id.string, "this"))
7863                {
7864                   if(_class && _class.type == structClass && !type.declaredWithStruct)
7865                      exp.byReference = true;
7866
7867                   //TESTING COMMENTING THIS OUT IN FAVOR OF ApplyAnyObjectLogic
7868                   /*if(type && _class && (type.classObjectType == typedObject || type.classObjectType == anyObject) &&
7869                      ((_class.type == unitClass || _class.type == enumClass || _class.type == bitClass) ||
7870                      (type.byReference && (_class.type == normalClass || _class.type == noHeadClass))))
7871                   {
7872                      Identifier id = exp.identifier;
7873                      exp.type = bracketsExp;
7874                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(id)));
7875                   }*/
7876                }
7877
7878                if(symbol.isIterator)
7879                {
7880                   if(symbol.isIterator == 3)
7881                   {
7882                      exp.type = bracketsExp;
7883                      exp.list = MkListOne(MkExpOp(null, '*', MkExpIdentifier(exp.identifier)));
7884                      ((Expression)exp.list->first).op.exp2.expType = exp.expType;
7885                      exp.expType = null;
7886                      ProcessExpressionType(exp);
7887                   }
7888                   else if(symbol.isIterator != 4)
7889                   {
7890                      exp.type = memberExp;
7891                      exp.member.exp = MkExpIdentifier(exp.identifier);
7892                      exp.member.exp.expType = exp.expType;
7893                      /*if(symbol.isIterator == 6)
7894                         exp.member.member = MkIdentifier("key");
7895                      else*/
7896                         exp.member.member = MkIdentifier("data");
7897                      exp.expType = null;
7898                      ProcessExpressionType(exp);
7899                   }
7900                }
7901                break;
7902             }
7903             else
7904             {
7905                DefinedExpression definedExp = null;
7906                if(thisNameSpace && !(id._class && !id._class.name))
7907                {
7908                   char name[1024];
7909                   strcpy(name, thisNameSpace);
7910                   strcat(name, "::");
7911                   strcat(name, id.string);
7912                   definedExp = eSystem_FindDefine(privateModule, name);
7913                }
7914                if(!definedExp)
7915                   definedExp = eSystem_FindDefine(privateModule, id.string);
7916                if(definedExp)
7917                {
7918                   int c;
7919                   for(c = 0; c<definedExpStackPos; c++)
7920                      if(definedExpStack[c] == definedExp)
7921                         break;
7922                   if(c == definedExpStackPos && c < sizeof(definedExpStack) / sizeof(void *))
7923                   {
7924                      Location backupYylloc = yylloc;
7925                      File backInput = fileInput;
7926                      definedExpStack[definedExpStackPos++] = definedExp;
7927
7928                      fileInput = TempFile { };
7929                      fileInput.Write(definedExp.value, 1, strlen(definedExp.value));
7930                      fileInput.Seek(0, start);
7931
7932                      echoOn = false;
7933                      parsedExpression = null;
7934                      resetScanner();
7935                      expression_yyparse();
7936                      delete fileInput;
7937                      if(backInput)
7938                         fileInput = backInput;
7939
7940                      yylloc = backupYylloc;
7941
7942                      if(parsedExpression)
7943                      {
7944                         FreeIdentifier(id);
7945                         exp.type = bracketsExp;
7946                         exp.list = MkListOne(parsedExpression);
7947                         ApplyLocation(parsedExpression, yylloc);
7948                         ProcessExpressionType(exp);
7949                         definedExpStackPos--;
7950                         return;
7951                      }
7952                      definedExpStackPos--;
7953                   }
7954                   else
7955                   {
7956                      if(inCompiler)
7957                      {
7958                         Compiler_Error($"Recursion in defined expression %s\n", id.string);
7959                      }
7960                   }
7961                }
7962                else
7963                {
7964                   GlobalData data = null;
7965                   if(thisNameSpace && !(id._class && !id._class.name))
7966                   {
7967                      char name[1024];
7968                      strcpy(name, thisNameSpace);
7969                      strcat(name, "::");
7970                      strcat(name, id.string);
7971                      data = FindGlobalData(name);
7972                   }
7973                   if(!data)
7974                      data = FindGlobalData(id.string);
7975                   if(data)
7976                   {
7977                      DeclareGlobalData(curExternal, data);
7978                      exp.expType = data.dataType;
7979                      if(data.dataType) data.dataType.refCount++;
7980
7981                      delete id.string;
7982                      id.string = CopyString(data.fullName);
7983                      FreeSpecifier(id._class);
7984                      id._class = null;
7985
7986                      break;
7987                   }
7988                   else
7989                   {
7990                      GlobalFunction function = null;
7991                      if(thisNameSpace && !(id._class && !id._class.name))
7992                      {
7993                         char name[1024];
7994                         strcpy(name, thisNameSpace);
7995                         strcat(name, "::");
7996                         strcat(name, id.string);
7997                         function = eSystem_FindFunction(privateModule, name);
7998                      }
7999                      if(!function)
8000                         function = eSystem_FindFunction(privateModule, id.string);
8001                      if(function)
8002                      {
8003                         char name[1024];
8004                         delete id.string;
8005                         id.string = CopyString(function.name);
8006                         name[0] = 0;
8007
8008                         if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
8009                            strcpy(name, "__ecereFunction_");
8010                         FullClassNameCat(name, id.string, false); // Why is this using FullClassNameCat ?
8011                         if(DeclareFunction(curExternal, function, name))
8012                         {
8013                            delete id.string;
8014                            id.string = CopyString(name);
8015                         }
8016                         exp.expType = function.dataType;
8017                         if(function.dataType) function.dataType.refCount++;
8018
8019                         FreeSpecifier(id._class);
8020                         id._class = null;
8021
8022                         break;
8023                      }
8024                   }
8025                }
8026             }
8027          }
8028          unresolved = true;
8029          break;
8030       }
8031       case instanceExp:
8032       {
8033          // Class _class;
8034          // Symbol classSym;
8035
8036          if(!exp.instance._class)
8037          {
8038             if(exp.destType && exp.destType.kind == classType && exp.destType._class)
8039             {
8040                exp.instance._class = MkSpecifierName(exp.destType._class.string);
8041             }
8042          }
8043
8044          //classSym = FindClass(exp.instance._class.fullName);
8045          //_class = classSym ? classSym.registered : null;
8046
8047          ProcessInstantiationType(exp.instance);
8048
8049          exp.isConstant = exp.instance.isConstant;
8050
8051          /*
8052          if(_class.type == unitClass && _class.base.type != systemClass)
8053          {
8054             {
8055                Type destType = exp.destType;
8056
8057                exp.destType = MkClassType(_class.base.fullName);
8058                exp.expType = MkClassType(_class.fullName);
8059                CheckExpressionType(exp, exp.destType, true);
8060
8061                exp.destType = destType;
8062             }
8063             exp.expType = MkClassType(_class.fullName);
8064          }
8065          else*/
8066          if(exp.instance._class)
8067          {
8068             exp.expType = MkClassType(exp.instance._class.name);
8069             /*if(exp.expType._class && exp.expType._class.registered &&
8070                (exp.expType._class.registered.type == normalClass || exp.expType._class.registered.type == noHeadClass))
8071                exp.expType.byReference = true;*/
8072          }
8073          break;
8074       }
8075       case constantExp:
8076       {
8077          if(!exp.expType)
8078          {
8079             char * constant = exp.constant;
8080             Type type
8081             {
8082                refCount = 1;
8083                constant = true;
8084             };
8085             exp.expType = type;
8086
8087             if(constant[0] == '\'')
8088             {
8089                if((int)((byte *)constant)[1] > 127)
8090                {
8091                   int nb;
8092                   unichar ch = UTF8GetChar(constant + 1, &nb);
8093                   if(nb < 2) ch = constant[1];
8094                   delete constant;
8095                   exp.constant = PrintUInt(ch);
8096                   // type.kind = (ch > 0xFFFF) ? intType : shortType;
8097                   type.kind = classType; //(ch > 0xFFFF) ? intType : shortType;
8098                   type._class = FindClass("unichar");
8099
8100                   type.isSigned = false;
8101                }
8102                else
8103                {
8104                   type.kind = charType;
8105                   type.isSigned = true;
8106                }
8107             }
8108             else
8109             {
8110                char * dot = strchr(constant, '.');
8111                bool isHex = (constant[0] == '0' && (constant[1] == 'x' || constant[1] == 'X'));
8112                char * exponent;
8113                if(isHex)
8114                {
8115                   exponent = strchr(constant, 'p');
8116                   if(!exponent) exponent = strchr(constant, 'P');
8117                }
8118                else
8119                {
8120                   exponent = strchr(constant, 'e');
8121                   if(!exponent) exponent = strchr(constant, 'E');
8122                }
8123
8124                if(dot || exponent)
8125                {
8126                   if(strchr(constant, 'f') || strchr(constant, 'F'))
8127                      type.kind = floatType;
8128                   else
8129                      type.kind = doubleType;
8130                   type.isSigned = true;
8131                }
8132                else
8133                {
8134                   bool isSigned = constant[0] == '-';
8135                   char * endP = null;
8136                   int64 i64 = strtoll(constant, &endP, 0);
8137                   uint64 ui64 = strtoull(constant, &endP, 0);
8138                   bool is64Bit = endP && (!strcmp(endP, "LL") || !strcmp(endP, "ll") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8139                   bool forceUnsigned = endP && (!strcmp(endP, "U") || !strcmp(endP, "u") || !strcmp(endP, "LLU") || !strcmp(endP, "llu") || !strcmp(endP, "ull") || !strcmp(endP, "ULL"));
8140                   if(isSigned)
8141                   {
8142                      if(i64 < MININT)
8143                         is64Bit = true;
8144                   }
8145                   else
8146                   {
8147                      if(ui64 > MAXINT)
8148                      {
8149                         if(ui64 > MAXDWORD)
8150                         {
8151                            is64Bit = true;
8152                            if(ui64 <= MAXINT64 && (constant[0] != '0' || !constant[1]))
8153                               isSigned = true;
8154                         }
8155                      }
8156                      else if(constant[0] != '0' || !constant[1])
8157                         isSigned = true;
8158                   }
8159                   if(forceUnsigned)
8160                      isSigned = false;
8161                   type.kind = is64Bit ? int64Type : intType;
8162                   type.isSigned = isSigned;
8163                }
8164             }
8165             exp.isConstant = true;
8166             if(exp.destType && exp.destType.kind == doubleType)
8167                type.kind = doubleType;
8168             else if(exp.destType && exp.destType.kind == floatType)
8169                type.kind = floatType;
8170             else if(exp.destType && exp.destType.kind == int64Type)
8171                type.kind = int64Type;
8172          }
8173          break;
8174       }
8175       case stringExp:
8176       {
8177          exp.isConstant = true;      // Why wasn't this constant?
8178          exp.expType = Type
8179          {
8180             refCount = 1;
8181             kind = pointerType;
8182             type = Type
8183             {
8184                refCount = 1;
8185                kind = exp.wideString ? shortType : charType;
8186                constant = true;
8187                isSigned = exp.wideString ? false : true;
8188             }
8189          };
8190          break;
8191       }
8192       case newExp:
8193       case new0Exp:
8194          ProcessExpressionType(exp._new.size);
8195          exp.expType = Type
8196          {
8197             refCount = 1;
8198             kind = pointerType;
8199             type = ProcessType(exp._new.typeName.qualifiers, exp._new.typeName.declarator);
8200          };
8201          DeclareType(curExternal, exp.expType.type, true, false);
8202          break;
8203       case renewExp:
8204       case renew0Exp:
8205          ProcessExpressionType(exp._renew.size);
8206          ProcessExpressionType(exp._renew.exp);
8207          exp.expType = Type
8208          {
8209             refCount = 1;
8210             kind = pointerType;
8211             type = ProcessType(exp._renew.typeName.qualifiers, exp._renew.typeName.declarator);
8212          };
8213          DeclareType(curExternal, exp.expType.type, true, false);
8214          break;
8215       case opExp:
8216       {
8217          bool assign = false, boolResult = false, boolOps = false;
8218          Type type1 = null, type2 = null;
8219          bool useDestType = false, useSideType = false;
8220          Location oldyylloc = yylloc;
8221          bool useSideUnit = false;
8222          Class destClass = (exp.destType && exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
8223
8224          // Dummy type to prevent ProcessExpression of operands to say unresolved identifiers yet
8225          Type dummy
8226          {
8227             count = 1;
8228             refCount = 1;
8229          };
8230
8231          switch(exp.op.op)
8232          {
8233             // Assignment Operators
8234             case '=':
8235             case MUL_ASSIGN:
8236             case DIV_ASSIGN:
8237             case MOD_ASSIGN:
8238             case ADD_ASSIGN:
8239             case SUB_ASSIGN:
8240             case LEFT_ASSIGN:
8241             case RIGHT_ASSIGN:
8242             case AND_ASSIGN:
8243             case XOR_ASSIGN:
8244             case OR_ASSIGN:
8245                assign = true;
8246                break;
8247             // boolean Operators
8248             case '!':
8249                // Expect boolean operators
8250                //boolOps = true;
8251                //boolResult = true;
8252                break;
8253             case AND_OP:
8254             case OR_OP:
8255                // Expect boolean operands
8256                boolOps = true;
8257                boolResult = true;
8258                break;
8259             // Comparisons
8260             case EQ_OP:
8261             case '<':
8262             case '>':
8263             case LE_OP:
8264             case GE_OP:
8265             case NE_OP:
8266                // Gives boolean result
8267                boolResult = true;
8268                useSideType = true;
8269                break;
8270             case '+':
8271             case '-':
8272                useSideUnit = true;
8273                useSideType = true;
8274                useDestType = true;
8275                break;
8276
8277             case LEFT_OP:
8278             case RIGHT_OP:
8279                // useSideType = true;
8280                // useDestType = true;
8281                break;
8282
8283             case '|':
8284             case '^':
8285                useSideType = true;
8286                useDestType = true;
8287                break;
8288
8289             case '/':
8290             case '%':
8291                useSideType = true;
8292                useDestType = true;
8293                break;
8294             case '&':
8295             case '*':
8296                if(exp.op.exp1)
8297                {
8298                   // For & operator, useDestType nicely ensures the result will fit in a bool (TODO: Fix for generic enum)
8299                   useSideType = true;
8300                   useDestType = true;
8301                }
8302                break;
8303
8304             /*// Implement speed etc.
8305             case '*':
8306             case '/':
8307                break;
8308             */
8309          }
8310          if(exp.op.op == '&')
8311          {
8312             // Added this here earlier for Iterator address as key
8313             if(!exp.op.exp1 && exp.op.exp2 && exp.op.exp2.type == identifierExp && exp.op.exp2.identifier)
8314             {
8315                Identifier id = exp.op.exp2.identifier;
8316                Symbol symbol = FindSymbol(id.string, curContext, topContext, false, id._class && id._class.name == null);
8317                if(symbol && symbol.isIterator == 2)
8318                {
8319                   exp.type = memberExp;
8320                   exp.member.exp = exp.op.exp2;
8321                   exp.member.member = MkIdentifier("key");
8322                   exp.expType = null;
8323                   exp.op.exp2.expType = symbol.type;
8324                   symbol.type.refCount++;
8325                   ProcessExpressionType(exp);
8326                   FreeType(dummy);
8327                   break;
8328                }
8329                // exp.op.exp2.usage.usageRef = true;
8330             }
8331          }
8332
8333          //dummy.kind = TypeDummy;
8334          if(exp.op.exp1)
8335          {
8336             // Added this check here to use the dest type only for units derived from the base unit
8337             // So that untyped units will use the side unit as opposed to the untyped destination unit
8338             // This fixes (#771) sin(Degrees { 5 } + 5) to be equivalent to sin(Degrees { 10 }), since sin expects a generic Angle
8339             if(exp.op.exp2 && useSideUnit && useDestType && destClass && destClass.type == unitClass && destClass.base.type != unitClass)
8340                useDestType = false;
8341
8342             if(destClass && useDestType &&
8343               ((destClass.type == unitClass && useSideUnit) || destClass.type == enumClass || destClass.type == bitClass))
8344
8345               //(exp.destType._class.registered.type == unitClass || exp.destType._class.registered.type == enumClass) && useDestType)
8346             {
8347                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8348                exp.op.exp1.destType = exp.destType;
8349                exp.op.exp1.opDestType = true;
8350                if(exp.destType)
8351                   exp.destType.refCount++;
8352             }
8353             else if(!assign)
8354             {
8355                if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8356                exp.op.exp1.destType = dummy;
8357                dummy.refCount++;
8358             }
8359
8360             // TESTING THIS HERE...
8361             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count++;
8362                ProcessExpressionType(exp.op.exp1);
8363             if(exp.op.exp1.destType && exp.op.op != '=') exp.op.exp1.destType.count--;
8364
8365             exp.op.exp1.opDestType = false;
8366
8367             // Fix for unit and ++ / --
8368             if(!exp.op.exp2 && (exp.op.op == INC_OP || exp.op.op == DEC_OP) && exp.op.exp1.expType && exp.op.exp1.expType.kind == classType &&
8369                exp.op.exp1.expType._class && exp.op.exp1.expType._class.registered && exp.op.exp1.expType._class.registered.type == unitClass)
8370             {
8371                exp.op.exp2 = MkExpConstant("1");
8372                exp.op.op = exp.op.op == INC_OP ? ADD_ASSIGN : SUB_ASSIGN;
8373                assign = true;
8374             }
8375
8376             if(exp.op.exp1.destType == dummy)
8377             {
8378                FreeType(dummy);
8379                exp.op.exp1.destType = null;
8380             }
8381
8382             if(exp.op.exp2)
8383             {
8384                if(!assign && exp.op.exp1.expType && (exp.op.exp1.expType.kind == charType || exp.op.exp1.expType.kind == shortType))
8385                {
8386                   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 };
8387                   FreeType(exp.op.exp1.expType);
8388                   exp.op.exp1.expType = type;
8389                }
8390             }
8391
8392             type1 = exp.op.exp1.expType;
8393          }
8394
8395          if(exp.op.exp2)
8396          {
8397             char expString[10240];
8398             expString[0] = '\0';
8399             if(exp.op.exp2.type == instanceExp && !exp.op.exp2.instance._class)
8400             {
8401                if(exp.op.exp1)
8402                {
8403                   exp.op.exp2.destType = exp.op.exp1.expType;
8404                   if(exp.op.exp1.expType)
8405                      exp.op.exp1.expType.refCount++;
8406                }
8407                else
8408                {
8409                   exp.op.exp2.destType = exp.destType;
8410                   if(!exp.op.exp1 || (exp.op.op != '&' && exp.op.op != '^'))
8411                      exp.op.exp2.opDestType = true;
8412                   if(exp.destType)
8413                      exp.destType.refCount++;
8414                }
8415
8416                if(type1) type1.refCount++;
8417                exp.expType = type1;
8418             }
8419             else if(assign)
8420             {
8421                if(inCompiler)
8422                   PrintExpression(exp.op.exp2, expString);
8423
8424                if(type1 && type1.kind == pointerType)
8425                {
8426                   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 ||
8427                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN)
8428                      Compiler_Error($"operator %s illegal on pointer\n", exp.op.op);
8429                   else if(exp.op.op == '=')
8430                   {
8431                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8432                      exp.op.exp2.destType = type1;
8433                      if(type1)
8434                         type1.refCount++;
8435                   }
8436                }
8437                else
8438                {
8439                   // Don't convert to the type for those... (e.g.: Degrees a; a /= 2;)
8440                   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/* ||
8441                      exp.op.op == AND_ASSIGN || exp.op.op == OR_ASSIGN*/);
8442                   else
8443                   {
8444                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8445                      exp.op.exp2.destType = type1;
8446                      if(type1)
8447                         type1.refCount++;
8448                   }
8449                }
8450                if(type1) type1.refCount++;
8451                exp.expType = type1;
8452             }
8453             else if(destClass &&
8454                   ((destClass.type == unitClass && useDestType && useSideUnit) ||
8455                   (destClass.type == enumClass && useDestType)))
8456             {
8457                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8458                exp.op.exp2.destType = exp.destType;
8459                if(exp.op.op != '&' && exp.op.op != '^')
8460                   exp.op.exp2.opDestType = true;
8461                if(exp.destType)
8462                   exp.destType.refCount++;
8463             }
8464             else
8465             {
8466                if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8467                exp.op.exp2.destType = dummy;
8468                dummy.refCount++;
8469             }
8470
8471             // TESTING THIS HERE... (DANGEROUS)
8472             if(type1 && boolResult && useSideType && type1.kind == classType && type1._class && type1._class.registered &&
8473                (type1._class.registered.type == bitClass || type1._class.registered.type == enumClass))
8474             {
8475                FreeType(exp.op.exp2.destType);
8476                exp.op.exp2.destType = type1;
8477                type1.refCount++;
8478             }
8479             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count++;
8480             // Cannot lose the cast on a sizeof
8481             if(exp.op.op == SIZEOF)
8482             {
8483                Expression e = exp.op.exp2;
8484                while((e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp) && e.list)
8485                {
8486                   if(e.type == bracketsExp || e.type == extensionExpressionExp || e.type == extensionCompoundExp)
8487                   {
8488                      if(e.type == extensionCompoundExp)
8489                         e = ((Statement)e.compound.compound.statements->last).expressions->last;
8490                      else
8491                         e = e.list->last;
8492                   }
8493                }
8494                if(e.type == castExp && e.cast.exp)
8495                   e.cast.exp.needCast = true;
8496             }
8497             ProcessExpressionType(exp.op.exp2);
8498             exp.op.exp2.opDestType = false;
8499             if(exp.op.exp2.destType && exp.op.op != '=') exp.op.exp2.destType.count--;
8500
8501             if(!assign && (exp.op.exp1 || exp.op.op == '~'))
8502             {
8503                if(exp.op.exp2.expType && (exp.op.exp2.expType.kind == charType || exp.op.exp2.expType.kind == shortType))
8504                {
8505                   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 };
8506                   FreeType(exp.op.exp2.expType);
8507                   exp.op.exp2.expType = type;
8508                }
8509             }
8510
8511             if(assign && type1 && type1.kind == pointerType && exp.op.exp2.expType)
8512             {
8513                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)
8514                {
8515                   if(exp.op.op != '=' && type1.type.kind == voidType)
8516                      Compiler_Error($"void *: unknown size\n");
8517                }
8518                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||
8519                            (type1.type.kind == voidType && exp.op.exp2.expType.kind == classType && exp.op.exp2.expType._class.registered &&
8520                               (exp.op.exp2.expType._class.registered.type == normalClass ||
8521                               exp.op.exp2.expType._class.registered.type == structClass ||
8522                               exp.op.exp2.expType._class.registered.type == noHeadClass)))
8523                {
8524                   if(exp.op.op == ADD_ASSIGN)
8525                      Compiler_Error($"cannot add two pointers\n");
8526                }
8527                else if((exp.op.exp2.expType.kind == classType && type1.kind == pointerType && type1.type.kind == classType &&
8528                   type1.type._class == exp.op.exp2.expType._class && exp.op.exp2.expType._class.registered && exp.op.exp2.expType._class.registered.type == structClass))
8529                {
8530                   if(exp.op.op == ADD_ASSIGN)
8531                      Compiler_Error($"cannot add two pointers\n");
8532                }
8533                else if(inCompiler)
8534                {
8535                   char type1String[1024];
8536                   char type2String[1024];
8537                   type1String[0] = '\0';
8538                   type2String[0] = '\0';
8539
8540                   PrintType(exp.op.exp2.expType, type1String, false, true);
8541                   PrintType(type1, type2String, false, true);
8542                   ChangeCh(expString, '\n', ' ');
8543                   Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1String, type2String);
8544                }
8545             }
8546
8547             if(exp.op.exp2.destType == dummy)
8548             {
8549                FreeType(dummy);
8550                exp.op.exp2.destType = null;
8551             }
8552
8553             if(exp.op.op == '-' && !exp.op.exp1 && exp.op.exp2.expType && !exp.op.exp2.expType.isSigned)
8554             {
8555                type2 = { };
8556                type2.refCount = 1;
8557                CopyTypeInto(type2, exp.op.exp2.expType);
8558                type2.isSigned = true;
8559             }
8560             else if(exp.op.op == '~' && !exp.op.exp1 && exp.op.exp2.expType && (!exp.op.exp2.expType.isSigned || exp.op.exp2.expType.kind != intType))
8561             {
8562                type2 = { kind = intType };
8563                type2.refCount = 1;
8564                type2.isSigned = true;
8565             }
8566             else
8567             {
8568                type2 = exp.op.exp2.expType;
8569                if(type2) type2.refCount++;
8570             }
8571          }
8572
8573          dummy.kind = voidType;
8574
8575          if(exp.op.op == SIZEOF)
8576          {
8577             exp.expType = Type
8578             {
8579                refCount = 1;
8580                kind = intSizeType;
8581             };
8582             exp.isConstant = true;
8583          }
8584          // Get type of dereferenced pointer
8585          else if(exp.op.op == '*' && !exp.op.exp1)
8586          {
8587             exp.expType = Dereference(type2);
8588             if(type2 && type2.kind == classType)
8589                notByReference = true;
8590          }
8591          else if(exp.op.op == '&' && !exp.op.exp1)
8592             exp.expType = Reference(type2);
8593          else if(exp.op.op == LEFT_OP || exp.op.op == RIGHT_OP)
8594          {
8595             if(exp.op.exp1.expType)
8596             {
8597                exp.expType = exp.op.exp1.expType;
8598                exp.expType.refCount++;
8599             }
8600          }
8601          else if(!assign)
8602          {
8603             if(boolOps)
8604             {
8605                if(exp.op.exp1)
8606                {
8607                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8608                   exp.op.exp1.destType = MkClassType("bool");
8609                   exp.op.exp1.destType.truth = true;
8610                   if(!exp.op.exp1.expType)
8611                      ProcessExpressionType(exp.op.exp1);
8612                   else
8613                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8614                   FreeType(exp.op.exp1.expType);
8615                   exp.op.exp1.expType = MkClassType("bool");
8616                   exp.op.exp1.expType.truth = true;
8617                }
8618                if(exp.op.exp2)
8619                {
8620                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8621                   exp.op.exp2.destType = MkClassType("bool");
8622                   exp.op.exp2.destType.truth = true;
8623                   if(!exp.op.exp2.expType)
8624                      ProcessExpressionType(exp.op.exp2);
8625                   else
8626                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8627                   FreeType(exp.op.exp2.expType);
8628                   exp.op.exp2.expType = MkClassType("bool");
8629                   exp.op.exp2.expType.truth = true;
8630                }
8631             }
8632             else if(exp.op.exp1 && exp.op.exp2 &&
8633                ((useSideType /*&&
8634                      (useSideUnit ||
8635                         ((!type1 || type1.kind != classType || type1._class.registered.type != unitClass) &&
8636                          (!type2 || type2.kind != classType || type2._class.registered.type != unitClass)))*/) ||
8637                   ((!type1 || type1.kind != classType || !strcmp(type1._class.string, "String")) &&
8638                   (!type2 || type2.kind != classType || !strcmp(type2._class.string, "String")))))
8639             {
8640                if(type1 && type2 &&
8641                   // If either both are class or both are not class
8642                   ((type1.kind == classType && type1._class && strcmp(type1._class.string, "String")) == (type2.kind == classType && type2._class && strcmp(type2._class.string, "String"))))
8643                {
8644                   // Added this check for enum subtraction to result in an int type:
8645                   if(exp.op.op == '-' &&
8646                      ((type1.kind == classType && type1._class.registered && type1._class.registered.type == enumClass) ||
8647                       (type2.kind == classType && type2._class.registered && type2._class.registered.type == enumClass)) )
8648                   {
8649                      Type intType;
8650                      if(!type1._class.registered.dataType)
8651                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8652                      if(!type2._class.registered.dataType)
8653                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8654
8655                      intType = ProcessTypeString(
8656                         (type1._class.registered.dataType.kind == int64Type || type2._class.registered.dataType.kind == int64Type) ? "int64" : "int", false);
8657
8658                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8659                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8660                      exp.op.exp1.destType = intType;
8661                      exp.op.exp2.destType = intType;
8662                      intType.refCount++;
8663                   }
8664                   else
8665                   {
8666                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8667                      exp.op.exp2.destType = type1;
8668                      type1.refCount++;
8669                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8670                      exp.op.exp1.destType = type2;
8671                      type2.refCount++;
8672                   }
8673
8674                   // Warning here for adding Radians + Degrees with no destination type
8675                   if(!boolResult && type1.kind == classType && (!exp.destType || exp.destType.kind != classType) &&
8676                      type1._class.registered && type1._class.registered.type == unitClass &&
8677                      type2._class.registered && type2._class.registered.type == unitClass &&
8678                      type1._class.registered != type2._class.registered)
8679                      Compiler_Warning($"operating on %s and %s with an untyped result, assuming %s\n",
8680                         type1._class.string, type2._class.string, type1._class.string);
8681
8682                   if(type1.kind == pointerType && type1.type.kind == templateType && type2.kind != pointerType)
8683                   {
8684                      Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8685                      if(argExp)
8686                      {
8687                         Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8688
8689                         exp.op.exp1 = MkExpBrackets(MkListOne(MkExpCast(
8690                            MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
8691                            exp.op.exp1)));
8692
8693                         ProcessExpressionType(exp.op.exp1);
8694
8695                         if(type2.kind != pointerType)
8696                         {
8697                            ProcessExpressionType(classExp);
8698
8699                            exp.op.exp2 = MkExpBrackets(MkListOne(MkExpOp(exp.op.exp2, '*', MkExpMember(classExp, MkIdentifier("typeSize")) )));
8700
8701                            if(!exp.op.exp2.expType)
8702                            {
8703                               if(type2)
8704                                  FreeType(type2);
8705                               type2 = exp.op.exp2.expType = ProcessTypeString("int", false);
8706                               type2.refCount++;
8707                            }
8708
8709                            ProcessExpressionType(exp.op.exp2);
8710                         }
8711                      }
8712                   }
8713
8714                   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)))
8715                   {
8716                      if(type1.kind != classType && type1.type.kind == voidType)
8717                         Compiler_Error($"void *: unknown size\n");
8718                      exp.expType = type1;
8719                      if(type1) type1.refCount++;
8720                   }
8721                   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)))
8722                   {
8723                      if(type2.kind != classType && type2.type.kind == voidType)
8724                         Compiler_Error($"void *: unknown size\n");
8725                      exp.expType = type2;
8726                      if(type2) type2.refCount++;
8727                   }
8728                   else if((type1.kind == pointerType && type2.kind != pointerType && type2.kind != arrayType && type2.kind != functionType && type2.kind != methodType && type2.kind != classType && type2.kind != subClassType) ||
8729                           (type2.kind == pointerType && type1.kind != pointerType && type1.kind != arrayType && type1.kind != functionType && type1.kind != methodType && type1.kind != classType && type1.kind != subClassType))
8730                   {
8731                      Compiler_Warning($"different levels of indirection\n");
8732                   }
8733                   else
8734                   {
8735                      bool success = false;
8736                      if(type1.kind == pointerType && type2.kind == pointerType)
8737                      {
8738                         if(exp.op.op == '+')
8739                            Compiler_Error($"cannot add two pointers\n");
8740                         else if(exp.op.op == '-')
8741                         {
8742                            // Pointer Subtraction gives integer
8743                            if(MatchTypes(type1.type, type2.type, null, null, null, false, false, false, false, false))
8744                            {
8745                               exp.expType = Type
8746                               {
8747                                  kind = intType;
8748                                  refCount = 1;
8749                               };
8750                               success = true;
8751
8752                               if(type1.type.kind == templateType)
8753                               {
8754                                  Expression argExp = GetTemplateArgExp(type1.type.templateParameter, thisClass, true);
8755                                  if(argExp)
8756                                  {
8757                                     Expression classExp = MkExpMember(argExp, MkIdentifier("dataTypeClass"));
8758
8759                                     ProcessExpressionType(classExp);
8760
8761                                     exp.type = bracketsExp;
8762                                     exp.list = MkListOne(MkExpOp(
8763                                        MkExpBrackets(MkListOne(MkExpOp(
8764                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp1)))
8765                                              , exp.op.op,
8766                                              MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpBrackets(MkListOne(exp.op.exp2)))))), '/',
8767                                              MkExpMember(classExp, MkIdentifier("typeSize"))));
8768
8769                                     ProcessExpressionType(((Expression)exp.list->first).op.exp2);
8770                                     FreeType(dummy);
8771                                     return;
8772                                  }
8773                               }
8774                            }
8775                         }
8776                      }
8777
8778                      if(!success && exp.op.exp1.type == constantExp)
8779                      {
8780                         // If first expression is constant, try to match that first
8781                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8782                         {
8783                            if(exp.expType) FreeType(exp.expType);
8784                            exp.expType = exp.op.exp1.destType;
8785                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8786                            success = true;
8787                         }
8788                         else if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8789                         {
8790                            if(exp.expType) FreeType(exp.expType);
8791                            exp.expType = exp.op.exp2.destType;
8792                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8793                            success = true;
8794                         }
8795                      }
8796                      else if(!success)
8797                      {
8798                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
8799                         {
8800                            if(exp.expType) FreeType(exp.expType);
8801                            exp.expType = exp.op.exp2.destType;
8802                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
8803                            success = true;
8804                         }
8805                         else if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8806                         {
8807                            if(exp.expType) FreeType(exp.expType);
8808                            exp.expType = exp.op.exp1.destType;
8809                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8810                            success = true;
8811                         }
8812                      }
8813                      if(!success)
8814                      {
8815                         char expString1[10240];
8816                         char expString2[10240];
8817                         char type1[1024];
8818                         char type2[1024];
8819                         expString1[0] = '\0';
8820                         expString2[0] = '\0';
8821                         type1[0] = '\0';
8822                         type2[0] = '\0';
8823                         if(inCompiler)
8824                         {
8825                            PrintExpression(exp.op.exp1, expString1);
8826                            ChangeCh(expString1, '\n', ' ');
8827                            PrintExpression(exp.op.exp2, expString2);
8828                            ChangeCh(expString2, '\n', ' ');
8829                            PrintType(exp.op.exp1.expType, type1, false, true);
8830                            PrintType(exp.op.exp2.expType, type2, false, true);
8831                         }
8832
8833                         Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1, expString2, type2);
8834                      }
8835                   }
8836                }
8837                // ADDED THESE TWO FROM OUTSIDE useSideType CHECK
8838                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type2 && type1 && type2.kind == classType && type1.kind != classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
8839                {
8840                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8841                   // Convert e.g. / 4 into / 4.0
8842                   exp.op.exp1.destType = type2._class.registered.dataType;
8843                   if(type2._class.registered.dataType)
8844                      type2._class.registered.dataType.refCount++;
8845                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8846                   exp.expType = type2;
8847                   if(type2) type2.refCount++;
8848                }
8849                else if(!boolResult && (!useSideUnit /*|| exp.destType*/) && type1 && type2 && type1.kind == classType && type2.kind != classType && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
8850                {
8851                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8852                   // Convert e.g. / 4 into / 4.0
8853                   exp.op.exp2.destType = type1._class.registered.dataType;
8854                   if(type1._class.registered.dataType)
8855                      type1._class.registered.dataType.refCount++;
8856                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8857                   exp.expType = type1;
8858                   if(type1) type1.refCount++;
8859                }
8860                else if(type1)
8861                {
8862                   bool valid = false;
8863
8864                   if(!boolResult && useSideUnit && type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
8865                   {
8866                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8867
8868                      if(!type1._class.registered.dataType)
8869                         type1._class.registered.dataType = ProcessTypeString(type1._class.registered.dataTypeString, false);
8870                      exp.op.exp2.destType = type1._class.registered.dataType;
8871                      exp.op.exp2.destType.refCount++;
8872
8873                      CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
8874                      if(type2)
8875                         FreeType(type2);
8876                      type2 = exp.op.exp2.destType;
8877                      if(type2) type2.refCount++;
8878
8879                      exp.expType = type2;
8880                      type2.refCount++;
8881                   }
8882
8883                   if(!boolResult && useSideUnit && type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8884                   {
8885                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8886
8887                      if(!type2._class.registered.dataType)
8888                         type2._class.registered.dataType = ProcessTypeString(type2._class.registered.dataTypeString, false);
8889                      exp.op.exp1.destType = type2._class.registered.dataType;
8890                      exp.op.exp1.destType.refCount++;
8891
8892                      CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
8893                      type1 = exp.op.exp1.destType;
8894                      exp.expType = type1;
8895                      type1.refCount++;
8896                   }
8897
8898                   // TESTING THIS NEW CODE
8899                   if(!boolResult || exp.op.op == '>' || exp.op.op == '<' || exp.op.op == GE_OP || exp.op.op == LE_OP)
8900                   {
8901                      bool op1IsEnum = type1 && type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass;
8902                      bool op2IsEnum = type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass;
8903                      if(exp.op.op == '*' || exp.op.op == '/' || exp.op.op == '-' || exp.op.op == '|' || exp.op.op == '^')
8904                      {
8905                         // Convert the enum to an int instead for these operators
8906                         if(op1IsEnum && exp.op.exp2.expType)
8907                         {
8908                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8909                            {
8910                               if(exp.expType) FreeType(exp.expType);
8911                               exp.expType = exp.op.exp2.expType;
8912                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8913                               valid = true;
8914                            }
8915                         }
8916                         else if(op2IsEnum && exp.op.exp1.expType)
8917                         {
8918                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8919                            {
8920                               if(exp.expType) FreeType(exp.expType);
8921                               exp.expType = exp.op.exp1.expType;
8922                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8923                               valid = true;
8924                            }
8925                         }
8926                      }
8927                      else
8928                      {
8929                         if(op1IsEnum && exp.op.exp2.expType)
8930                         {
8931                            if(CheckExpressionType(exp.op.exp1, exp.op.exp2.expType, false, false))
8932                            {
8933                               if(exp.expType) FreeType(exp.expType);
8934                               exp.expType = exp.op.exp1.expType;
8935                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
8936                               valid = true;
8937                            }
8938                         }
8939                         else if(op2IsEnum && exp.op.exp1.expType)
8940                         {
8941                            if(CheckExpressionType(exp.op.exp2, exp.op.exp1.expType, false, false))
8942                            {
8943                               if(exp.expType) FreeType(exp.expType);
8944                               exp.expType = exp.op.exp2.expType;
8945                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
8946                               valid = true;
8947                            }
8948                         }
8949                      }
8950                   }
8951
8952                   if(!valid)
8953                   {
8954                      // 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
8955                      if(type2 && type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == unitClass &&
8956                         (type1.kind != classType || !type1._class || !type1._class.registered || type1._class.registered.type != unitClass))
8957                      {
8958                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
8959                         exp.op.exp1.destType = type2;
8960                         type2.refCount++;
8961
8962                         if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
8963                         {
8964                            if(exp.expType) FreeType(exp.expType);
8965                            exp.expType = exp.op.exp1.destType;
8966                            if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
8967                         }
8968                      }
8969                      else
8970                      {
8971                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8972                         exp.op.exp2.destType = type1;
8973                         type1.refCount++;
8974
8975                      /*
8976                      // Maybe this was meant to be an enum...
8977                      if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
8978                      {
8979                         Type oldType = exp.op.exp2.expType;
8980                         exp.op.exp2.expType = null;
8981                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false))
8982                            FreeType(oldType);
8983                         else
8984                            exp.op.exp2.expType = oldType;
8985                      }
8986                      */
8987
8988                      /*
8989                      // TESTING THIS HERE... LATEST ADDITION
8990                      if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
8991                      {
8992                         if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
8993                         exp.op.exp2.destType = type2._class.registered.dataType;
8994                         if(type2._class.registered.dataType)
8995                            type2._class.registered.dataType.refCount++;
8996                         CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false);
8997
8998                         //exp.expType = type2._class.registered.dataType; //type2;
8999                         //if(type2) type2.refCount++;
9000                      }
9001
9002                      // TESTING THIS HERE... LATEST ADDITION
9003                      if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9004                      {
9005                         if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9006                         exp.op.exp1.destType = type1._class.registered.dataType;
9007                         if(type1._class.registered.dataType)
9008                            type1._class.registered.dataType.refCount++;
9009                         CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false);
9010                         exp.expType = type1._class.registered.dataType; //type1;
9011                         if(type1) type1.refCount++;
9012                      }
9013                      */
9014
9015                         if(CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false))
9016                         {
9017                            if(exp.expType) FreeType(exp.expType);
9018                            exp.expType = exp.op.exp2.destType;
9019                            if(exp.op.exp2.destType) exp.op.exp2.destType.refCount++;
9020                         }
9021                         else if(type1 && type2)
9022                         {
9023                            char expString1[10240];
9024                            char expString2[10240];
9025                            char type1String[1024];
9026                            char type2String[1024];
9027                            expString1[0] = '\0';
9028                            expString2[0] = '\0';
9029                            type1String[0] = '\0';
9030                            type2String[0] = '\0';
9031                            if(inCompiler)
9032                            {
9033                               PrintExpression(exp.op.exp1, expString1);
9034                               ChangeCh(expString1, '\n', ' ');
9035                               PrintExpression(exp.op.exp2, expString2);
9036                               ChangeCh(expString2, '\n', ' ');
9037                               PrintType(exp.op.exp1.expType, type1String, false, true);
9038                               PrintType(exp.op.exp2.expType, type2String, false, true);
9039                            }
9040
9041                            Compiler_Warning($"incompatible expressions %s (%s) and %s (%s)\n", expString1, type1String, expString2, type2String);
9042
9043                            if(type1.kind == classType && type1._class && type1._class.registered && type1._class.registered.type == enumClass)
9044                            {
9045                               exp.expType = exp.op.exp1.expType;
9046                               if(exp.op.exp1.expType) exp.op.exp1.expType.refCount++;
9047                            }
9048                            else if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9049                            {
9050                               exp.expType = exp.op.exp2.expType;
9051                               if(exp.op.exp2.expType) exp.op.exp2.expType.refCount++;
9052                            }
9053                         }
9054                      }
9055                   }
9056                }
9057                else if(type2)
9058                {
9059                   // Maybe this was meant to be an enum...
9060                   if(type2.kind == classType && type2._class && type2._class.registered && type2._class.registered.type == enumClass)
9061                   {
9062                      Type oldType = exp.op.exp1.expType;
9063                      exp.op.exp1.expType = null;
9064                      if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9065                         FreeType(oldType);
9066                      else
9067                         exp.op.exp1.expType = oldType;
9068                   }
9069
9070                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9071                   exp.op.exp1.destType = type2;
9072                   type2.refCount++;
9073                   /*
9074                   // TESTING THIS HERE... LATEST ADDITION
9075                   if(type1 && type1.kind == classType && type1._class.registered && type1._class.registered.type == unitClass && type2 && type2.kind != classType)
9076                   {
9077                      if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9078                      exp.op.exp1.destType = type1._class.registered.dataType;
9079                      if(type1._class.registered.dataType)
9080                         type1._class.registered.dataType.refCount++;
9081                   }
9082
9083                   // TESTING THIS HERE... LATEST ADDITION
9084                   if(type2 && type2.kind == classType && type2._class.registered && type2._class.registered.type == unitClass && type1 && type1.kind != classType)
9085                   {
9086                      if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9087                      exp.op.exp2.destType = type2._class.registered.dataType;
9088                      if(type2._class.registered.dataType)
9089                         type2._class.registered.dataType.refCount++;
9090                   }
9091                   */
9092
9093                   if(CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false))
9094                   {
9095                      if(exp.expType) FreeType(exp.expType);
9096                      exp.expType = exp.op.exp1.destType;
9097                      if(exp.op.exp1.destType) exp.op.exp1.destType.refCount++;
9098                   }
9099                }
9100             }
9101             else if(type2 && (!type1 || (type2.kind == classType && type1.kind != classType)))
9102             {
9103                if(type1 && type2._class && type2._class.registered && type2._class.registered.type == unitClass)
9104                {
9105                   if(exp.op.exp1.destType) FreeType(exp.op.exp1.destType);
9106                   // Convert e.g. / 4 into / 4.0
9107                   exp.op.exp1.destType = type2._class.registered.dataType;
9108                   if(type2._class.registered.dataType)
9109                      type2._class.registered.dataType.refCount++;
9110                   CheckExpressionType(exp.op.exp1, exp.op.exp1.destType, false, false);
9111                }
9112                if(exp.op.op == '!')
9113                {
9114                   exp.expType = MkClassType("bool");
9115                   exp.expType.truth = true;
9116                }
9117                else
9118                {
9119                   exp.expType = type2;
9120                   if(type2) type2.refCount++;
9121                }
9122             }
9123             else if(type1 && (!type2 || (type1.kind == classType && type2.kind != classType)))
9124             {
9125                if(type2 && type1._class && type1._class.registered && type1._class.registered.type == unitClass)
9126                {
9127                   if(exp.op.exp2.destType) FreeType(exp.op.exp2.destType);
9128                   // Convert e.g. / 4 into / 4.0
9129                   exp.op.exp2.destType = type1._class.registered.dataType;
9130                   if(type1._class.registered.dataType)
9131                      type1._class.registered.dataType.refCount++;
9132                   CheckExpressionType(exp.op.exp2, exp.op.exp2.destType, false, false);
9133                }
9134                exp.expType = type1;
9135                if(type1) type1.refCount++;
9136             }
9137          }
9138
9139          yylloc = exp.loc;
9140          if(exp.op.exp1 && !exp.op.exp1.expType)
9141          {
9142             char expString[10000];
9143             expString[0] = '\0';
9144             if(inCompiler)
9145             {
9146                PrintExpression(exp.op.exp1, expString);
9147                ChangeCh(expString, '\n', ' ');
9148             }
9149             if(expString[0])
9150                Compiler_Error($"couldn't determine type of %s\n", expString);
9151          }
9152          if(exp.op.exp2 && !exp.op.exp2.expType)
9153          {
9154             char expString[10240];
9155             expString[0] = '\0';
9156             if(inCompiler)
9157             {
9158                PrintExpression(exp.op.exp2, expString);
9159                ChangeCh(expString, '\n', ' ');
9160             }
9161             if(expString[0])
9162                Compiler_Error($"couldn't determine type of %s\n", expString);
9163          }
9164
9165          if(boolResult)
9166          {
9167             FreeType(exp.expType);
9168             exp.expType = MkClassType("bool");
9169             exp.expType.truth = true;
9170          }
9171
9172          if(exp.op.op != SIZEOF)
9173             exp.isConstant = (!exp.op.exp1 || exp.op.exp1.isConstant) &&
9174                (!exp.op.exp2 || exp.op.exp2.isConstant);
9175
9176          if(exp.op.op == SIZEOF && exp.op.exp2.expType)
9177          {
9178             DeclareType(curExternal, exp.op.exp2.expType, true, false);
9179          }
9180
9181          if(exp.op.op == DELETE && exp.op.exp2 && exp.op.exp2.expType && exp.op.exp2.expType.specConst)
9182             Compiler_Warning($"deleting const qualified object\n");
9183
9184          yylloc = oldyylloc;
9185
9186          FreeType(dummy);
9187          if(type2)
9188             FreeType(type2);
9189          break;
9190       }
9191       case bracketsExp:
9192       case extensionExpressionExp:
9193       {
9194          Expression e;
9195          exp.isConstant = true;
9196          for(e = exp.list->first; e; e = e.next)
9197          {
9198             //bool inced = false;
9199             if(!e.next)
9200             {
9201                FreeType(e.destType);
9202                e.opDestType = exp.opDestType;
9203                e.destType = exp.destType;
9204                if(e.destType) { exp.destType.refCount++; /*e.destType.count++; inced = true;*/ }
9205             }
9206             ProcessExpressionType(e);
9207             /*if(inced)
9208                exp.destType.count--;*/
9209             if(!exp.expType && !e.next)
9210             {
9211                exp.expType = e.expType;
9212                if(e.expType) e.expType.refCount++;
9213             }
9214             if(!e.isConstant)
9215                exp.isConstant = false;
9216          }
9217
9218          // In case a cast became a member...
9219          e = exp.list->first;
9220          if(!e.next && e.type == memberExp)
9221          {
9222             // Preserve prev, next
9223             Expression next = exp.next, prev = exp.prev;
9224
9225
9226             FreeType(exp.expType);
9227             FreeType(exp.destType);
9228             delete exp.list;
9229
9230             *exp = *e;
9231
9232             exp.prev = prev;
9233             exp.next = next;
9234
9235             delete e;
9236
9237             ProcessExpressionType(exp);
9238          }
9239          break;
9240       }
9241       case indexExp:
9242       {
9243          Expression e;
9244          exp.isConstant = true;
9245
9246          ProcessExpressionType(exp.index.exp);
9247          if(!exp.index.exp.isConstant)
9248             exp.isConstant = false;
9249
9250          if(exp.index.exp.expType)
9251          {
9252             Type source = exp.index.exp.expType;
9253             if(source.kind == classType && source._class && source._class.registered)
9254             {
9255                Class _class = source._class.registered;
9256                Class c = _class.templateClass ? _class.templateClass : _class;
9257                if(_class != containerClass && eClass_IsDerived(c, containerClass) && _class.templateArgs)
9258                {
9259                   exp.expType = ProcessTypeString(_class.templateArgs[2].dataTypeString, false);
9260
9261                   if(exp.index.index && exp.index.index->last)
9262                   {
9263                      Type type = ProcessTypeString(_class.templateArgs[1].dataTypeString, false);
9264
9265                      if(type.kind == classType) type.constant = true;
9266                      else if(type.kind == pointerType)
9267                      {
9268                         Type t = type;
9269                         while(t.kind == pointerType) t = t.type;
9270                         t.constant = true;
9271                      }
9272
9273                      ((Expression)exp.index.index->last).destType = type;
9274                   }
9275                }
9276             }
9277          }
9278
9279          for(e = exp.index.index->first; e; e = e.next)
9280          {
9281             if(!e.next && exp.index.exp.expType && exp.index.exp.expType.kind == arrayType && exp.index.exp.expType.enumClass)
9282             {
9283                if(e.destType) FreeType(e.destType);
9284                e.destType = MkClassType(exp.index.exp.expType.enumClass.string);
9285             }
9286             ProcessExpressionType(e);
9287             if(!e.next)
9288             {
9289                // Check if this type is int
9290             }
9291             if(!e.isConstant)
9292                exp.isConstant = false;
9293          }
9294
9295          if(!exp.expType)
9296             exp.expType = Dereference(exp.index.exp.expType);
9297          if(exp.expType)
9298             DeclareType(curExternal, exp.expType, true, false);
9299          break;
9300       }
9301       case callExp:
9302       {
9303          Expression e;
9304          Type functionType;
9305          Type methodType = null;
9306          char name[1024];
9307          name[0] = '\0';
9308
9309          if(inCompiler)
9310          {
9311             PrintExpression(exp.call.exp,  name);
9312             if(exp.call.exp.expType && !exp.call.exp.expType.returnType)
9313             {
9314                //exp.call.exp.expType = null;
9315                PrintExpression(exp.call.exp,  name);
9316             }
9317          }
9318          if(exp.call.exp.type == identifierExp)
9319          {
9320             Expression idExp = exp.call.exp;
9321             Identifier id = idExp.identifier;
9322             if(!strcmp(id.string, "__builtin_frame_address"))
9323             {
9324                exp.expType = ProcessTypeString("void *", true);
9325                if(exp.call.arguments && exp.call.arguments->first)
9326                   ProcessExpressionType(exp.call.arguments->first);
9327                break;
9328             }
9329             else if(!strcmp(id.string, "__ENDIAN_PAD"))
9330             {
9331                exp.expType = ProcessTypeString("int", true);
9332                if(exp.call.arguments && exp.call.arguments->first)
9333                   ProcessExpressionType(exp.call.arguments->first);
9334                break;
9335             }
9336             else if(!strcmp(id.string, "Max") ||
9337                !strcmp(id.string, "Min") ||
9338                !strcmp(id.string, "Sgn") ||
9339                !strcmp(id.string, "Abs"))
9340             {
9341                Expression a = null;
9342                Expression b = null;
9343                Expression tempExp1 = null, tempExp2 = null;
9344                if((!strcmp(id.string, "Max") ||
9345                   !strcmp(id.string, "Min")) && exp.call.arguments->count == 2)
9346                {
9347                   a = exp.call.arguments->first;
9348                   b = exp.call.arguments->last;
9349                   tempExp1 = a;
9350                   tempExp2 = b;
9351                }
9352                else if(exp.call.arguments->count == 1)
9353                {
9354                   a = exp.call.arguments->first;
9355                   tempExp1 = a;
9356                }
9357
9358                if(a)
9359                {
9360                   exp.call.arguments->Clear();
9361                   idExp.identifier = null;
9362
9363                   FreeExpContents(exp);
9364
9365                   ProcessExpressionType(a);
9366                   if(b)
9367                      ProcessExpressionType(b);
9368
9369                   exp.type = bracketsExp;
9370                   exp.list = MkList();
9371
9372                   if(a.expType && (!b || b.expType))
9373                   {
9374                      if((!a.isConstant && a.type != identifierExp) || (b && !b.isConstant && b.type != identifierExp))
9375                      {
9376                         // Use the simpleStruct name/ids for now...
9377                         if(inCompiler)
9378                         {
9379                            OldList * specs = MkList();
9380                            OldList * decls = MkList();
9381                            Declaration decl;
9382                            char temp1[1024], temp2[1024];
9383
9384                            GetTypeSpecs(a.expType, specs);
9385
9386                            if(a && !a.isConstant && a.type != identifierExp)
9387                            {
9388                               sprintf(temp1, "__simpleStruct%d", curContext.simpleID++);
9389                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp1)), null));
9390                               tempExp1 = QMkExpId(temp1);
9391                               tempExp1.expType = a.expType;
9392                               if(a.expType)
9393                                  a.expType.refCount++;
9394                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp1), '=', a));
9395                            }
9396                            if(b && !b.isConstant && b.type != identifierExp)
9397                            {
9398                               sprintf(temp2, "__simpleStruct%d", curContext.simpleID++);
9399                               ListAdd(decls, MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier(temp2)), null));
9400                               tempExp2 = QMkExpId(temp2);
9401                               tempExp2.expType = b.expType;
9402                               if(b.expType)
9403                                  b.expType.refCount++;
9404                               ListAdd(exp.list, MkExpOp(CopyExpression(tempExp2), '=', b));
9405                            }
9406
9407                            decl = MkDeclaration(specs, decls);
9408                            if(!curCompound.compound.declarations)
9409                               curCompound.compound.declarations = MkList();
9410                            curCompound.compound.declarations->Insert(null, decl);
9411                         }
9412                      }
9413                   }
9414
9415                   if(!strcmp(id.string, "Max") || !strcmp(id.string, "Min"))
9416                   {
9417                      int op = (!strcmp(id.string, "Max")) ? '>' : '<';
9418                      ListAdd(exp.list,
9419                         MkExpCondition(MkExpBrackets(MkListOne(
9420                            MkExpOp(CopyExpression(tempExp1), op, CopyExpression(tempExp2)))),
9421                            MkListOne(CopyExpression(tempExp1)), CopyExpression(tempExp2)));
9422                      exp.expType = a.expType;
9423                      if(a.expType)
9424                         a.expType.refCount++;
9425                   }
9426                   else if(!strcmp(id.string, "Abs"))
9427                   {
9428                      ListAdd(exp.list,
9429                         MkExpCondition(MkExpBrackets(MkListOne(
9430                            MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9431                            MkListOne(MkExpOp(null, '-', CopyExpression(tempExp1))), CopyExpression(tempExp1)));
9432                      exp.expType = a.expType;
9433                      if(a.expType)
9434                         a.expType.refCount++;
9435                   }
9436                   else if(!strcmp(id.string, "Sgn"))
9437                   {
9438                      // ((!(a))?(0):(((a)<0)?(-1):(1)))
9439                      ListAdd(exp.list,
9440                         MkExpCondition(MkExpBrackets(MkListOne(
9441                            MkExpOp(null, '!', CopyExpression(tempExp1)))), MkListOne(MkExpConstant("0")),
9442                               MkExpBrackets(MkListOne(MkExpCondition(MkExpBrackets(MkListOne(
9443                                  MkExpOp(CopyExpression(tempExp1), '<', MkExpConstant("0")))),
9444                                  MkListOne(MkExpConstant("-1")), MkExpConstant("1"))))));
9445                      exp.expType = ProcessTypeString("int", false);
9446                   }
9447
9448                   FreeExpression(tempExp1);
9449                   if(tempExp2) FreeExpression(tempExp2);
9450
9451                   FreeIdentifier(id);
9452                   break;
9453                }
9454             }
9455          }
9456
9457          {
9458             Type dummy
9459             {
9460                count = 1;
9461                refCount = 1;
9462             };
9463             if(!exp.call.exp.destType)
9464             {
9465                exp.call.exp.destType = dummy;
9466                dummy.refCount++;
9467             }
9468             ProcessExpressionType(exp.call.exp);
9469             if(exp.call.exp.destType == dummy)
9470             {
9471                FreeType(dummy);
9472                exp.call.exp.destType = null;
9473             }
9474             FreeType(dummy);
9475          }
9476
9477          // Check argument types against parameter types
9478          functionType = exp.call.exp.expType;
9479
9480          if(functionType && functionType.kind == TypeKind::methodType)
9481          {
9482             methodType = functionType;
9483             functionType = methodType.method.dataType;
9484
9485             //if(functionType.returnType && functionType.returnType.kind == thisClassType)
9486             // TOCHECK: Instead of doing this here could this be done per param?
9487             if(exp.call.exp.expType.usedClass)
9488             {
9489                char typeString[1024];
9490                typeString[0] = '\0';
9491                {
9492                   Symbol back = functionType.thisClass;
9493                   // Do not output class specifier here (thisclass was added to this)
9494                   functionType.thisClass = null;
9495                   PrintType(functionType, typeString, true, true);
9496                   functionType.thisClass = back;
9497                }
9498                if(strstr(typeString, "thisclass"))
9499                {
9500                   OldList * specs = MkList();
9501                   Declarator decl;
9502                   {
9503                      Context context = SetupTemplatesContext(exp.call.exp.expType.usedClass);
9504
9505                      decl = SpecDeclFromString(typeString, specs, null);
9506
9507                      // SET THIS TO FALSE WHEN PROCESSING THISCLASS OUTSIDE THE CLASS
9508                      if(thisClass != (exp.call.exp.expType.usedClass.templateClass ? exp.call.exp.expType.usedClass.templateClass :
9509                         exp.call.exp.expType.usedClass))
9510                         thisClassParams = false;
9511
9512                      ReplaceThisClassSpecifiers(specs, exp.call.exp.expType.usedClass);
9513                      {
9514                         Class backupThisClass = thisClass;
9515                         thisClass = exp.call.exp.expType.usedClass;
9516                         ProcessDeclarator(decl, true);
9517                         thisClass = backupThisClass;
9518                      }
9519
9520                      thisClassParams = true;
9521
9522                      functionType = ProcessType(specs, decl);
9523                      functionType.refCount = 0;
9524                      FinishTemplatesContext(context);
9525
9526                      // Mark parameters that were 'thisclass'
9527                      {
9528                         Type p, op;
9529                         for(p = functionType.params.first, op = methodType.method.dataType.params.first; p && op; p = p.next, op = op.next)
9530                         {
9531                            //p.wasThisClass = op.kind == thisClassType;
9532                            if(op.kind == thisClassType)
9533                               p.thisClassFrom = methodType.method._class;
9534                         }
9535                      }
9536                      if(methodType.method.dataType.returnType.kind == thisClassType)
9537                      {
9538                         // functionType.returnType.wasThisClass = true;
9539                         functionType.returnType.thisClassFrom = methodType.method._class;
9540                      }
9541                   }
9542
9543                   FreeList(specs, FreeSpecifier);
9544                   FreeDeclarator(decl);
9545                 }
9546             }
9547          }
9548          if(functionType && functionType.kind == pointerType && functionType.type && functionType.type.kind == TypeKind::functionType)
9549          {
9550             Type type = functionType.type;
9551             if(!functionType.refCount)
9552             {
9553                functionType.type = null;
9554                FreeType(functionType);
9555             }
9556             //methodType = functionType;
9557             functionType = type;
9558          }
9559          if(functionType && functionType.kind != TypeKind::functionType)
9560          {
9561             Compiler_Error($"called object %s is not a function\n", name);
9562          }
9563          else if(functionType)
9564          {
9565             bool emptyParams = false, noParams = false;
9566             Expression e = exp.call.arguments ? exp.call.arguments->first : null;
9567             Type type = functionType.params.first;
9568             Expression memberExp = (exp.call.exp.type == ExpressionType::memberExp) ? exp.call.exp : null;
9569             int extra = 0;
9570             Location oldyylloc = yylloc;
9571
9572             if(!type) emptyParams = true;
9573
9574             // WORKING ON THIS:
9575             if(functionType.extraParam && e && functionType.thisClass)
9576             {
9577                e.destType = MkClassType(functionType.thisClass.string);
9578                e = e.next;
9579             }
9580
9581             // WHY WAS THIS COMMENTED OUT ? Broke DisplaySystem::FontExtent(this ? displaySystem : null, font, text, len, width, height);
9582             // Fixed #141 by adding '&& !functionType.extraParam'
9583             if(!functionType.staticMethod && !functionType.extraParam)
9584             {
9585                if(memberExp && memberExp.member.exp && memberExp.member.exp.expType && memberExp.member.exp.expType.kind == subClassType &&
9586                   memberExp.member.exp.expType._class)
9587                {
9588                   type = MkClassType(memberExp.member.exp.expType._class.string);
9589                   if(e)
9590                   {
9591                      e.destType = type;
9592                      e = e.next;
9593                      type = functionType.params.first;
9594                   }
9595                   else
9596                      type.refCount = 0;
9597                }
9598                else if(!memberExp && (functionType.thisClass || (methodType && methodType.methodClass)))
9599                {
9600                   type = MkClassType(functionType.thisClass ? functionType.thisClass.string : (methodType ? methodType.methodClass.fullName : null));
9601                   type.byReference = functionType.byReference;
9602                   type.typedByReference = functionType.typedByReference;
9603                   if(e)
9604                   {
9605                      // Allow manually passing a class for typed object
9606                      if(e.next && type.kind == classType && (functionType && functionType.thisClass) && functionType.classObjectType == typedObject)
9607                         e = e.next;
9608                      e.destType = type;
9609                      e = e.next;
9610                      type = functionType.params.first;
9611                   }
9612                   else
9613                      type.refCount = 0;
9614                   //extra = 1;
9615                }
9616             }
9617
9618             if(type && type.kind == voidType)
9619             {
9620                noParams = true;
9621                if(!type.refCount) FreeType(type);
9622                type = null;
9623             }
9624
9625             for( ; e; e = e.next)
9626             {
9627                if(!type && !emptyParams)
9628                {
9629                   yylloc = e.loc;
9630                   if(methodType && methodType.methodClass)
9631                      Compiler_Error($"too many arguments for method %s::%s (%d given, expected %d)\n",
9632                         methodType.methodClass.fullName, methodType.method.name, exp.call.arguments->count,
9633                         noParams ? 0 : functionType.params.count);
9634                   else
9635                      Compiler_Error($"too many arguments for function %s (%d given, expected %d)\n",
9636                         name /*exp.call.exp.identifier.string*/, exp.call.arguments->count,
9637                         noParams ? 0 : functionType.params.count);
9638                   break;
9639                }
9640
9641                if(methodType && type && type.kind == templateType && type.templateParameter.type == TemplateParameterType::type)
9642                {
9643                   Type templatedType = null;
9644                   Class _class = methodType.usedClass;
9645                   ClassTemplateParameter curParam = null;
9646                   int id = 0;
9647                   if(_class && _class.templateArgs /*&& _class.templateClass*/)
9648                   {
9649                      Class sClass;
9650                      for(sClass = _class; sClass; sClass = sClass.base)
9651                      {
9652                         if(sClass.templateClass) sClass = sClass.templateClass;
9653                         id = 0;
9654                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
9655                         {
9656                            if(curParam.type == TemplateParameterType::type && !strcmp(type.templateParameter.identifier.string, curParam.name))
9657                            {
9658                               Class nextClass;
9659                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base)
9660                               {
9661                                  if(nextClass.templateClass) nextClass = nextClass.templateClass;
9662                                  id += nextClass.templateParams.count;
9663                               }
9664                               break;
9665                            }
9666                            id++;
9667                         }
9668                         if(curParam) break;
9669                      }
9670                   }
9671                   if(curParam && _class.templateArgs[id].dataTypeString)
9672                   {
9673                      bool constant = type.constant;
9674                      ClassTemplateArgument arg = _class.templateArgs[id];
9675                      {
9676                         Context context = SetupTemplatesContext(_class);
9677
9678                         /*if(!arg.dataType)
9679                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
9680                         templatedType = ProcessTypeString(arg.dataTypeString, false);
9681                         FinishTemplatesContext(context);
9682                      }
9683
9684                      if(templatedType.kind == classType && constant) templatedType.constant = true;
9685                      else if(templatedType.kind == pointerType)
9686                      {
9687                         Type t = templatedType.type;
9688                         while(t.kind == pointerType) t = t.type;
9689                         if(constant) t.constant = constant;
9690                      }
9691
9692                      e.destType = templatedType;
9693                      if(templatedType)
9694                      {
9695                         templatedType.passAsTemplate = true;
9696                         // templatedType.refCount++;
9697                      }
9698                   }
9699                   else
9700                   {
9701                      e.destType = type;
9702                      if(type) type.refCount++;
9703                   }
9704                }
9705                else
9706                {
9707                   if(type && type.kind == ellipsisType && type.prev && type.prev.kind == classType && type.prev.classObjectType)
9708                   {
9709                      e.destType = type.prev;
9710                      e.destType.refCount++;
9711                   }
9712                   else
9713                   {
9714                      e.destType = type;
9715                      if(type) type.refCount++;
9716                   }
9717                }
9718                // Don't reach the end for the ellipsis
9719                if(type && type.kind != ellipsisType)
9720                {
9721                   Type next = type.next;
9722                   if(!type.refCount) FreeType(type);
9723                   type = next;
9724                }
9725             }
9726
9727             if(type && type.kind != ellipsisType)
9728             {
9729                if(methodType && methodType.methodClass)
9730                   Compiler_Warning($"not enough arguments for method %s::%s (%d given, expected %d)\n",
9731                      methodType.methodClass.fullName, methodType.method.name, exp.call.arguments ? exp.call.arguments->count : 0,
9732                      functionType.params.count + extra);
9733                else
9734                   Compiler_Warning($"not enough arguments for function %s (%d given, expected %d)\n",
9735                      name /*exp.call.exp.identifier.string*/, exp.call.arguments ? exp.call.arguments->count : 0,
9736                      functionType.params.count + extra);
9737             }
9738             yylloc = oldyylloc;
9739             if(type && !type.refCount) FreeType(type);
9740          }
9741          else
9742          {
9743             functionType = Type
9744             {
9745                refCount = 0;
9746                kind = TypeKind::functionType;
9747             };
9748
9749             if(exp.call.exp.type == identifierExp)
9750             {
9751                char * string = exp.call.exp.identifier.string;
9752                if(inCompiler)
9753                {
9754                   Symbol symbol;
9755                   Location oldyylloc = yylloc;
9756
9757                   yylloc = exp.call.exp.identifier.loc;
9758                   if(strstr(string, "__builtin_") == string)
9759                   {
9760                      if(exp.destType)
9761                      {
9762                         functionType.returnType = exp.destType;
9763                         exp.destType.refCount++;
9764                      }
9765                   }
9766                   else
9767                      Compiler_Warning($"%s undefined; assuming extern returning int\n", string);
9768                   symbol = Symbol { string = CopyString(string), type = ProcessTypeString("int()", true) };
9769                   globalContext.symbols.Add((BTNode)symbol);
9770                   if(strstr(symbol.string, "::"))
9771                      globalContext.hasNameSpace = true;
9772
9773                   yylloc = oldyylloc;
9774                }
9775             }
9776             else if(exp.call.exp.type == memberExp)
9777             {
9778                /*Compiler_Warning($"%s undefined; assuming returning int\n",
9779                   exp.call.exp.member.member.string);*/
9780             }
9781             else
9782                Compiler_Warning($"callable object undefined; extern assuming returning int\n");
9783
9784             if(!functionType.returnType)
9785             {
9786                functionType.returnType = Type
9787                {
9788                   refCount = 1;
9789                   kind = intType;
9790                };
9791             }
9792          }
9793          if(functionType && functionType.kind == TypeKind::functionType)
9794          {
9795             exp.expType = functionType.returnType;
9796
9797             if(functionType.returnType)
9798                functionType.returnType.refCount++;
9799
9800             if(!functionType.refCount)
9801                FreeType(functionType);
9802          }
9803
9804          if(exp.call.arguments)
9805          {
9806             for(e = exp.call.arguments->first; e; e = e.next)
9807                ProcessExpressionType(e);
9808          }
9809          break;
9810       }
9811       case memberExp:
9812       {
9813          Type type;
9814          Location oldyylloc = yylloc;
9815          bool thisPtr;
9816          Expression checkExp = exp.member.exp;
9817          while(checkExp)
9818          {
9819             if(checkExp.type == castExp)
9820                checkExp = checkExp.cast.exp;
9821             else if(checkExp.type == bracketsExp)
9822                checkExp = checkExp.list ? checkExp.list->first : null;
9823             else
9824                break;
9825          }
9826
9827          thisPtr = (checkExp && checkExp.type == identifierExp && !strcmp(checkExp.identifier.string, "this"));
9828          exp.thisPtr = thisPtr;
9829
9830          // DOING THIS LATER NOW...
9831          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
9832          {
9833             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
9834             /* TODO: Name Space Fix ups
9835             if(!exp.member.member.classSym)
9836                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.fullName);
9837             */
9838          }
9839
9840          ProcessExpressionType(exp.member.exp);
9841          if(exp.member.exp.expType && exp.member.exp.expType.kind == classType && exp.member.exp.expType._class &&
9842             exp.member.exp.expType._class.registered && exp.member.exp.expType._class.registered.type == normalClass)
9843          {
9844             exp.isConstant = false;
9845          }
9846          else
9847             exp.isConstant = exp.member.exp.isConstant;
9848          type = exp.member.exp.expType;
9849
9850          yylloc = exp.loc;
9851
9852          if(type && (type.kind == templateType))
9853          {
9854             Class _class = thisClass ? thisClass : currentClass;
9855             ClassTemplateParameter param = null;
9856             if(_class)
9857             {
9858                for(param = _class.templateParams.first; param; param = param.next)
9859                {
9860                   if(param.type == identifier && exp.member.member && exp.member.member.string && !strcmp(param.name, exp.member.member.string))
9861                      break;
9862                }
9863             }
9864             if(param && param.defaultArg.member)
9865             {
9866                Expression argExp = GetTemplateArgExpByName(param.name, thisClass, TemplateParameterType::identifier);
9867                if(argExp)
9868                {
9869                   Expression expMember = exp.member.exp;
9870                   Declarator decl;
9871                   OldList * specs = MkList();
9872                   char thisClassTypeString[1024];
9873
9874                   FreeIdentifier(exp.member.member);
9875
9876                   ProcessExpressionType(argExp);
9877
9878                   {
9879                      char * colon = strstr(param.defaultArg.memberString, "::");
9880                      if(colon)
9881                      {
9882                         memcpy(thisClassTypeString, param.defaultArg.memberString, colon - param.defaultArg.memberString);
9883                         thisClassTypeString[colon - param.defaultArg.memberString] = '\0';
9884                      }
9885                      else
9886                         strcpy(thisClassTypeString, _class.fullName);
9887                   }
9888
9889                   decl = SpecDeclFromString(param.defaultArg.member.dataTypeString, specs, null);
9890
9891                   exp.expType = ProcessType(specs, decl);
9892                   if(exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.templateClass)
9893                   {
9894                      Class expClass = exp.expType._class.registered;
9895                      Class cClass = null;
9896                      int paramCount = 0;
9897                      int lastParam = -1;
9898
9899                      char templateString[1024];
9900                      ClassTemplateParameter param;
9901                      sprintf(templateString, "%s<", expClass.templateClass.fullName);
9902                      for(cClass = expClass; cClass; cClass = cClass.base)
9903                      {
9904                         int p = 0;
9905                         for(param = cClass.templateParams.first; param; param = param.next)
9906                         {
9907                            int id = p;
9908                            Class sClass;
9909                            ClassTemplateArgument arg;
9910                            for(sClass = cClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
9911                            arg = expClass.templateArgs[id];
9912
9913                            for(sClass = _class /*expClass*/; sClass; sClass = sClass.base)
9914                            {
9915                               ClassTemplateParameter cParam;
9916                               //int p = numParams - sClass.templateParams.count;
9917                               int p = 0;
9918                               Class nextClass;
9919                               for(nextClass = sClass.base; nextClass; nextClass = nextClass.base) p += nextClass.templateParams.count;
9920
9921                               for(cParam = sClass.templateParams.first; cParam; cParam = cParam.next, p++)
9922                               {
9923                                  if(cParam.type == TemplateParameterType::type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
9924                                  {
9925                                     if(_class.templateArgs && arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9926                                     {
9927                                        arg.dataTypeString = _class.templateArgs[p].dataTypeString;
9928                                        arg.dataTypeClass = _class.templateArgs[p].dataTypeClass;
9929                                        break;
9930                                     }
9931                                  }
9932                               }
9933                            }
9934
9935                            {
9936                               char argument[256];
9937                               argument[0] = '\0';
9938                               /*if(arg.name)
9939                               {
9940                                  strcat(argument, arg.name.string);
9941                                  strcat(argument, " = ");
9942                               }*/
9943                               switch(param.type)
9944                               {
9945                                  case expression:
9946                                  {
9947                                     // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
9948                                     char expString[1024];
9949                                     OldList * specs = MkList();
9950                                     Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
9951                                     Expression exp;
9952                                     char * string = PrintHexUInt64(arg.expression.ui64);
9953                                     exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
9954                                     delete string;
9955
9956                                     ProcessExpressionType(exp);
9957                                     ComputeExpression(exp);
9958                                     expString[0] = '\0';
9959                                     PrintExpression(exp, expString);
9960                                     strcat(argument, expString);
9961                                     // delete exp;
9962                                     FreeExpression(exp);
9963                                     break;
9964                                  }
9965                                  case identifier:
9966                                  {
9967                                     strcat(argument, arg.member.name);
9968                                     break;
9969                                  }
9970                                  case TemplateParameterType::type:
9971                                  {
9972                                     if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
9973                                     {
9974                                        if(!strcmp(arg.dataTypeString, "thisclass"))
9975                                           strcat(argument, thisClassTypeString);
9976                                        else
9977                                           strcat(argument, arg.dataTypeString);
9978                                     }
9979                                     break;
9980                                  }
9981                               }
9982                               if(argument[0])
9983                               {
9984                                  if(paramCount) strcat(templateString, ", ");
9985                                  if(lastParam != p - 1)
9986                                  {
9987                                     strcat(templateString, param.name);
9988                                     strcat(templateString, " = ");
9989                                  }
9990                                  strcat(templateString, argument);
9991                                  paramCount++;
9992                                  lastParam = p;
9993                               }
9994                               p++;
9995                            }
9996                         }
9997                      }
9998                      {
9999                         int len = strlen(templateString);
10000                         if(templateString[len-1] == '>') templateString[len++] = ' ';
10001                         templateString[len++] = '>';
10002                         templateString[len++] = '\0';
10003                      }
10004                      {
10005                         Context context = SetupTemplatesContext(_class);
10006                         FreeType(exp.expType);
10007                         exp.expType = ProcessTypeString(templateString, false);
10008                         FinishTemplatesContext(context);
10009                      }
10010                   }
10011
10012                   if(!expMember.expType.isPointerType)
10013                      expMember = MkExpCast(MkTypeName(MkListOne(MkSpecifierName("uintptr")), null), expMember);
10014                   // *([expType] *)(((byte *)(uintptr)[exp.member.exp]) + [argExp].member.offset)
10015                   exp.type = bracketsExp;
10016                   exp.list = MkListOne(MkExpOp(null, '*',
10017                   /*opExp;
10018                   exp.op.op = '*';
10019                   exp.op.exp1 = null;
10020                   exp.op.exp2 = */
10021                   MkExpCast(MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl)), MkExpBrackets(MkListOne(MkExpOp(
10022                      MkExpBrackets(MkListOne(
10023                         MkExpCast(MkTypeName(MkListOne(MkSpecifierName("byte")), MkDeclaratorPointer(MkPointer(null, null), null)),
10024                            expMember))),
10025                               '+',
10026                               MkExpOp(MkExpMember(MkExpMember(argExp, MkIdentifier("member")), MkIdentifier("offset")),
10027                               '+',
10028                               MkExpMember(MkExpMember(MkExpMember(CopyExpression(argExp), MkIdentifier("member")), MkIdentifier("_class")), MkIdentifier("offset")))))))
10029
10030                            ));
10031                }
10032             }
10033             else if(type.templateParameter && type.templateParameter.type == TemplateParameterType::type &&
10034                (type.templateParameter.dataType || type.templateParameter.dataTypeString))
10035             {
10036                type = ProcessTemplateParameterType(type.templateParameter);
10037             }
10038          }
10039          // TODO: *** This seems to be where we should add method support for all basic types ***
10040          if(type && (type.kind == templateType));
10041          else if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType ||
10042                           type.kind == int64Type || type.kind == shortType || type.kind == longType || type.kind == charType || type.kind == _BoolType ||
10043                           type.kind == intPtrType || type.kind == intSizeType || type.kind == floatType || type.kind == doubleType ||
10044                           (type.kind == pointerType && type.type.kind == charType)))
10045          {
10046             Identifier id = exp.member.member;
10047             TypeKind typeKind = type.kind;
10048             Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10049             if(typeKind == subClassType && exp.member.exp.type == classExp)
10050             {
10051                _class = eSystem_FindClass(privateModule, "ecere::com::Class");
10052                typeKind = classType;
10053             }
10054
10055             if(id)
10056             {
10057                if(typeKind == intType || typeKind == enumType)
10058                   _class = eSystem_FindClass(privateModule, "int");
10059                else if(!_class)
10060                {
10061                   if(type.kind == classType && type._class && type._class.registered)
10062                   {
10063                      _class = type._class.registered;
10064                   }
10065                   else if((type.kind == arrayType || type.kind == pointerType) && type.type && type.type.kind == charType)
10066                   {
10067                      _class = FindClass("char *").registered;
10068                   }
10069                   else if(type.kind == pointerType)
10070                   {
10071                      _class = eSystem_FindClass(privateModule, "uintptr");
10072                      FreeType(exp.expType);
10073                      exp.expType = ProcessTypeString("uintptr", false);
10074                      exp.byReference = true;
10075                   }
10076                   else
10077                   {
10078                      char string[1024] = "";
10079                      Symbol classSym;
10080                      PrintTypeNoConst(type, string, false, true);
10081                      classSym = FindClass(string);
10082                      if(classSym) _class = classSym.registered;
10083                   }
10084                }
10085             }
10086
10087             if(_class && id)
10088             {
10089                /*bool thisPtr =
10090                   (exp.member.exp.type == identifierExp &&
10091                   !strcmp(exp.member.exp.identifier.string, "this"));*/
10092                Property prop = null;
10093                Method method = null;
10094                DataMember member = null;
10095                Property revConvert = null;
10096                ClassProperty classProp = null;
10097
10098                if(id && id._class && id._class.name && !strcmp(id._class.name, "property"))
10099                   exp.member.memberType = propertyMember;
10100
10101                if(id && id._class && type._class && !eClass_IsDerived(type._class.registered, _class))
10102                   Compiler_Error($"invalid class specifier %s for object of class %s\n", _class.fullName, type._class.string);
10103
10104                if(typeKind != subClassType)
10105                {
10106                   // Prioritize data members over properties for "this"
10107                   if((exp.member.memberType == unresolvedMember && thisPtr) || exp.member.memberType == dataMember)
10108                   {
10109                      member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10110                      if(member && member._class != (_class.templateClass ? _class.templateClass : _class) && exp.member.memberType != dataMember)
10111                      {
10112                         prop = eClass_FindProperty(_class, id.string, privateModule);
10113                         if(prop)
10114                            member = null;
10115                      }
10116                      if(!member && !prop)
10117                         prop = eClass_FindProperty(_class, id.string, privateModule);
10118                      if((member && member._class == (_class.templateClass ? _class.templateClass : _class)) ||
10119                         (prop && prop._class == (_class.templateClass ? _class.templateClass : _class)))
10120                         exp.member.thisPtr = true;
10121                   }
10122                   // Prioritize properties over data members otherwise
10123                   else
10124                   {
10125                      bool useMemberForNonConst = false;
10126                      // First look for Public Members (Unless class specifier is provided, which skips public priority)
10127                      if(!id.classSym)
10128                      {
10129                         prop = eClass_FindProperty(_class, id.string, null);
10130
10131                         useMemberForNonConst = prop && exp.destType &&
10132                            ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10133                               !strncmp(prop.dataTypeString, "const ", 6);
10134
10135                         if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10136                            member = eClass_FindDataMember(_class, id.string, null, null, null);
10137                      }
10138
10139                      if((!prop || useMemberForNonConst) && !member)
10140                      {
10141                         method = useMemberForNonConst ? null : eClass_FindMethod(_class, id.string, null);
10142                         if(!method)
10143                         {
10144                            prop = eClass_FindProperty(_class, id.string, privateModule);
10145
10146                            useMemberForNonConst |= prop && exp.destType &&
10147                               ( (exp.destType.kind == classType && !exp.destType.constant) || ((exp.destType.kind == pointerType || exp.destType.kind == arrayType) && exp.destType.type && !exp.destType.type.constant) ) &&
10148                                  !strncmp(prop.dataTypeString, "const ", 6);
10149
10150                            if(useMemberForNonConst || !id._class || !id._class.name || strcmp(id._class.name, "property"))
10151                               member = eClass_FindDataMember(_class, id.string, privateModule, null, null);
10152                         }
10153                      }
10154
10155                      if(member && prop)
10156                      {
10157                         if(useMemberForNonConst || (member._class != prop._class && !id._class && eClass_IsDerived(member._class, prop._class)))
10158                            prop = null;
10159                         else
10160                            member = null;
10161                      }
10162                   }
10163                }
10164                if(!prop && !member && !method)     // NOTE: Recently added the !method here, causes private methods to unprioritized
10165                   method = eClass_FindMethod(_class, id.string, privateModule);
10166                if(!prop && !member && !method)
10167                {
10168                   if(typeKind == subClassType)
10169                   {
10170                      classProp = eClass_FindClassProperty(type._class.registered, exp.member.member.string);
10171                      if(classProp)
10172                      {
10173                         exp.member.memberType = classPropertyMember;
10174                         exp.expType = ProcessTypeString(classProp.dataTypeString, false);
10175                      }
10176                      else
10177                      {
10178                         // Assume this is a class_data member
10179                         char structName[1024];
10180                         Identifier id = exp.member.member;
10181                         Expression classExp = exp.member.exp;
10182                         type.refCount++;
10183
10184                         FreeType(classExp.expType);
10185                         classExp.expType = ProcessTypeString("ecere::com::Class", false);
10186
10187                         strcpy(structName, "__ecereClassData_");
10188                         FullClassNameCat(structName, type._class.string, false);
10189                         exp.type = pointerExp;
10190                         exp.member.member = id;
10191
10192                         exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10193                            MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10194                               MkExpBrackets(MkListOne(MkExpOp(
10195                                  MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10196                                     MkExpMember(classExp, MkIdentifier("data"))), '+',
10197                                        MkExpMember(MkExpClass(MkListOne(MkSpecifierName(type._class.string)), null), MkIdentifier("offsetClass")))))
10198                                  )));
10199
10200                         FreeType(type);
10201
10202                         ProcessExpressionType(exp);
10203                         return;
10204                      }
10205                   }
10206                   else
10207                   {
10208                      // Check for reverse conversion
10209                      // (Convert in an instantiation later, so that we can use
10210                      //  deep properties system)
10211                      Symbol classSym = FindClass(id.string);
10212                      if(classSym)
10213                      {
10214                         Class convertClass = classSym.registered;
10215                         if(convertClass)
10216                            revConvert = eClass_FindProperty(convertClass, _class.fullName, privateModule);
10217                      }
10218                   }
10219                }
10220
10221                //if(!exp.member.exp.destType)
10222                if(exp.member.exp.destType)
10223                   FreeType(exp.member.exp.destType);
10224                {
10225                   if(method && !method._class.symbol)
10226                      method._class.symbol = FindClass(method._class.fullName);
10227                   if(prop && !prop._class.symbol)
10228                      prop._class.symbol = FindClass(prop._class.fullName);
10229
10230                   exp.member.exp.destType = Type
10231                   {
10232                      refCount = 1;
10233                      kind = classType;
10234                      _class = prop ? prop._class.symbol : method ? method._class.symbol : _class.symbol;
10235                      // wasThisClass = type ? type.wasThisClass : false;
10236                      thisClassFrom = type ? type.thisClassFrom : null;
10237                   };
10238                }
10239
10240                if(prop)
10241                {
10242                   exp.member.memberType = propertyMember;
10243                   if(!prop.dataType)
10244                      ProcessPropertyType(prop);
10245                   exp.expType = prop.dataType;
10246                   if(!strcmp(_class.base.fullName, "eda::Row") && !exp.expType.constant && !exp.destType)
10247                   {
10248                      Type type { };
10249                      CopyTypeInto(type, exp.expType);
10250                      type.refCount = 1;
10251                      type.constant = true;
10252                      exp.expType = type;
10253                   }
10254                   else if(prop.dataType)
10255                      prop.dataType.refCount++;
10256                }
10257                else if(member)
10258                {
10259                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10260                   {
10261                      FreeExpContents(exp);
10262                      exp.type = identifierExp;
10263                      exp.identifier = MkIdentifier("class");
10264                      ProcessExpressionType(exp);
10265                      return;
10266                   }
10267
10268                   exp.member.memberType = dataMember;
10269                   DeclareStruct(curExternal, _class.fullName, false, true);
10270                   if(member._class != _class)
10271                      DeclareStruct(curExternal, member._class.fullName, false, true);
10272
10273                   if(!member.dataType)
10274                   {
10275                      Context context = SetupTemplatesContext(_class);
10276                      member.dataType = ProcessTypeString(member.dataTypeString, false);
10277                      FinishTemplatesContext(context);
10278                   }
10279                   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)
10280                      member.dataType.bitMemberSize = ((BitMember)member).size;
10281                   exp.expType = member.dataType;
10282                   if(member.dataType) member.dataType.refCount++;
10283                }
10284                else if(revConvert)
10285                {
10286                   exp.member.memberType = reverseConversionMember;
10287                   exp.expType = MkClassType(revConvert._class.fullName);
10288                }
10289                else if(method)
10290                {
10291                   //if(inCompiler)
10292                   {
10293                      /*if(id._class)
10294                      {
10295                         exp.type = identifierExp;
10296                         exp.identifier = exp.member.member;
10297                      }
10298                      else*/
10299                         exp.member.memberType = methodMember;
10300                   }
10301                   if(!method.dataType)
10302                      ProcessMethodType(method);
10303                   exp.expType = Type
10304                   {
10305                      refCount = 1;
10306                      kind = methodType;
10307                      method = method;
10308                   };
10309
10310                   // Tricky spot here... To use instance versus class virtual table
10311                   // Put it back to what it was... What did we break?
10312
10313                   // Had to put it back for overriding Main of Thread global instance
10314
10315                   //exp.expType.methodClass = _class;
10316                   exp.expType.methodClass = (id && id._class) ? _class : null;
10317
10318                   // Need the actual class used for templated classes
10319                   exp.expType.usedClass = _class;
10320                }
10321                else if(!classProp)
10322                {
10323                   if(exp.member.exp.expType.classObjectType == typedObject && !strcmp(exp.member.member.string, "_class"))
10324                   {
10325                      FreeExpContents(exp);
10326                      exp.type = identifierExp;
10327                      exp.identifier = MkIdentifier("class");
10328                      FreeType(exp.expType);
10329                      exp.expType = MkClassType("ecere::com::Class");
10330                      return;
10331                   }
10332                   yylloc = exp.member.member.loc;
10333                   Compiler_Error($"couldn't find member %s in class %s\n", id.string, _class.fullName);
10334                   if(inCompiler)
10335                      eClass_AddDataMember(_class, id.string, "int", 0, 0, publicAccess);
10336                }
10337
10338                if(_class && /*(_class.templateClass || _class.templateArgs) && */exp.expType)
10339                {
10340                   Class tClass;
10341
10342                   tClass = type._class && type._class.registered ? type._class.registered : _class;
10343                   while(tClass && !tClass.templateClass) tClass = tClass.base;
10344
10345                   if(tClass && exp.expType.kind == templateType && exp.expType.templateParameter.type == TemplateParameterType::type)
10346                   {
10347                      int id = 0;
10348                      ClassTemplateParameter curParam = null;
10349                      Class sClass;
10350
10351                      for(sClass = tClass; sClass; sClass = sClass.base)
10352                      {
10353                         id = 0;
10354                         if(sClass.templateClass) sClass = sClass.templateClass;
10355                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10356                         {
10357                            if(curParam.type == TemplateParameterType::type && !strcmp(exp.expType.templateParameter.identifier.string, curParam.name))
10358                            {
10359                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10360                                  id += sClass.templateParams.count;
10361                               break;
10362                            }
10363                            id++;
10364                         }
10365                         if(curParam) break;
10366                      }
10367
10368                      if(curParam && tClass.templateArgs[id].dataTypeString)
10369                      {
10370                         ClassTemplateArgument arg = tClass.templateArgs[id];
10371                         Context context = SetupTemplatesContext(tClass);
10372                         bool constant = exp.expType.constant;
10373                         bool passAsTemplate = false;
10374                         Class thisClassFrom = null;
10375                         Type t = ProcessTypeString(exp.expType.templateParameter.dataTypeString, false);
10376                         if(t && t.kind == classType && t._class)
10377                            thisClassFrom = t._class.registered;
10378                         else
10379                            // Mark that 'thisClassFrom' was set to something
10380                            thisClassFrom = eSystem_FindClass(GetPrivateModule(), "class");
10381
10382                         FreeType(t);
10383
10384                         passAsTemplate = tClass.templateClass && (exp.expType.kind != templateType ||
10385                            (!exp.expType.templateParameter || (!exp.expType.templateParameter.dataTypeString && !exp.expType.templateParameter.dataType)));
10386
10387                         /*if(!arg.dataType)
10388                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10389                         FreeType(exp.expType);
10390
10391                         exp.expType = ProcessTypeString(arg.dataTypeString, false);
10392                         exp.expType.thisClassFrom = thisClassFrom;
10393                         if(exp.expType.kind == classType && constant) exp.expType.constant = true;
10394                         else if(exp.expType.kind == pointerType)
10395                         {
10396                            Type t = exp.expType.type;
10397                            while(t.kind == pointerType) t = t.type;
10398                            if(constant) t.constant = constant;
10399                         }
10400                         if(exp.expType)
10401                         {
10402                            if(exp.expType.kind == thisClassType)
10403                            {
10404                               FreeType(exp.expType);
10405                               exp.expType = ReplaceThisClassType(_class);
10406                            }
10407
10408                            if(passAsTemplate)
10409                               exp.expType.passAsTemplate = true;
10410                            //exp.expType.refCount++;
10411                            if(!exp.destType)
10412                            {
10413                               exp.destType = ProcessTypeString(arg.dataTypeString, false);
10414                               if(exp.destType.kind == classType && constant) exp.destType.constant = true;
10415                               else if(exp.destType.kind == pointerType)
10416                               {
10417                                  Type t = exp.destType.type;
10418                                  while(t.kind == pointerType) t = t.type;
10419                                  if(constant) t.constant = constant;
10420                               }
10421
10422                               //exp.destType.refCount++;
10423
10424                               if(exp.destType.kind == thisClassType)
10425                               {
10426                                  FreeType(exp.destType);
10427                                  exp.destType = ReplaceThisClassType(_class);
10428                               }
10429                            }
10430                         }
10431                         FinishTemplatesContext(context);
10432                      }
10433                   }
10434                   // TODO: MORE GENERIC SUPPORT FOR DEEPER TYPES
10435                   else if(tClass && exp.expType.kind == pointerType && exp.expType.type && exp.expType.type.kind == templateType && exp.expType.type.templateParameter.type == TemplateParameterType::type)
10436                   {
10437                      int id = 0;
10438                      ClassTemplateParameter curParam = null;
10439                      Class sClass;
10440
10441                      for(sClass = tClass; sClass; sClass = sClass.base)
10442                      {
10443                         id = 0;
10444                         if(sClass.templateClass) sClass = sClass.templateClass;
10445                         for(curParam = sClass.templateParams.first; curParam; curParam = curParam.next)
10446                         {
10447                            if(curParam.type == TemplateParameterType::type &&
10448                               !strcmp(exp.expType.type.templateParameter.identifier.string, curParam.name))
10449                            {
10450                               for(sClass = sClass.base; sClass; sClass = sClass.base)
10451                                  id += sClass.templateParams.count;
10452                               break;
10453                            }
10454                            id++;
10455                         }
10456                         if(curParam) break;
10457                      }
10458
10459                      if(curParam)
10460                      {
10461                         ClassTemplateArgument arg = tClass.templateArgs[id];
10462                         Context context = SetupTemplatesContext(tClass);
10463                         Type basicType;
10464                         /*if(!arg.dataType)
10465                            arg.dataType = ProcessTypeString(arg.dataTypeString, false);*/
10466
10467                         basicType = ProcessTypeString(arg.dataTypeString, false);
10468                         if(basicType)
10469                         {
10470                            if(basicType.kind == thisClassType)
10471                            {
10472                               FreeType(basicType);
10473                               basicType = ReplaceThisClassType(_class);
10474                            }
10475
10476                            /*    DO WE REALLY WANT THIS HERE? IT SEEMS TO BE ONLY USED WITH Array::array which was causing bug 135
10477                            if(tClass.templateClass)
10478                               basicType.passAsTemplate = true;
10479                            */
10480
10481                            FreeType(exp.expType);
10482
10483                            exp.expType = Type { refCount = 1, kind = pointerType, type = basicType };
10484                            //exp.expType.refCount++;
10485                            if(!exp.destType)
10486                            {
10487                               exp.destType = exp.expType;
10488                               exp.destType.refCount++;
10489                            }
10490
10491                            {
10492                               Expression newExp { };
10493                               OldList * specs = MkList();
10494                               Declarator decl;
10495                               decl = SpecDeclFromString(arg.dataTypeString, specs, null);
10496                               *newExp = *exp;
10497                               if(exp.destType) exp.destType.refCount++;
10498                               if(exp.expType)  exp.expType.refCount++;
10499                               exp.type = castExp;
10500                               exp.cast.typeName = MkTypeName(specs, MkDeclaratorPointer(MkPointer(null, null), decl));
10501                               exp.cast.exp = newExp;
10502                               //FreeType(exp.expType);
10503                               //exp.expType = null;
10504                               //ProcessExpressionType(sourceExp);
10505                            }
10506                         }
10507                         FinishTemplatesContext(context);
10508                      }
10509                   }
10510                   else if(tClass && exp.expType.kind == classType && exp.expType._class && strchr(exp.expType._class.string, '<'))
10511                   {
10512                      Class expClass = exp.expType._class.registered;
10513                      if(expClass)
10514                      {
10515                         Class cClass = null;
10516                         int p = 0;
10517                         int paramCount = 0;
10518                         int lastParam = -1;
10519                         char templateString[1024];
10520                         ClassTemplateParameter param;
10521                         sprintf(templateString, "%s<", expClass.templateClass.fullName);
10522                         while(cClass != expClass)
10523                         {
10524                            Class sClass;
10525                            for(sClass = expClass; sClass && sClass.base != cClass; sClass = sClass.base);
10526                            cClass = sClass;
10527
10528                            for(param = cClass.templateParams.first; param; param = param.next)
10529                            {
10530                               Class cClassCur = null;
10531                               int cp = 0;
10532                               ClassTemplateParameter paramCur = null;
10533                               ClassTemplateArgument arg;
10534                               while(cClassCur != tClass && !paramCur)
10535                               {
10536                                  Class sClassCur;
10537                                  for(sClassCur = tClass; sClassCur && sClassCur.base != cClassCur; sClassCur = sClassCur.base);
10538                                  cClassCur = sClassCur;
10539
10540                                  for(paramCur = cClassCur.templateParams.first; paramCur; paramCur = paramCur.next)
10541                                  {
10542                                     if(!strcmp(paramCur.name, param.name))
10543                                     {
10544
10545                                        break;
10546                                     }
10547                                     cp++;
10548                                  }
10549                               }
10550                               if(paramCur && paramCur.type == TemplateParameterType::type)
10551                                  arg = tClass.templateArgs[cp];
10552                               else
10553                                  arg = expClass.templateArgs[p];
10554
10555                               {
10556                                  char argument[256];
10557                                  argument[0] = '\0';
10558                                  /*if(arg.name)
10559                                  {
10560                                     strcat(argument, arg.name.string);
10561                                     strcat(argument, " = ");
10562                                  }*/
10563                                  switch(param.type)
10564                                  {
10565                                     case expression:
10566                                     {
10567                                        // THIS WHOLE THING IS A WILD GUESS... FIX IT UP
10568                                        char expString[1024];
10569                                        OldList * specs = MkList();
10570                                        Declarator decl = SpecDeclFromString(param.dataTypeString, specs, null);
10571                                        Expression exp;
10572                                        char * string = PrintHexUInt64(arg.expression.ui64);
10573                                        exp = MkExpCast(MkTypeName(specs, decl), MkExpConstant(string));
10574                                        delete string;
10575
10576                                        ProcessExpressionType(exp);
10577                                        ComputeExpression(exp);
10578                                        expString[0] = '\0';
10579                                        PrintExpression(exp, expString);
10580                                        strcat(argument, expString);
10581                                        // delete exp;
10582                                        FreeExpression(exp);
10583                                        break;
10584                                     }
10585                                     case identifier:
10586                                     {
10587                                        strcat(argument, arg.member.name);
10588                                        break;
10589                                     }
10590                                     case TemplateParameterType::type:
10591                                     {
10592                                        if(arg.dataTypeString && (!param.defaultArg.dataTypeString || strcmp(arg.dataTypeString, param.defaultArg.dataTypeString)))
10593                                           strcat(argument, arg.dataTypeString);
10594                                        break;
10595                                     }
10596                                  }
10597                                  if(argument[0])
10598                                  {
10599                                     if(paramCount) strcat(templateString, ", ");
10600                                     if(lastParam != p - 1)
10601                                     {
10602                                        strcat(templateString, param.name);
10603                                        strcat(templateString, " = ");
10604                                     }
10605                                     strcat(templateString, argument);
10606                                     paramCount++;
10607                                     lastParam = p;
10608                                  }
10609                               }
10610                               p++;
10611                            }
10612                         }
10613                         {
10614                            int len = strlen(templateString);
10615                            if(templateString[len-1] == '>') templateString[len++] = ' ';
10616                            templateString[len++] = '>';
10617                            templateString[len++] = '\0';
10618                         }
10619
10620                         FreeType(exp.expType);
10621                         {
10622                            Context context = SetupTemplatesContext(tClass);
10623                            exp.expType = ProcessTypeString(templateString, false);
10624                            FinishTemplatesContext(context);
10625                         }
10626                      }
10627                   }
10628                }
10629             }
10630             else
10631                Compiler_Error($"undefined class %s\n", (id && (!id._class || id._class.name))? (id.classSym ? id.classSym.string : (type._class ? type._class.string : null)) : "(null)");
10632          }
10633          else if(type && (type.kind == structType || type.kind == unionType))
10634          {
10635             Type memberType = exp.member.member ? FindMember(type, exp.member.member.string) : null;
10636             if(memberType)
10637             {
10638                exp.expType = memberType;
10639                if(memberType)
10640                   memberType.refCount++;
10641             }
10642          }
10643          else
10644          {
10645             char expString[10240];
10646             expString[0] = '\0';
10647             if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
10648             Compiler_Error($"member operator on non-structure type expression %s\n", expString);
10649          }
10650
10651          if(exp.expType && exp.expType.kind == thisClassType && (!exp.destType || exp.destType.kind != thisClassType))
10652          {
10653             if(type && (type.kind == classType || type.kind == subClassType || type.kind == intType || type.kind == enumType))
10654             {
10655                Identifier id = exp.member.member;
10656                Class _class = (id && (!id._class || id._class.name))? ( id.classSym ? id.classSym.registered : (type._class ? type._class.registered : null)) : null;
10657                if(_class)
10658                {
10659                   FreeType(exp.expType);
10660                   exp.expType = ReplaceThisClassType(_class);
10661                }
10662             }
10663          }
10664          yylloc = oldyylloc;
10665          break;
10666       }
10667       // Convert x->y into (*x).y
10668       case pointerExp:
10669       {
10670          Type destType = exp.destType;
10671
10672          // DOING THIS LATER NOW...
10673          if(exp.member.member && exp.member.member._class && exp.member.member._class.name)
10674          {
10675             exp.member.member.classSym = exp.member.member._class.symbol; // FindClass(exp.member.member._class.name);
10676             /* TODO: Name Space Fix ups
10677             if(!exp.member.member.classSym)
10678                exp.member.member.nameSpace = eSystem_FindNameSpace(privateModule, exp.member.member._class.name);
10679             */
10680          }
10681
10682          exp.member.exp = MkExpBrackets(MkListOne(MkExpOp(null, '*', exp.member.exp)));
10683          exp.type = memberExp;
10684          if(destType)
10685             destType.count++;
10686          ProcessExpressionType(exp);
10687          if(destType)
10688             destType.count--;
10689          break;
10690       }
10691       case classSizeExp:
10692       {
10693          //ComputeExpression(exp);
10694
10695          Symbol classSym = exp._class.symbol; // FindClass(exp._class.name);
10696          if(classSym && classSym.registered)
10697          {
10698             if(classSym.registered.type == noHeadClass || (classSym.registered.fixed && classSym.registered.structSize))
10699             {
10700                char name[1024];
10701                Class b = classSym.registered;
10702                name[0] = '\0';
10703                DeclareStruct(curExternal, classSym.string, false, true);
10704                FreeSpecifier(exp._class);
10705                FullClassNameCat(name, classSym.string, false);
10706
10707                if(b.offset == 0)
10708                {
10709                   exp.type = typeSizeExp;
10710                   exp.typeName = MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null);
10711                }
10712                else
10713                {
10714                   Expression e;
10715                   exp.type = opExp;
10716                   if(b.structSize == b.offset)
10717                      exp.op.exp1 = MkExpConstant("0");
10718                   else
10719                      exp.op.exp1 = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10720                   exp.op.op = '+';
10721                   e = exp;
10722                   while(b.offset != 0)
10723                   {
10724                      Symbol sym;
10725                      Expression typeSize;
10726
10727                      b = b.base;
10728                      sym = FindClass(b.fullName);
10729
10730                      name[0] = '\0';
10731                      DeclareStruct(curExternal, sym.string, false, true);
10732                      FullClassNameCat(name, sym.string, false);
10733
10734                      if(b.structSize == b.offset)
10735                         typeSize = MkExpConstant("0");
10736                      else
10737                         typeSize = MkExpTypeSize(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(name), null)), null));
10738                      e.op.exp2 = b.offset ? MkExpOp(typeSize, '+', null) : typeSize;
10739                      e = e.op.exp2;
10740                   }
10741                }
10742             }
10743             else
10744             {
10745                if(classSym.registered.fixed && !classSym.registered.structSize)
10746                {
10747                   FreeSpecifier(exp._class);
10748                   exp.constant = PrintUInt(classSym.registered.templateClass ? classSym.registered.templateClass.structSize : classSym.registered.structSize);
10749                   exp.type = constantExp;
10750                }
10751                else
10752                {
10753                   char className[1024];
10754                   strcpy(className, "__ecereClass_");
10755                   FullClassNameCat(className, classSym.string, true);
10756
10757                   DeclareClass(curExternal, classSym, className);
10758
10759                   FreeExpContents(exp);
10760                   exp.type = pointerExp;
10761                   exp.member.exp = MkExpIdentifier(MkIdentifier(className));
10762                   exp.member.member = MkIdentifier("structSize");
10763                }
10764             }
10765          }
10766
10767          exp.expType = Type
10768          {
10769             refCount = 1;
10770             kind = intSizeType;
10771          };
10772          // exp.isConstant = true;
10773          break;
10774       }
10775       case typeSizeExp:
10776       {
10777          Type type = ProcessType(exp.typeName.qualifiers, exp.typeName.declarator);
10778
10779          exp.expType = Type
10780          {
10781             refCount = 1;
10782             kind = intSizeType;
10783          };
10784          exp.isConstant = true;
10785
10786          DeclareType(curExternal, type, true, false);
10787          FreeType(type);
10788          break;
10789       }
10790       case castExp:
10791       {
10792          Type type = ProcessType(exp.cast.typeName.qualifiers, exp.cast.typeName.declarator);
10793          type.count = 1;
10794          FreeType(exp.cast.exp.destType);
10795          exp.cast.exp.destType = type;
10796          type.refCount++;
10797          type.casted = true;
10798          ProcessExpressionType(exp.cast.exp);
10799          type.casted = false;
10800          type.count = 0;
10801          exp.expType = type;
10802          //type.refCount++;
10803
10804          // if(!NeedCast(exp.cast.exp.expType, exp.cast.exp.destType))
10805          if(!exp.cast.exp.needCast && !NeedCast(exp.cast.exp.expType, type))
10806          {
10807             void * prev = exp.prev, * next = exp.next;
10808             Type expType = exp.cast.exp.destType;
10809             Expression castExp = exp.cast.exp;
10810             Type destType = exp.destType;
10811
10812             if(expType) expType.refCount++;
10813
10814             //FreeType(exp.destType);
10815             FreeType(exp.expType);
10816             FreeTypeName(exp.cast.typeName);
10817
10818             *exp = *castExp;
10819             FreeType(exp.expType);
10820             FreeType(exp.destType);
10821
10822             exp.expType = expType;
10823             exp.destType = destType;
10824
10825             delete castExp;
10826
10827             exp.prev = prev;
10828             exp.next = next;
10829
10830          }
10831          else
10832          {
10833             exp.isConstant = exp.cast.exp.isConstant;
10834          }
10835          //FreeType(type);
10836          break;
10837       }
10838       case extensionInitializerExp:
10839       {
10840          Type type = ProcessType(exp.initializer.typeName.qualifiers, exp.initializer.typeName.declarator);
10841          // We have yet to support this... ( { } initializers are currently processed inside ProcessDeclaration()'s initDeclaration case statement
10842          // ProcessInitializer(exp.initializer.initializer, type);
10843          exp.expType = type;
10844          break;
10845       }
10846       case vaArgExp:
10847       {
10848          Type type = ProcessType(exp.vaArg.typeName.qualifiers, exp.vaArg.typeName.declarator);
10849          ProcessExpressionType(exp.vaArg.exp);
10850          exp.expType = type;
10851          break;
10852       }
10853       case conditionExp:
10854       {
10855          Expression e;
10856          Type t = exp.destType;
10857          if(t && !exp.destType.casted)
10858          {
10859             t = { };
10860             CopyTypeInto(t, exp.destType);
10861             t.count = 0;
10862          }
10863          else if(t)
10864             t.refCount++;
10865
10866          exp.isConstant = true;
10867
10868          FreeType(exp.cond.cond.destType);
10869          exp.cond.cond.destType = MkClassType("bool");
10870          exp.cond.cond.destType.truth = true;
10871          ProcessExpressionType(exp.cond.cond);
10872          if(!exp.cond.cond.isConstant)
10873             exp.isConstant = false;
10874          for(e = exp.cond.exp->first; e; e = e.next)
10875          {
10876             if(!e.next)
10877             {
10878                FreeType(e.destType);
10879                e.destType = t;
10880                if(e.destType) e.destType.refCount++;
10881             }
10882             ProcessExpressionType(e);
10883             if(!e.next)
10884             {
10885                exp.expType = e.expType;
10886                if(e.expType) e.expType.refCount++;
10887             }
10888             if(!e.isConstant)
10889                exp.isConstant = false;
10890          }
10891
10892          FreeType(exp.cond.elseExp.destType);
10893          // Added this check if we failed to find an expType
10894          // exp.cond.elseExp.destType = exp.expType ? exp.expType : exp.destType;
10895
10896          // Reversed it...
10897          exp.cond.elseExp.destType = t ? t : exp.expType;
10898
10899          if(exp.cond.elseExp.destType)
10900             exp.cond.elseExp.destType.refCount++;
10901          ProcessExpressionType(exp.cond.elseExp);
10902
10903          // FIXED THIS: Was done before calling process on elseExp
10904          if(!exp.cond.elseExp.isConstant)
10905             exp.isConstant = false;
10906
10907          FreeType(t);
10908          break;
10909       }
10910       case extensionCompoundExp:
10911       {
10912          if(exp.compound && exp.compound.compound.statements && exp.compound.compound.statements->last)
10913          {
10914             Statement last = exp.compound.compound.statements->last;
10915             if(last.type == expressionStmt && last.expressions && last.expressions->last)
10916             {
10917                ((Expression)last.expressions->last).destType = exp.destType;
10918                if(exp.destType)
10919                   exp.destType.refCount++;
10920             }
10921             ProcessStatement(exp.compound);
10922             exp.expType = (last.expressions && last.expressions->last) ? ((Expression)last.expressions->last).expType : null;
10923             if(exp.expType)
10924                exp.expType.refCount++;
10925          }
10926          break;
10927       }
10928       case classExp:
10929       {
10930          Specifier spec = exp._classExp.specifiers->first;
10931          if(spec && spec.type == nameSpecifier)
10932          {
10933             exp.expType = MkClassType(spec.name);
10934             exp.expType.kind = subClassType;
10935             exp.byReference = true;
10936          }
10937          else
10938          {
10939             exp.expType = MkClassType("ecere::com::Class");
10940             exp.byReference = true;
10941          }
10942          break;
10943       }
10944       case classDataExp:
10945       {
10946          Class _class = thisClass ? thisClass : currentClass;
10947          if(_class)
10948          {
10949             Identifier id = exp.classData.id;
10950             char structName[1024];
10951             Expression classExp;
10952             strcpy(structName, "__ecereClassData_");
10953             FullClassNameCat(structName, _class.fullName, false);
10954             exp.type = pointerExp;
10955             exp.member.member = id;
10956             if(curCompound && FindSymbol("this", curContext, curCompound.compound.context, false, false))
10957                classExp = MkExpMember(MkExpIdentifier(MkIdentifier("this")), MkIdentifier("_class"));
10958             else
10959                classExp = MkExpIdentifier(MkIdentifier("class"));
10960
10961             exp.member.exp = MkExpBrackets(MkListOne(MkExpCast(
10962                MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)),
10963                   MkExpBrackets(MkListOne(MkExpOp(
10964                      MkExpCast(MkTypeName(MkListOne(MkSpecifier(CHAR)), MkDeclaratorPointer(MkPointer(null,null), null)),
10965                         MkExpMember(classExp, MkIdentifier("data"))), '+',
10966                            MkExpMember(MkExpClass(MkListOne(MkSpecifierName(_class.fullName)), null), MkIdentifier("offsetClass")))))
10967                      )));
10968
10969             ProcessExpressionType(exp);
10970             return;
10971          }
10972          break;
10973       }
10974       case arrayExp:
10975       {
10976          Type type = null;
10977          const char * typeString = null;
10978          char typeStringBuf[1024];
10979          if(exp.destType && exp.destType.kind == classType && exp.destType._class && exp.destType._class.registered &&
10980             exp.destType._class.registered != containerClass && eClass_IsDerived(exp.destType._class.registered, containerClass))
10981          {
10982             Class templateClass = exp.destType._class.registered;
10983             typeString = templateClass.templateArgs[2].dataTypeString;
10984          }
10985          else if(exp.list)
10986          {
10987             // Guess type from expressions in the array
10988             Expression e;
10989             for(e = exp.list->first; e; e = e.next)
10990             {
10991                ProcessExpressionType(e);
10992                if(e.expType)
10993                {
10994                   if(!type) { type = e.expType; type.refCount++; }
10995                   else
10996                   {
10997                      // if(!MatchType(e.expType, type, null, null, null, false, false, false))
10998                      if(!MatchTypeExpression(e, type, null, false, true))
10999                      {
11000                         FreeType(type);
11001                         type = e.expType;
11002                         e.expType = null;
11003
11004                         e = exp.list->first;
11005                         ProcessExpressionType(e);
11006                         if(e.expType)
11007                         {
11008                            //if(!MatchTypes(e.expType, type, null, null, null, false, false, false))
11009                            if(!MatchTypeExpression(e, type, null, false, true))
11010                            {
11011                               FreeType(e.expType);
11012                               e.expType = null;
11013                               FreeType(type);
11014                               type = null;
11015                               break;
11016                            }
11017                         }
11018                      }
11019                   }
11020                   if(e.expType)
11021                   {
11022                      FreeType(e.expType);
11023                      e.expType = null;
11024                   }
11025                }
11026             }
11027             if(type)
11028             {
11029                typeStringBuf[0] = '\0';
11030                PrintTypeNoConst(type, typeStringBuf, false, true);
11031                typeString = typeStringBuf;
11032                FreeType(type);
11033                type = null;
11034             }
11035          }
11036          if(typeString)
11037          {
11038             /*
11039             (Container)& (struct BuiltInContainer)
11040             {
11041                ._vTbl = class(BuiltInContainer)._vTbl,
11042                ._class = class(BuiltInContainer),
11043                .refCount = 0,
11044                .data = (int[]){ 1, 7, 3, 4, 5 },
11045                .count = 5,
11046                .type = class(int),
11047             }
11048             */
11049             char templateString[1024];
11050             OldList * initializers = MkList();
11051             OldList * structInitializers = MkList();
11052             OldList * specs = MkList();
11053             Expression expExt;
11054             Declarator decl = SpecDeclFromString(typeString, specs, null);
11055             sprintf(templateString, "Container<%s>", typeString);
11056
11057             if(exp.list)
11058             {
11059                Expression e;
11060                type = ProcessTypeString(typeString, false);
11061                while((e = exp.list->first))
11062                {
11063                   exp.list->Remove(e);
11064                   e.destType = type;
11065                   type.refCount++;
11066                   ProcessExpressionType(e);
11067                   ListAdd(initializers, MkInitializerAssignment(e));
11068                }
11069                FreeType(type);
11070                delete exp.list;
11071             }
11072
11073             DeclareStruct(curExternal, "ecere::com::BuiltInContainer", false, true);
11074
11075             ListAdd(structInitializers, /*MkIdentifier("_vTbl")*/    MkInitializerAssignment(MkExpMember(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null), MkIdentifier("_vTbl"))));
11076                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11077             ListAdd(structInitializers, /*MkIdentifier("_class")*/   MkInitializerAssignment(MkExpClass(MkListOne(MkSpecifierName("BuiltInContainer")), null)));
11078                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11079             ListAdd(structInitializers, /*MkIdentifier("_refCount")*/MkInitializerAssignment(MkExpConstant("0")));
11080                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11081             ListAdd(structInitializers, /*MkIdentifier("data")*/     MkInitializerAssignment(MkExpExtensionInitializer(
11082                MkTypeName(specs, MkDeclaratorArray(decl, null)),
11083                MkInitializerList(initializers))));
11084                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11085             ListAdd(structInitializers, /*MkIdentifier("count")*/    MkInitializerAssignment({ type = constantExp, constant = PrintString(initializers->count) }));
11086                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11087             ListAdd(structInitializers, /*MkIdentifier("type")*/     MkInitializerAssignment(MkExpClass(CopyList(specs, CopySpecifier), CopyDeclarator(decl))));
11088                ProcessExpressionType(((Initializer)structInitializers->last).exp);
11089             exp.expType = ProcessTypeString(templateString, false);
11090             exp.type = bracketsExp;
11091             exp.list = MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName(templateString)), null),
11092                MkExpOp(null, '&',
11093                expExt = MkExpExtensionInitializer(MkTypeName(MkListOne(MkSpecifierName("BuiltInContainer")), null),
11094                   MkInitializerList(structInitializers)))));
11095             ProcessExpressionType(expExt);
11096          }
11097          else
11098          {
11099             exp.expType = ProcessTypeString("Container", false);
11100             Compiler_Error($"Couldn't determine type of array elements\n");
11101          }
11102          break;
11103       }
11104    }
11105
11106    if(exp.expType && exp.expType.kind == thisClassType && thisClass && (!exp.destType || exp.destType.kind != thisClassType))
11107    {
11108       FreeType(exp.expType);
11109       exp.expType = ReplaceThisClassType(thisClass);
11110    }
11111
11112    // Resolve structures here
11113    if(exp.expType && (exp.expType.kind == structType || exp.expType.kind == unionType || exp.expType.kind == enumType) && !exp.expType.members.first && exp.expType.enumName)
11114    {
11115       Symbol symbol = FindSymbol(exp.expType.enumName, curContext, globalContext, true, false);
11116       // TODO: Fix members reference...
11117       if(symbol)
11118       {
11119          if(exp.expType.kind != enumType)
11120          {
11121             Type member;
11122             String enumName = CopyString(exp.expType.enumName);
11123
11124             // Fixed a memory leak on self-referencing C structs typedefs
11125             // by instantiating a new type rather than simply copying members
11126             // into exp.expType
11127             FreeType(exp.expType);
11128             exp.expType = Type { };
11129             exp.expType.kind = symbol.type.kind;
11130             exp.expType.refCount++;
11131             exp.expType.enumName = enumName;
11132
11133             exp.expType.members = symbol.type.members;
11134             for(member = symbol.type.members.first; member; member = member.next)
11135                member.refCount++;
11136          }
11137          else
11138          {
11139             NamedLink64 member;
11140             for(member = symbol.type.members.first; member; member = member.next)
11141             {
11142                NamedLink64 value { name = CopyString(member.name) };
11143                exp.expType.members.Add(value);
11144             }
11145          }
11146       }
11147    }
11148
11149    yylloc = exp.loc;
11150    if(exp.destType && (/*exp.destType.kind == voidType || */exp.destType.kind == dummyType) );
11151    else if(exp.destType && !exp.destType.keepCast)
11152    {
11153       if(!exp.needTemplateCast && exp.expType && (exp.expType.kind == templateType || exp.expType.passAsTemplate)) // && exp.destType && !exp.destType.passAsTemplate)
11154          exp.needTemplateCast = 1;
11155
11156       if(exp.destType.kind == voidType);
11157       else if(!CheckExpressionType(exp, exp.destType, false, !exp.destType.casted))
11158       {
11159          // Warn for casting unrelated types to/from struct classes
11160          bool invalidCast = false;
11161          if(inCompiler && exp.destType.count && exp.expType)
11162          {
11163             Class c1 = (exp.expType.kind == classType && exp.expType._class) ? exp.expType._class.registered : null;
11164             Class c2 = (exp.destType.kind == classType && exp.destType._class) ? exp.destType._class.registered : null;
11165             if(c1 && c1.type != structClass) c1 = null;
11166             if(c2 && c2.type != structClass) c2 = null;
11167             if((c1 && !exp.expType.byReference && !c2 && !exp.destType.isPointerType) || (c2 && !exp.destType.byReference && !c1 && !exp.expType.isPointerType))
11168                invalidCast = true;
11169          }
11170          if(!exp.destType.count || unresolved || invalidCast)
11171          {
11172             if(!exp.expType)
11173             {
11174                yylloc = exp.loc;
11175                if(exp.destType.kind != ellipsisType)
11176                {
11177                   char type2[1024];
11178                   type2[0] = '\0';
11179                   if(inCompiler)
11180                   {
11181                      char expString[10240];
11182                      expString[0] = '\0';
11183
11184                      PrintType(exp.destType, type2, false, true);
11185
11186                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11187                      if(unresolved)
11188                         Compiler_Error($"unresolved identifier %s; expected %s\n", expString, type2);
11189                      else if(exp.type != dummyExp)
11190                         Compiler_Error($"couldn't determine type of %s; expected %s\n", expString, type2);
11191                   }
11192                }
11193                else
11194                {
11195                   char expString[10240] ;
11196                   expString[0] = '\0';
11197                   if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11198
11199                   if(unresolved)
11200                      Compiler_Error($"unresolved identifier %s\n", expString);
11201                   else if(exp.type != dummyExp)
11202                      Compiler_Error($"couldn't determine type of %s\n", expString);
11203                }
11204             }
11205             else
11206             {
11207                char type1[1024];
11208                char type2[1024];
11209                type1[0] = '\0';
11210                type2[0] = '\0';
11211                if(inCompiler)
11212                {
11213                   PrintType(exp.expType, type1, false, true);
11214                   PrintType(exp.destType, type2, false, true);
11215                }
11216
11217                //CheckExpressionType(exp, exp.destType, false);
11218
11219                if(exp.destType.truth && exp.destType._class && exp.destType._class.registered && !strcmp(exp.destType._class.registered.name, "bool") &&
11220                   exp.expType.kind != voidType && exp.expType.kind != structType && exp.expType.kind != unionType &&
11221                   (exp.expType.kind != classType || exp.expType.classObjectType || (exp.expType._class && exp.expType._class.registered && exp.expType._class.registered.type != structClass)));
11222                else
11223                {
11224                   Expression nbExp = GetNonBracketsExp(exp);
11225                   bool skipWarning = false;
11226                   TypeKind kind = exp.destType.kind;
11227                   if(nbExp.type == conditionExp && !nbExp.destType.casted && nbExp.destType.kind == exp.destType.kind)
11228                      // The if/else operands have already been checked / warned about
11229                      skipWarning = true;
11230                   if((kind == charType || kind == shortType) && exp.destType.isSigned == exp.expType.signedBeforePromotion && nbExp.type == opExp && nbExp.op.exp1 && nbExp.op.exp2)
11231                   {
11232                      int op = nbExp.op.op;
11233                      Expression nbExp1, nbExp2;
11234                      TypeKind from;
11235
11236                      switch(op)
11237                      {
11238                         case '%': case '/':
11239                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11240                            from = nbExp1.expType.promotedFrom;
11241                            // Division and Modulo will not take more room than type before promotion
11242                            if(from == charType || (kind == shortType && from == shortType))
11243                               skipWarning = true;
11244                            break;
11245                         // Left shift
11246                         case LEFT_OP: case RIGHT_OP:
11247                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11248                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11249                            from = nbExp1.expType.promotedFrom;
11250                            // Right shift will not take more room than type before promotion
11251                            if(op == RIGHT_OP && (from == charType || (kind == shortType && from == shortType)))
11252                               skipWarning = true;
11253                            else if(nbExp2.isConstant && nbExp2.type == constantExp && (nbExp.op.op == RIGHT_OP || nbExp1.expType.bitMemberSize))
11254                            {
11255                               int n = (int)strtol(nbExp2.constant, null, 0);
11256                               int s = from == charType ? 8 : 16;
11257                               // Left shifting a bit member constrained in size may still fit in type before promotion
11258                               if(nbExp1.expType.bitMemberSize && nbExp1.expType.bitMemberSize < s)
11259                                  s = nbExp1.expType.bitMemberSize;
11260
11261                               // If right shifted enough things will fit in smaller type
11262                               if(nbExp.op.op == RIGHT_OP)
11263                                  s -= n;
11264                               else
11265                                  s += n;
11266                               if(s <= (kind == charType ? 8 : 16))
11267                                  skipWarning = true;
11268                            }
11269                            break;
11270                         case '-':
11271                            if(!exp.destType.isSigned)
11272                            {
11273                               nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11274                               nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11275                               from = nbExp2.expType.promotedFrom;
11276                               // Max value of unsigned type before promotion minus the same will always fit
11277                               if((from == charType || from == shortType) && nbExp1.isConstant && nbExp1.type == constantExp)
11278                               {
11279                                  int n = (int)strtol(nbExp1.constant, null, 0);
11280                                  if(n == (from == charType ? 255 : 65535))
11281                                     skipWarning = true;
11282                               }
11283                            }
11284                            break;
11285                         case '|':
11286                         {
11287                            TypeKind kind1, kind2;
11288                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11289                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11290                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11291                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11292                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) &&
11293                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11294                               skipWarning = true;
11295                            break;
11296                         }
11297                         case '&':
11298                         {
11299                            TypeKind kind1, kind2;
11300                            nbExp1 = GetNonBracketsExp(nbExp.op.exp1);
11301                            nbExp2 = GetNonBracketsExp(nbExp.op.exp2);
11302                            kind1 = nbExp1.expType.promotedFrom ? nbExp1.expType.promotedFrom : nbExp1.expType.kind;
11303                            kind2 = nbExp2.expType.promotedFrom ? nbExp2.expType.promotedFrom : nbExp2.expType.kind;
11304                            if(((kind1 == charType || (kind1 == shortType && kind == shortType)) || MatchTypeExpression(nbExp1, exp.destType, null, false, false)) ||
11305                               ((kind2 == charType || (kind2 == shortType && kind == shortType)) || MatchTypeExpression(nbExp2, exp.destType, null, false, false)))
11306                               skipWarning = true;
11307                            break;
11308                         }
11309                      }
11310                   }
11311
11312                   if(!skipWarning)
11313                   {
11314                      char expString[10240];
11315                      expString[0] = '\0';
11316                      if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11317
11318 #ifdef _DEBUG
11319                      CheckExpressionType(exp, exp.destType, false, true);
11320 #endif
11321
11322                      // Flex & Bison generate code that triggers this, so we ignore it for a quiet sdk build:
11323                      if(!sourceFile || (!strstr(sourceFile, "src\\lexer.ec") && !strstr(sourceFile, "src/lexer.ec") &&
11324                                         !strstr(sourceFile, "src\\grammar.ec") && !strstr(sourceFile, "src/grammar.ec") &&
11325                                         !strstr(sourceFile, "src\\type.ec") && !strstr(sourceFile, "src/type.ec") &&
11326                                         !strstr(sourceFile, "src\\expression.ec") && !strstr(sourceFile, "src/expression.ec")))
11327                      {
11328                         if(invalidCast)
11329                            Compiler_Error($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11330                         else
11331                            Compiler_Warning($"incompatible expression %s (%s); expected %s\n", expString, type1, type2);
11332                      }
11333                   }
11334
11335                   // TO CHECK: FORCING HERE TO HELP DEBUGGER
11336                   if(!inCompiler)
11337                   {
11338                      FreeType(exp.expType);
11339                      exp.destType.refCount++;
11340                      exp.expType = exp.destType;
11341                   }
11342                }
11343             }
11344          }
11345       }
11346       // Cast function pointers to void * as eC already checked compatibility
11347       else if(exp.destType && exp.destType.kind == pointerType && exp.destType.type && exp.destType.type.kind == functionType &&
11348               exp.expType && (exp.expType.kind == functionType || exp.expType.kind == methodType))
11349       {
11350          Expression nbExp = GetNonBracketsExp(exp);
11351          if(nbExp.type != castExp || !IsVoidPtrCast(nbExp.cast.typeName))
11352          {
11353             Expression e = MoveExpContents(exp);
11354             exp.cast.exp = MkExpBrackets(MkListOne(e));
11355             exp.type = castExp;
11356             exp.cast.exp.destType = exp.destType;
11357             if(exp.destType) exp.destType.refCount++;
11358             exp.cast.typeName = MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null));
11359          }
11360       }
11361    }
11362    else if(unresolved)
11363    {
11364       if(exp.identifier._class && exp.identifier._class.name)
11365          Compiler_Error($"unresolved identifier %s::%s\n", exp.identifier._class.name, exp.identifier.string);
11366       else if(exp.identifier.string && exp.identifier.string[0])
11367          Compiler_Error($"unresolved identifier %s\n", exp.identifier.string);
11368    }
11369    else if(!exp.expType && exp.type != dummyExp)
11370    {
11371       char expString[10240];
11372       expString[0] = '\0';
11373       if(inCompiler) { PrintExpression(exp, expString); ChangeCh(expString, '\n', ' '); }
11374       Compiler_Error($"couldn't determine type of %s\n", expString);
11375    }
11376
11377    // Let's try to support any_object & typed_object here:
11378    if(inCompiler)
11379       ApplyAnyObjectLogic(exp);
11380
11381    // Mark nohead classes as by reference, unless we're casting them to an integral type
11382    if(!notByReference && exp.expType && exp.expType.kind == classType && exp.expType._class && exp.expType._class.registered &&
11383       exp.expType._class.registered.type == noHeadClass && (!exp.destType ||
11384          (exp.destType.kind != intType && exp.destType.kind != int64Type && exp.destType.kind != intPtrType && exp.destType.kind != intSizeType &&
11385           exp.destType.kind != longType && exp.destType.kind != shortType && exp.destType.kind != charType && exp.destType.kind != _BoolType)))
11386    {
11387       exp.byReference = true;
11388    }
11389    yylloc = oldyylloc;
11390 }
11391
11392 static void FindNextDataMember(Class _class, Class * curClass, DataMember * curMember, DataMember * subMemberStack, int * subMemberStackPos)
11393 {
11394    // THIS CODE WILL FIND NEXT MEMBER...
11395    if(*curMember)
11396    {
11397       *curMember = (*curMember).next;
11398
11399       if(subMemberStackPos && *subMemberStackPos > 0 && subMemberStack[*subMemberStackPos-1].type == unionMember)
11400       {
11401          *curMember = subMemberStack[--(*subMemberStackPos)];
11402          *curMember = (*curMember).next;
11403       }
11404
11405       // SKIP ALL PROPERTIES HERE...
11406       while((*curMember) && (*curMember).isProperty)
11407          *curMember = (*curMember).next;
11408
11409       if(subMemberStackPos)
11410       {
11411          while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11412          {
11413             subMemberStack[(*subMemberStackPos)++] = *curMember;
11414
11415             *curMember = (*curMember).members.first;
11416             while(*curMember && (*curMember).isProperty)
11417                *curMember = (*curMember).next;
11418          }
11419       }
11420    }
11421    while(!*curMember)
11422    {
11423       if(!*curMember)
11424       {
11425          if(subMemberStackPos && *subMemberStackPos)
11426          {
11427             *curMember = subMemberStack[--(*subMemberStackPos)];
11428             *curMember = (*curMember).next;
11429          }
11430          else
11431          {
11432             Class lastCurClass = *curClass;
11433
11434             if(*curClass == _class) break;     // REACHED THE END
11435
11436             for(*curClass = _class; (*curClass).base != lastCurClass && (*curClass).base.type != systemClass; *curClass = (*curClass).base);
11437             *curMember = (*curClass).membersAndProperties.first;
11438          }
11439
11440          while((*curMember) && (*curMember).isProperty)
11441             *curMember = (*curMember).next;
11442          if(subMemberStackPos)
11443          {
11444             while((*curMember) && !(*curMember).isProperty && !(*curMember).name && ((*curMember).type == structMember || (*curMember).type == unionMember))
11445             {
11446                subMemberStack[(*subMemberStackPos)++] = *curMember;
11447
11448                *curMember = (*curMember).members.first;
11449                while(*curMember && (*curMember).isProperty)
11450                   *curMember = (*curMember).next;
11451             }
11452          }
11453       }
11454    }
11455 }
11456
11457
11458 static void ProcessInitializer(Initializer init, Type type)
11459 {
11460    switch(init.type)
11461    {
11462       case expInitializer:
11463          if(!init.exp || init.exp.type != instanceExp || !init.exp.instance || init.exp.instance._class || !type || type.kind == classType)
11464          {
11465             // TESTING THIS FOR SHUTTING = 0 WARNING
11466             if(init.exp && !init.exp.destType)
11467             {
11468                FreeType(init.exp.destType);
11469                init.exp.destType = type;
11470                if(type) type.refCount++;
11471             }
11472             if(init.exp)
11473             {
11474                ProcessExpressionType(init.exp);
11475                init.isConstant = init.exp.isConstant;
11476             }
11477             break;
11478          }
11479          else
11480          {
11481             Expression exp = init.exp;
11482             Instantiation inst = exp.instance;
11483             MembersInit members;
11484
11485             init.type = listInitializer;
11486             init.list = MkList();
11487
11488             if(inst.members)
11489             {
11490                for(members = inst.members->first; members; members = members.next)
11491                {
11492                   if(members.type == dataMembersInit)
11493                   {
11494                      MemberInit member;
11495                      for(member = members.dataMembers->first; member; member = member.next)
11496                      {
11497                         ListAdd(init.list, member.initializer);
11498                         member.initializer = null;
11499                      }
11500                   }
11501                   // Discard all MembersInitMethod
11502                }
11503             }
11504             FreeExpression(exp);
11505          }
11506       case listInitializer:
11507       {
11508          Initializer i;
11509          Type initializerType = null;
11510          Class curClass = null;
11511          DataMember curMember = null;
11512          DataMember subMemberStack[256];
11513          int subMemberStackPos = 0;
11514
11515          if(type && type.kind == arrayType)
11516             initializerType = Dereference(type);
11517          else if(type && (type.kind == structType || type.kind == unionType))
11518             initializerType = type.members.first;
11519
11520          for(i = init.list->first; i; i = i.next)
11521          {
11522             if(type && type.kind == classType && type._class && type._class.registered)
11523             {
11524                // 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)
11525                FindNextDataMember(type._class.registered, &curClass, &curMember, subMemberStack, &subMemberStackPos);
11526                // TODO: Generate error on initializing a private data member this way from another module...
11527                if(curMember)
11528                {
11529                   if(!curMember.dataType)
11530                      curMember.dataType = ProcessTypeString(curMember.dataTypeString, false);
11531                   initializerType = curMember.dataType;
11532                }
11533             }
11534             ProcessInitializer(i, initializerType);
11535             if(initializerType && type && (type.kind == structType || type.kind == unionType))
11536                initializerType = initializerType.next;
11537             if(!i.isConstant)
11538                init.isConstant = false;
11539          }
11540
11541          if(type && type.kind == arrayType)
11542             FreeType(initializerType);
11543
11544          if(type && type.kind != arrayType && type.kind != structType && type.kind != unionType && (type.kind != classType || !type._class.registered || type._class.registered.type != structClass))
11545          {
11546             Compiler_Error($"Assigning list initializer to non list\n");
11547          }
11548          break;
11549       }
11550    }
11551 }
11552
11553 static void ProcessSpecifier(Specifier spec, bool declareStruct, bool warnClasses)
11554 {
11555    switch(spec.type)
11556    {
11557       case baseSpecifier:
11558       {
11559          if(spec.specifier == THISCLASS)
11560          {
11561             if(thisClass)
11562             {
11563                spec.type = nameSpecifier;
11564                spec.name = ReplaceThisClass(thisClass);
11565                spec.symbol = FindClass(spec.name);
11566                ProcessSpecifier(spec, declareStruct, false);
11567             }
11568          }
11569          break;
11570       }
11571       case nameSpecifier:
11572       {
11573          Symbol symbol = FindType(curContext, spec.name);
11574          if(symbol)
11575             DeclareType(curExternal, symbol.type, true, true);
11576          else if(spec.symbol /*&& declareStruct*/)
11577          {
11578             Class c = spec.symbol.registered;
11579             if(warnClasses && !c)
11580                Compiler_Warning("Undeclared class %s\n", spec.name);
11581             DeclareStruct(curExternal, spec.name, c && c.type == noHeadClass, declareStruct && c && c.type == structClass);
11582          }
11583          break;
11584       }
11585       case enumSpecifier:
11586       {
11587          Enumerator e;
11588          if(spec.list)
11589          {
11590             for(e = spec.list->first; e; e = e.next)
11591             {
11592                if(e.exp)
11593                   ProcessExpressionType(e.exp);
11594             }
11595          }
11596          // Fall through for IDE type processing
11597          if(inCompiler)
11598             break;
11599       }
11600       case structSpecifier:
11601       case unionSpecifier:
11602       {
11603          if(spec.definitions)
11604          {
11605             //ClassDef def;
11606             Symbol symbol = spec.id ? FindClass(spec.id.string) : null;
11607             //if(symbol)
11608                ProcessClass(spec.definitions, symbol);
11609             /*else
11610             {
11611                for(def = spec.definitions->first; def; def = def.next)
11612                {
11613                   //if(def.type == declarationClassDef && def.decl && def.decl.type == DeclarationStruct)
11614                      ProcessDeclaration(def.decl);
11615                }
11616             }*/
11617          }
11618          break;
11619       }
11620       /*
11621       case classSpecifier:
11622       {
11623          Symbol classSym = FindClass(spec.name);
11624          if(classSym && classSym.registered && classSym.registered.type == structClass)
11625             DeclareStruct(spec.name, false, true);
11626          break;
11627       }
11628       */
11629    }
11630 }
11631
11632
11633 static void ProcessDeclarator(Declarator decl, bool isFunction)
11634 {
11635    switch(decl.type)
11636    {
11637       case identifierDeclarator:
11638          if(decl.identifier.classSym /* TODO: Name Space Fix ups  || decl.identifier.nameSpace*/)
11639          {
11640             FreeSpecifier(decl.identifier._class);
11641             decl.identifier._class = null;
11642          }
11643          break;
11644       case arrayDeclarator:
11645          if(decl.array.exp)
11646             ProcessExpressionType(decl.array.exp);
11647       case structDeclarator:
11648       case bracketsDeclarator:
11649       case functionDeclarator:
11650       case pointerDeclarator:
11651       case extendedDeclarator:
11652       case extendedDeclaratorEnd:
11653       {
11654          Identifier id = null;
11655          Specifier classSpec = null;
11656          if(decl.type == functionDeclarator)
11657          {
11658             id = GetDeclId(decl);
11659             if(id && id._class)
11660             {
11661                classSpec = id._class;
11662                id._class = null;
11663             }
11664          }
11665          if(decl.declarator)
11666             ProcessDeclarator(decl.declarator, isFunction);
11667          if(decl.type == functionDeclarator)
11668          {
11669             if(classSpec)
11670             {
11671                TypeName param
11672                {
11673                   qualifiers = MkListOne(classSpec);
11674                   declarator = null;
11675                };
11676                if(!decl.function.parameters)
11677                   decl.function.parameters = MkList();
11678                decl.function.parameters->Insert(null, param);
11679             }
11680             if(decl.function.parameters)
11681             {
11682                TypeName param;
11683
11684                for(param = decl.function.parameters->first; param; param = param.next)
11685                {
11686                   if(param.qualifiers)
11687                   {
11688                      Specifier spec;
11689                      for(spec = param.qualifiers->first; spec; spec = spec.next)
11690                      {
11691                         if(spec.type == baseSpecifier)
11692                         {
11693                            if(spec.specifier == TYPED_OBJECT)
11694                            {
11695                               Declarator d = param.declarator;
11696                               TypeName newParam
11697                               {
11698                                  qualifiers = MkListOne(MkSpecifier(VOID));
11699                                  declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11700                               };
11701                               if(d.type != pointerDeclarator)
11702                                  newParam.qualifiers->Insert(null, MkSpecifier(CONST));
11703
11704                               FreeList(param.qualifiers, FreeSpecifier);
11705
11706                               param.qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
11707                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
11708
11709                               DeclareStruct(curExternal, "ecere::com::Class", false, true);
11710
11711                               decl.function.parameters->Insert(param, newParam);
11712                               param = newParam;
11713                               break;
11714                            }
11715                            else if(spec.specifier == ANY_OBJECT)
11716                            {
11717                               Declarator d = param.declarator;
11718
11719                               FreeList(param.qualifiers, FreeSpecifier);
11720
11721                               param.qualifiers = MkListOne(MkSpecifier(VOID));
11722                               if(d.type != pointerDeclarator)
11723                                  param.qualifiers->Insert(null, MkSpecifier(CONST));
11724                               param.declarator = MkDeclaratorPointer(MkPointer(null,null), d);
11725                               break;
11726                            }
11727                            else if(spec.specifier == THISCLASS)
11728                            {
11729                               if(thisClass)
11730                               {
11731                                  spec.type = nameSpecifier;
11732                                  spec.name = ReplaceThisClass(thisClass);
11733                                  spec.symbol = FindClass(spec.name);
11734                                  ProcessSpecifier(spec, false, false);
11735                               }
11736                               break;
11737                            }
11738                         }
11739                         else if(spec.type == nameSpecifier)
11740                         {
11741                            ProcessSpecifier(spec, isFunction, true);
11742                         }
11743                      }
11744                   }
11745
11746                   if(param.declarator)
11747                      ProcessDeclarator(param.declarator, false);
11748                }
11749             }
11750          }
11751          break;
11752       }
11753    }
11754 }
11755
11756 static void ProcessDeclaration(Declaration decl, bool warnClasses)
11757 {
11758    yylloc = decl.loc;
11759    switch(decl.type)
11760    {
11761       case initDeclaration:
11762       {
11763          bool declareStruct = false;
11764          /*
11765          lineNum = decl.pos.line;
11766          column = decl.pos.col;
11767          */
11768
11769          if(decl.declarators)
11770          {
11771             InitDeclarator d;
11772
11773             for(d = decl.declarators->first; d; d = d.next)
11774             {
11775                Type type, subType;
11776                ProcessDeclarator(d.declarator, false);
11777
11778                type = ProcessType(decl.specifiers, d.declarator);
11779
11780                if(d.initializer)
11781                {
11782                   ProcessInitializer(d.initializer, type);
11783
11784                   // Change "ColorRGB a = ColorRGB { 1,2,3 } => ColorRGB a { 1,2,3 }
11785
11786                   if(decl.declarators->count == 1 && d.initializer.type == expInitializer &&
11787                      d.initializer.exp.type == instanceExp)
11788                   {
11789                      if(type.kind == classType && type._class ==
11790                         d.initializer.exp.expType._class)
11791                      {
11792                         Instantiation inst = d.initializer.exp.instance;
11793                         inst.exp = MkExpIdentifier(CopyIdentifier(GetDeclId(d.declarator)));
11794
11795                         d.initializer.exp.instance = null;
11796                         if(decl.specifiers)
11797                            FreeList(decl.specifiers, FreeSpecifier);
11798                         FreeList(decl.declarators, FreeInitDeclarator);
11799
11800                         d = null;
11801
11802                         decl.type = instDeclaration;
11803                         decl.inst = inst;
11804                      }
11805                   }
11806                }
11807                for(subType = type; subType;)
11808                {
11809                   if(subType.kind == classType)
11810                   {
11811                      declareStruct = true;
11812                      break;
11813                   }
11814                   else if(subType.kind == pointerType)
11815                      break;
11816                   else if(subType.kind == arrayType)
11817                      subType = subType.arrayType;
11818                   else
11819                      break;
11820                }
11821
11822                FreeType(type);
11823                if(!d) break;
11824             }
11825          }
11826
11827          if(decl.specifiers)
11828          {
11829             Specifier s;
11830             for(s = decl.specifiers->first; s; s = s.next)
11831             {
11832                ProcessSpecifier(s, declareStruct, true);
11833             }
11834          }
11835          break;
11836       }
11837       case instDeclaration:
11838       {
11839          ProcessInstantiationType(decl.inst);
11840          break;
11841       }
11842       case structDeclaration:
11843       {
11844          Specifier spec;
11845          Declarator d;
11846          bool declareStruct = false;
11847
11848          if(decl.declarators)
11849          {
11850             for(d = decl.declarators->first; d; d = d.next)
11851             {
11852                Type type = ProcessType(decl.specifiers, d.declarator);
11853                Type subType;
11854                ProcessDeclarator(d, false);
11855                for(subType = type; subType;)
11856                {
11857                   if(subType.kind == classType)
11858                   {
11859                      declareStruct = true;
11860                      break;
11861                   }
11862                   else if(subType.kind == pointerType)
11863                      break;
11864                   else if(subType.kind == arrayType)
11865                      subType = subType.arrayType;
11866                   else
11867                      break;
11868                }
11869                FreeType(type);
11870             }
11871          }
11872          if(decl.specifiers)
11873          {
11874             for(spec = decl.specifiers->first; spec; spec = spec.next)
11875                ProcessSpecifier(spec, declareStruct, warnClasses);
11876          }
11877          break;
11878       }
11879    }
11880 }
11881
11882 static FunctionDefinition curFunction;
11883
11884 static void CreateFireWatcher(Property prop, Expression object, Statement stmt)
11885 {
11886    char propName[1024], propNameM[1024];
11887    char getName[1024], setName[1024];
11888    OldList * args;
11889
11890    DeclareProperty(curExternal, prop, setName, getName);
11891
11892    // eInstance_FireWatchers(object, prop);
11893    strcpy(propName, "__ecereProp_");
11894    FullClassNameCat(propName, prop._class.fullName, false);
11895    strcat(propName, "_");
11896    FullClassNameCat(propName, prop.name, true);
11897
11898    strcpy(propNameM, "__ecerePropM_");
11899    FullClassNameCat(propNameM, prop._class.fullName, false);
11900    strcat(propNameM, "_");
11901    FullClassNameCat(propNameM, prop.name, true);
11902
11903    if(prop.isWatchable)
11904    {
11905       args = MkList();
11906       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11907       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11908       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11909
11910       args = MkList();
11911       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11912       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11913       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireWatchers")), args));
11914
11915       DeclareFunctionUtil(curExternal, "eInstance_FireWatchers");
11916    }
11917
11918    {
11919       args = MkList();
11920       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11921       ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
11922       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11923
11924       args = MkList();
11925       ListAdd(args, object ? CopyExpression(object) : MkExpIdentifier(MkIdentifier("this")));
11926       ListAdd(args, MkExpIdentifier(MkIdentifier(propNameM)));
11927       ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_FireSelfWatchers")), args));
11928
11929       DeclareFunctionUtil(curExternal, "eInstance_FireSelfWatchers");
11930    }
11931
11932    if(curFunction.propSet && !strcmp(curFunction.propSet.string, prop.name) &&
11933       (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
11934       curFunction.propSet.fireWatchersDone = true;
11935 }
11936
11937 static void ProcessStatement(Statement stmt)
11938 {
11939    yylloc = stmt.loc;
11940    /*
11941    lineNum = stmt.pos.line;
11942    column = stmt.pos.col;
11943    */
11944    switch(stmt.type)
11945    {
11946       case labeledStmt:
11947          ProcessStatement(stmt.labeled.stmt);
11948          break;
11949       case caseStmt:
11950          // This expression should be constant...
11951          if(stmt.caseStmt.exp)
11952          {
11953             FreeType(stmt.caseStmt.exp.destType);
11954             stmt.caseStmt.exp.destType = curSwitchType;
11955             if(curSwitchType) curSwitchType.refCount++;
11956             ProcessExpressionType(stmt.caseStmt.exp);
11957             ComputeExpression(stmt.caseStmt.exp);
11958          }
11959          if(stmt.caseStmt.stmt)
11960             ProcessStatement(stmt.caseStmt.stmt);
11961          break;
11962       case compoundStmt:
11963       {
11964          if(stmt.compound.context)
11965          {
11966             Declaration decl;
11967             Statement s;
11968
11969             Statement prevCompound = curCompound;
11970             Context prevContext = curContext;
11971
11972             if(!stmt.compound.isSwitch)
11973                curCompound = stmt;
11974             curContext = stmt.compound.context;
11975
11976             if(stmt.compound.declarations)
11977             {
11978                for(decl = stmt.compound.declarations->first; decl; decl = decl.next)
11979                   ProcessDeclaration(decl, true);
11980             }
11981             if(stmt.compound.statements)
11982             {
11983                for(s = stmt.compound.statements->first; s; s = s.next)
11984                   ProcessStatement(s);
11985             }
11986
11987             curContext = prevContext;
11988             curCompound = prevCompound;
11989          }
11990          break;
11991       }
11992       case expressionStmt:
11993       {
11994          Expression exp;
11995          if(stmt.expressions)
11996          {
11997             for(exp = stmt.expressions->first; exp; exp = exp.next)
11998                ProcessExpressionType(exp);
11999          }
12000          break;
12001       }
12002       case ifStmt:
12003       {
12004          Expression exp;
12005
12006          FreeType(((Expression)stmt.ifStmt.exp->last).destType);
12007          ((Expression)stmt.ifStmt.exp->last).destType = MkClassType("bool");
12008          ((Expression)stmt.ifStmt.exp->last).destType.truth = true;
12009          for(exp = stmt.ifStmt.exp->first; exp; exp = exp.next)
12010          {
12011             ProcessExpressionType(exp);
12012          }
12013          if(stmt.ifStmt.stmt)
12014             ProcessStatement(stmt.ifStmt.stmt);
12015          if(stmt.ifStmt.elseStmt)
12016             ProcessStatement(stmt.ifStmt.elseStmt);
12017          break;
12018       }
12019       case switchStmt:
12020       {
12021          Type oldSwitchType = curSwitchType;
12022          if(stmt.switchStmt.exp)
12023          {
12024             Expression exp;
12025             for(exp = stmt.switchStmt.exp->first; exp; exp = exp.next)
12026             {
12027                if(!exp.next)
12028                {
12029                   /*
12030                   Type destType
12031                   {
12032                      kind = intType;
12033                      refCount = 1;
12034                   };
12035                   e.exp.destType = destType;
12036                   */
12037
12038                   ProcessExpressionType(exp);
12039                }
12040                if(!exp.next)
12041                   curSwitchType = exp.expType;
12042             }
12043          }
12044          ProcessStatement(stmt.switchStmt.stmt);
12045          curSwitchType = oldSwitchType;
12046          break;
12047       }
12048       case whileStmt:
12049       {
12050          if(stmt.whileStmt.exp)
12051          {
12052             Expression exp;
12053
12054             FreeType(((Expression)stmt.whileStmt.exp->last).destType);
12055             ((Expression)stmt.whileStmt.exp->last).destType = MkClassType("bool");
12056             ((Expression)stmt.whileStmt.exp->last).destType.truth = true;
12057             for(exp = stmt.whileStmt.exp->first; exp; exp = exp.next)
12058             {
12059                ProcessExpressionType(exp);
12060             }
12061          }
12062          if(stmt.whileStmt.stmt)
12063             ProcessStatement(stmt.whileStmt.stmt);
12064          break;
12065       }
12066       case doWhileStmt:
12067       {
12068          if(stmt.doWhile.exp)
12069          {
12070             Expression exp;
12071
12072             if(stmt.doWhile.exp->last)
12073             {
12074                FreeType(((Expression)stmt.doWhile.exp->last).destType);
12075                ((Expression)stmt.doWhile.exp->last).destType = MkClassType("bool");
12076                ((Expression)stmt.doWhile.exp->last).destType.truth = true;
12077             }
12078             for(exp = stmt.doWhile.exp->first; exp; exp = exp.next)
12079             {
12080                ProcessExpressionType(exp);
12081             }
12082          }
12083          if(stmt.doWhile.stmt)
12084             ProcessStatement(stmt.doWhile.stmt);
12085          break;
12086       }
12087       case forStmt:
12088       {
12089          Expression exp;
12090          if(stmt.forStmt.init)
12091             ProcessStatement(stmt.forStmt.init);
12092
12093          if(stmt.forStmt.check && stmt.forStmt.check.expressions)
12094          {
12095             FreeType(((Expression)stmt.forStmt.check.expressions->last).destType);
12096             ((Expression)stmt.forStmt.check.expressions->last).destType = MkClassType("bool");
12097             ((Expression)stmt.forStmt.check.expressions->last).destType.truth = true;
12098          }
12099
12100          if(stmt.forStmt.check)
12101             ProcessStatement(stmt.forStmt.check);
12102          if(stmt.forStmt.increment)
12103          {
12104             for(exp = stmt.forStmt.increment->first; exp; exp = exp.next)
12105                ProcessExpressionType(exp);
12106          }
12107
12108          if(stmt.forStmt.stmt)
12109             ProcessStatement(stmt.forStmt.stmt);
12110          break;
12111       }
12112       case forEachStmt:
12113       {
12114          Identifier id = stmt.forEachStmt.id;
12115          OldList * exp = stmt.forEachStmt.exp;
12116          OldList * filter = stmt.forEachStmt.filter;
12117          Statement block = stmt.forEachStmt.stmt;
12118          char iteratorType[1024];
12119          Type source;
12120          Expression e;
12121          bool isBuiltin = exp && exp->last &&
12122             (((Expression)exp->last).type == ExpressionType::arrayExp ||
12123               (((Expression)exp->last).type == castExp && ((Expression)exp->last).cast.exp.type == ExpressionType::arrayExp));
12124          Expression arrayExp;
12125          const char * typeString = null;
12126          int builtinCount = 0;
12127
12128          for(e = exp ? exp->first : null; e; e = e.next)
12129          {
12130             if(!e.next)
12131             {
12132                FreeType(e.destType);
12133                e.destType = ProcessTypeString("Container", false);
12134             }
12135             if(!isBuiltin || e.next)
12136                ProcessExpressionType(e);
12137          }
12138
12139          source = (exp && exp->last) ? ((Expression)exp->last).expType : null;
12140          if(isBuiltin || (source && source.kind == classType && source._class && source._class.registered && source._class.registered != containerClass &&
12141             eClass_IsDerived(source._class.registered, containerClass)))
12142          {
12143             Class _class = source ? source._class.registered : null;
12144             Symbol symbol;
12145             Expression expIt = null;
12146             bool isMap = false, isArray = false, isLinkList = false, isList = false, isCustomAVLTree = false; //, isAVLTree = false;
12147             Class arrayClass = eSystem_FindClass(privateModule, "Array");
12148             Class linkListClass = eSystem_FindClass(privateModule, "LinkList");
12149             Class customAVLTreeClass = eSystem_FindClass(privateModule, "CustomAVLTree");
12150
12151             if(inCompiler)
12152             {
12153                stmt.type = compoundStmt;
12154
12155                stmt.compound.context = Context { };
12156                stmt.compound.context.parent = curContext;
12157                curContext = stmt.compound.context;
12158             }
12159
12160             if(source && eClass_IsDerived(source._class.registered, customAVLTreeClass))
12161             {
12162                Class mapClass = eSystem_FindClass(privateModule, "Map");
12163                //Class avlTreeClass = eSystem_FindClass(privateModule, "AVLTree");
12164                isCustomAVLTree = true;
12165                /*if(eClass_IsDerived(source._class.registered, avlTreeClass))
12166                   isAVLTree = true;
12167                else */if(eClass_IsDerived(source._class.registered, mapClass))
12168                   isMap = true;
12169             }
12170             else if(source && eClass_IsDerived(source._class.registered, arrayClass)) isArray = true;
12171             else if(source && eClass_IsDerived(source._class.registered, linkListClass))
12172             {
12173                Class listClass = eSystem_FindClass(privateModule, "List");
12174                isLinkList = true;
12175                isList = eClass_IsDerived(source._class.registered, listClass);
12176             }
12177
12178             if(inCompiler && isArray)
12179             {
12180                Declarator decl;
12181                OldList * specs = MkList();
12182                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12183                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12184                stmt.compound.declarations = MkListOne(
12185                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12186                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12187                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalArray")),
12188                      MkInitializerAssignment(MkExpBrackets(exp))))));
12189             }
12190             else if(isBuiltin)
12191             {
12192                Type type = null;
12193                char typeStringBuf[1024];
12194
12195                // TODO: Merge this code?
12196                arrayExp = (((Expression)exp->last).type == ExpressionType::arrayExp) ? (Expression)exp->last : ((Expression)exp->last).cast.exp;
12197                if(((Expression)exp->last).type == castExp)
12198                {
12199                   TypeName typeName = ((Expression)exp->last).cast.typeName;
12200                   if(typeName)
12201                      arrayExp.destType = ProcessType(typeName.qualifiers, typeName.declarator);
12202                }
12203
12204                if(arrayExp.destType && arrayExp.destType.kind == classType && arrayExp.destType._class && arrayExp.destType._class.registered &&
12205                   arrayExp.destType._class.registered != containerClass && eClass_IsDerived(arrayExp.destType._class.registered, containerClass) &&
12206                   arrayExp.destType._class.registered.templateArgs)
12207                {
12208                   Class templateClass = arrayExp.destType._class.registered;
12209                   typeString = templateClass.templateArgs[2].dataTypeString;
12210                }
12211                else if(arrayExp.list)
12212                {
12213                   // Guess type from expressions in the array
12214                   Expression e;
12215                   for(e = arrayExp.list->first; e; e = e.next)
12216                   {
12217                      ProcessExpressionType(e);
12218                      if(e.expType)
12219                      {
12220                         if(!type) { type = e.expType; type.refCount++; }
12221                         else
12222                         {
12223                            // if(!MatchType(e.expType, type, null, null, null, false, false, false))
12224                            if(!MatchTypeExpression(e, type, null, false, true))
12225                            {
12226                               FreeType(type);
12227                               type = e.expType;
12228                               e.expType = null;
12229
12230                               e = arrayExp.list->first;
12231                               ProcessExpressionType(e);
12232                               if(e.expType)
12233                               {
12234                                  //if(!MatchTypes(e.expType, type, null, null, null, false, false, false, false))
12235                                  if(!MatchTypeExpression(e, type, null, false, true))
12236                                  {
12237                                     FreeType(e.expType);
12238                                     e.expType = null;
12239                                     FreeType(type);
12240                                     type = null;
12241                                     break;
12242                                  }
12243                               }
12244                            }
12245                         }
12246                         if(e.expType)
12247                         {
12248                            FreeType(e.expType);
12249                            e.expType = null;
12250                         }
12251                      }
12252                   }
12253                   if(type)
12254                   {
12255                      typeStringBuf[0] = '\0';
12256                      PrintType(type, typeStringBuf, false, true);
12257                      typeString = typeStringBuf;
12258                      FreeType(type);
12259                   }
12260                }
12261                if(typeString)
12262                {
12263                   if(inCompiler)
12264                   {
12265                      OldList * initializers = MkList();
12266                      Declarator decl;
12267                      OldList * specs = MkList();
12268                      if(arrayExp.list)
12269                      {
12270                         Expression e;
12271
12272                         builtinCount = arrayExp.list->count;
12273                         type = ProcessTypeString(typeString, false);
12274                         while((e = arrayExp.list->first))
12275                         {
12276                            arrayExp.list->Remove(e);
12277                            e.destType = type;
12278                            type.refCount++;
12279                            ProcessExpressionType(e);
12280                            if(inCompiler)
12281                               ListAdd(initializers, MkInitializerAssignment(e));
12282                         }
12283                         FreeType(type);
12284                         delete arrayExp.list;
12285                      }
12286                      decl = SpecDeclFromString(typeString, specs, MkDeclaratorIdentifier(id));
12287
12288                      stmt.compound.declarations = MkListOne(MkDeclaration(CopyList(specs, CopySpecifier),
12289                         MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), /*CopyDeclarator(*/decl/*)*/), null))));
12290
12291                      ListAdd(stmt.compound.declarations, MkDeclaration(specs, MkListOne(MkInitDeclarator(
12292                         PlugDeclarator(
12293                            /*CopyDeclarator(*/decl/*)*/, MkDeclaratorArray(MkDeclaratorIdentifier(MkIdentifier("__internalArray")), null)
12294                            ), MkInitializerList(initializers)))));
12295                      FreeList(exp, FreeExpression);
12296                   }
12297                   else if(arrayExp.list)
12298                   {
12299                      Expression e;
12300                      type = ProcessTypeString(typeString, false);
12301                      for(e = arrayExp.list->first; e; e = e.next)
12302                      {
12303                         e.destType = type;
12304                         type.refCount++;
12305                         ProcessExpressionType(e);
12306                      }
12307                      FreeType(type);
12308                   }
12309                }
12310                else
12311                {
12312                   arrayExp.expType = ProcessTypeString("Container", false);
12313                   Compiler_Error($"Couldn't determine type of array elements\n");
12314                }
12315
12316                /*
12317                Declarator decl;
12318                OldList * specs = MkList();
12319
12320                decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs,
12321                   MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(id)));
12322                stmt.compound.declarations = MkListOne(
12323                   MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12324                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName("BuiltInContainer")),
12325                   MkListOne(MkInitDeclarator(MkDeclaratorPointer(MkPointer(null, null), MkDeclaratorIdentifier(MkIdentifier("__internalArray"))),
12326                      MkInitializerAssignment(MkExpBrackets(exp))))));
12327                */
12328             }
12329             else if(inCompiler && isLinkList && !isList)
12330             {
12331                Declarator decl;
12332                OldList * specs = MkList();
12333                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12334                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12335                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12336                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalLinkList")),
12337                      MkInitializerAssignment(MkExpBrackets(exp))))));
12338             }
12339             /*else if(isCustomAVLTree)
12340             {
12341                Declarator decl;
12342                OldList * specs = MkList();
12343                decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, MkDeclaratorIdentifier(id));
12344                stmt.compound.declarations = MkListOne(MkDeclaration(specs, MkListOne(MkInitDeclarator(decl, null))));
12345                ListAdd(stmt.compound.declarations, MkDeclaration(MkListOne(MkSpecifierName(source._class.registered.fullName)),
12346                   MkListOne(MkInitDeclarator(MkDeclaratorIdentifier(MkIdentifier("__internalTree")),
12347                      MkInitializerAssignment(MkExpBrackets(exp))))));
12348             }*/
12349             else if(inCompiler && _class.templateArgs)
12350             {
12351                if(isMap)
12352                   sprintf(iteratorType, "MapIterator<%s, %s >", _class.templateArgs[5].dataTypeString, _class.templateArgs[6].dataTypeString);
12353                else
12354                   sprintf(iteratorType, "Iterator<%s, %s >", _class.templateArgs[2].dataTypeString, _class.templateArgs[1].dataTypeString);
12355
12356                stmt.compound.declarations = MkListOne(
12357                   MkDeclarationInst(MkInstantiationNamed(MkListOne(MkSpecifierName(iteratorType)),
12358                   MkExpIdentifier(id), MkListOne(MkMembersInitList(MkListOne(MkMemberInit(isMap ? MkListOne(MkIdentifier("map")) : null,
12359                   MkInitializerAssignment(MkExpBrackets(exp)))))))));
12360             }
12361             if(inCompiler)
12362             {
12363                symbol = FindSymbol(id.string, curContext, curContext, false, false);
12364
12365                if(block)
12366                {
12367                   // Reparent sub-contexts in this statement
12368                   switch(block.type)
12369                   {
12370                      case compoundStmt:
12371                         if(block.compound.context)
12372                            block.compound.context.parent = stmt.compound.context;
12373                         break;
12374                      case ifStmt:
12375                         if(block.ifStmt.stmt && block.ifStmt.stmt.type == compoundStmt && block.ifStmt.stmt.compound.context)
12376                            block.ifStmt.stmt.compound.context.parent = stmt.compound.context;
12377                         if(block.ifStmt.elseStmt && block.ifStmt.elseStmt.type == compoundStmt && block.ifStmt.elseStmt.compound.context)
12378                            block.ifStmt.elseStmt.compound.context.parent = stmt.compound.context;
12379                         break;
12380                      case switchStmt:
12381                         if(block.switchStmt.stmt && block.switchStmt.stmt.type == compoundStmt && block.switchStmt.stmt.compound.context)
12382                            block.switchStmt.stmt.compound.context.parent = stmt.compound.context;
12383                         break;
12384                      case whileStmt:
12385                         if(block.whileStmt.stmt && block.whileStmt.stmt.type == compoundStmt && block.whileStmt.stmt.compound.context)
12386                            block.whileStmt.stmt.compound.context.parent = stmt.compound.context;
12387                         break;
12388                      case doWhileStmt:
12389                         if(block.doWhile.stmt && block.doWhile.stmt.type == compoundStmt && block.doWhile.stmt.compound.context)
12390                            block.doWhile.stmt.compound.context.parent = stmt.compound.context;
12391                         break;
12392                      case forStmt:
12393                         if(block.forStmt.stmt && block.forStmt.stmt.type == compoundStmt && block.forStmt.stmt.compound.context)
12394                            block.forStmt.stmt.compound.context.parent = stmt.compound.context;
12395                         break;
12396                      case forEachStmt:
12397                         if(block.forEachStmt.stmt && block.forEachStmt.stmt.type == compoundStmt && block.forEachStmt.stmt.compound.context)
12398                            block.forEachStmt.stmt.compound.context.parent = stmt.compound.context;
12399                         break;
12400                      /* Only handle those with compound blocks for now... (Potential limitation on compound statements within expressions)
12401                      case labeledStmt:
12402                      case caseStmt
12403                      case expressionStmt:
12404                      case gotoStmt:
12405                      case continueStmt:
12406                      case breakStmt
12407                      case returnStmt:
12408                      case asmStmt:
12409                      case badDeclarationStmt:
12410                      case fireWatchersStmt:
12411                      case stopWatchingStmt:
12412                      case watchStmt:
12413                      */
12414                   }
12415                }
12416
12417                if(filter)
12418                {
12419                   block = MkIfStmt(filter, block, null);
12420                }
12421                if(isArray)
12422                {
12423                   stmt.compound.statements = MkListOne(MkForStmt(
12424                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array"))))),
12425                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12426                         MkExpOp(MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("array")), '+', MkExpMember(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12427                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12428                      block));
12429                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12430                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12431                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12432                }
12433                else if(isBuiltin)
12434                {
12435                   char count[128];
12436                   //OldList * specs = MkList();
12437                   // Declarator decl = SpecDeclFromString(typeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12438
12439                   sprintf(count, "%d", builtinCount);
12440
12441                   stmt.compound.statements = MkListOne(MkForStmt(
12442                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpIdentifier(MkIdentifier("__internalArray"))))),
12443                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12444                         MkExpOp(MkExpIdentifier(MkIdentifier("__internalArray")), '+', MkExpConstant(count))))),
12445                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12446                      block));
12447
12448                   /*
12449                   Declarator decl = SpecDeclFromString(_class.templateArgs[2].dataTypeString, specs, MkDeclaratorPointer(MkPointer(null, null), null));
12450                   stmt.compound.statements = MkListOne(MkForStmt(
12451                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))))),
12452                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '<',
12453                         MkExpOp(MkExpCast(MkTypeName(specs, decl), MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("data"))), '+', MkExpPointer(MkExpIdentifier(MkIdentifier("__internalArray")), MkIdentifier("count")))))),
12454                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), INC_OP, null)),
12455                      block));
12456                  */
12457                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12458                  ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12459                  ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12460                }
12461                else if(isLinkList && !isList)
12462                {
12463                   Class typeClass = eSystem_FindClass(_class.module, _class.templateArgs[3].dataTypeString);
12464                   Class listItemClass = eSystem_FindClass(_class.module, "ListItem");
12465                   if(typeClass && eClass_IsDerived(typeClass, listItemClass) && _class.templateArgs[5].dataTypeString &&
12466                      !strcmp(_class.templateArgs[5].dataTypeString, "LT::link"))
12467                   {
12468                      stmt.compound.statements = MkListOne(MkForStmt(
12469                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12470                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12471                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12472                         block));
12473                   }
12474                   else
12475                   {
12476                      OldList * specs = MkList();
12477                      Declarator decl = SpecDeclFromString(_class.templateArgs[3].dataTypeString, specs, null);
12478                      stmt.compound.statements = MkListOne(MkForStmt(
12479                         MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("first"))))),
12480                         MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12481                         MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpCast(MkTypeName(specs, decl), MkExpCall(
12482                            MkExpMember(MkExpIdentifier(MkIdentifier("__internalLinkList")), MkIdentifier("GetNext")),
12483                               MkListOne(MkExpCast(MkTypeName(MkListOne(MkSpecifierName("IteratorPointer")), null), MkExpIdentifier(CopyIdentifier(id)))))))),
12484                         block));
12485                   }
12486                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12487                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12488                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12489                }
12490                /*else if(isCustomAVLTree)
12491                {
12492                   stmt.compound.statements = MkListOne(MkForStmt(
12493                      MkExpressionStmt(MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpMember(MkExpIdentifier(
12494                         MkIdentifier("__internalTree")), MkIdentifier("root")), MkIdentifier("minimum"))))),
12495                      MkExpressionStmt(MkListOne(MkExpIdentifier(CopyIdentifier(id)))),
12496                      MkListOne(MkExpOp(MkExpIdentifier(CopyIdentifier(id)), '=', MkExpMember(MkExpIdentifier(CopyIdentifier(id)), MkIdentifier("next")))),
12497                      block));
12498
12499                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.init);
12500                   ProcessStatement(((Statement)stmt.compound.statements->first).forStmt.check);
12501                   ProcessExpressionType(((Statement)stmt.compound.statements->first).forStmt.increment->first);
12502                }*/
12503                else
12504                {
12505                   stmt.compound.statements = MkListOne(MkWhileStmt(MkListOne(MkExpCall(MkExpMember(expIt = MkExpIdentifier(CopyIdentifier(id)),
12506                      MkIdentifier("Next")), null)), block));
12507                }
12508                ProcessExpressionType(expIt);
12509                if(stmt.compound.declarations->first)
12510                   ProcessDeclaration(stmt.compound.declarations->first, true);
12511
12512                if(symbol)
12513                   symbol.isIterator = isMap ? 2 : ((isArray || isBuiltin) ? 3 : (isLinkList ? (isList ? 5 : 4) : (isCustomAVLTree ? 6 : 1)));
12514
12515                ProcessStatement(stmt);
12516             }
12517             else
12518                ProcessStatement(stmt.forEachStmt.stmt);
12519             if(inCompiler)
12520                curContext = stmt.compound.context.parent;
12521             break;
12522          }
12523          else
12524          {
12525             Compiler_Error($"Expression is not a container\n");
12526          }
12527          break;
12528       }
12529       case gotoStmt:
12530          break;
12531       case continueStmt:
12532          break;
12533       case breakStmt:
12534          break;
12535       case returnStmt:
12536       {
12537          Expression exp;
12538          if(stmt.expressions)
12539          {
12540             for(exp = stmt.expressions->first; exp; exp = exp.next)
12541             {
12542                if(!exp.next)
12543                {
12544                   if(curFunction && !curFunction.type)
12545                      curFunction.type = ProcessType(
12546                         curFunction.specifiers, curFunction.declarator);
12547                   FreeType(exp.destType);
12548                   // TODO: current property if not compiling
12549                   exp.destType = (curFunction && curFunction.type && curFunction.type.kind == functionType) ? curFunction.type.returnType : null;
12550                   if(exp.destType) exp.destType.refCount++;
12551                }
12552                ProcessExpressionType(exp);
12553             }
12554          }
12555          break;
12556       }
12557       case badDeclarationStmt:
12558       {
12559          ProcessDeclaration(stmt.decl, true);
12560          break;
12561       }
12562       case asmStmt:
12563       {
12564          AsmField field;
12565          if(stmt.asmStmt.inputFields)
12566          {
12567             for(field = stmt.asmStmt.inputFields->first; field; field = field.next)
12568                if(field.expression)
12569                   ProcessExpressionType(field.expression);
12570          }
12571          if(stmt.asmStmt.outputFields)
12572          {
12573             for(field = stmt.asmStmt.outputFields->first; field; field = field.next)
12574                if(field.expression)
12575                   ProcessExpressionType(field.expression);
12576          }
12577          if(stmt.asmStmt.clobberedFields)
12578          {
12579             for(field = stmt.asmStmt.clobberedFields->first; field; field = field.next)
12580             {
12581                if(field.expression)
12582                   ProcessExpressionType(field.expression);
12583             }
12584          }
12585          break;
12586       }
12587       case watchStmt:
12588       {
12589          PropertyWatch propWatch;
12590          OldList * watches = stmt._watch.watches;
12591          Expression object = stmt._watch.object;
12592          Expression watcher = stmt._watch.watcher;
12593          if(watcher)
12594             ProcessExpressionType(watcher);
12595          if(object)
12596             ProcessExpressionType(object);
12597
12598          if(inCompiler)
12599          {
12600             if(watcher || thisClass)
12601             {
12602                External external = curExternal;
12603                Context context = curContext;
12604
12605                stmt.type = expressionStmt;
12606                stmt.expressions = MkList();
12607
12608                for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12609                {
12610                   ClassFunction func;
12611                   char watcherName[1024];
12612                   Class watcherClass = watcher ?
12613                      ((watcher.expType && watcher.expType.kind == classType && watcher.expType._class) ? watcher.expType._class.registered : null) : thisClass;
12614                   External createdExternal;
12615
12616                   sprintf(watcherName,"__ecerePropertyWatcher_%d", propWatcherID++);
12617                   if(propWatch.deleteWatch)
12618                      strcat(watcherName, "_delete");
12619                   else
12620                   {
12621                      Identifier propID;
12622                      for(propID = propWatch.properties->first; propID; propID = propID.next)
12623                      {
12624                         strcat(watcherName, "_");
12625                         strcat(watcherName, propID.string);
12626                      }
12627                   }
12628
12629                   if(object && object.expType && object.expType.kind == classType && object.expType._class && object.expType._class.registered)
12630                   {
12631                      func = MkClassFunction(MkListOne(MkSpecifier(VOID)), null, MkDeclaratorFunction(MkDeclaratorIdentifier(MkIdentifier(watcherName)),
12632                         MkListOne(MkTypeName(MkListOne(MkSpecifierName(object.expType._class.string)), MkDeclaratorIdentifier(MkIdentifier("value"))))), null);
12633                      ProcessClassFunctionBody(func, propWatch.compound);
12634                      propWatch.compound = null;
12635
12636                      createdExternal = ProcessClassFunction(watcherClass, func, ast, curExternal, true);
12637
12638                      FreeClassFunction(func);
12639
12640                      curExternal = createdExternal;
12641                      ProcessFunction(createdExternal.function);
12642
12643                      if(propWatch.deleteWatch)
12644                      {
12645                         OldList * args = MkList();
12646                         ListAdd(args, CopyExpression(object));
12647                         ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12648                         ListAdd(args, MkExpIdentifier(MkIdentifier(watcherName)));
12649                         ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_WatchDestruction")), args));
12650                      }
12651                      else
12652                      {
12653                         Class _class = object.expType._class.registered;
12654                         Identifier propID;
12655
12656                         for(propID = propWatch.properties->first; propID; propID = propID.next)
12657                         {
12658                            char propName[1024];
12659                            Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12660                            if(prop)
12661                            {
12662                               char getName[1024], setName[1024];
12663                               OldList * args = MkList();
12664
12665                               DeclareProperty(createdExternal, prop, setName, getName);
12666
12667                               // eInstance_Watch(stmt.watch.object, prop, stmt.watch.watcher, callback);
12668                               strcpy(propName, "__ecereProp_");
12669                               FullClassNameCat(propName, prop._class.fullName, false);
12670                               strcat(propName, "_");
12671                               FullClassNameCat(propName, prop.name, true);
12672
12673                               ListAdd(args, CopyExpression(object));
12674                               ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12675                               ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12676                               ListAdd(args, MkExpCast(MkTypeName(MkListOne(MkSpecifier(VOID)), MkDeclaratorPointer(MkPointer(null, null), null)), MkExpIdentifier(MkIdentifier(watcherName))));
12677
12678                               ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_Watch")), args));
12679
12680                               external.CreateUniqueEdge(createdExternal, true);
12681                            }
12682                            else
12683                               Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12684                         }
12685                      }
12686                   }
12687                   else
12688                      Compiler_Error($"Invalid watched object\n");
12689                }
12690
12691                curExternal = external;
12692                curContext = context;
12693
12694                if(watcher)
12695                   FreeExpression(watcher);
12696                if(object)
12697                   FreeExpression(object);
12698                FreeList(watches, FreePropertyWatch);
12699             }
12700             else
12701                Compiler_Error($"No observer specified and not inside a class\n");
12702          }
12703          else
12704          {
12705             for(propWatch = watches->first; propWatch; propWatch = propWatch.next)
12706             {
12707                ProcessStatement(propWatch.compound);
12708             }
12709
12710          }
12711          break;
12712       }
12713       case fireWatchersStmt:
12714       {
12715          OldList * watches = stmt._watch.watches;
12716          Expression object = stmt._watch.object;
12717          Class _class;
12718          // DEBUGGER BUG: Why doesn't watches evaluate to null??
12719          // printf("%X\n", watches);
12720          // printf("%X\n", stmt._watch.watches);
12721          if(object)
12722             ProcessExpressionType(object);
12723
12724          if(inCompiler)
12725          {
12726             _class = object ?
12727                   ((object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null) : thisClass;
12728
12729             if(_class)
12730             {
12731                Identifier propID;
12732
12733                stmt.type = expressionStmt;
12734                stmt.expressions = MkList();
12735
12736                // Check if we're inside a property set
12737                if(!watches && curFunction.propSet && (!object || (object.type == identifierExp && !strcmp(object.identifier.string, "this"))))
12738                {
12739                   watches = MkListOne(MkIdentifier(curFunction.propSet.string));
12740                }
12741                else if(!watches)
12742                {
12743                   //Compiler_Error($"No property specified and not inside a property set\n");
12744                }
12745                if(watches)
12746                {
12747                   for(propID = watches->first; propID; propID = propID.next)
12748                   {
12749                      Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12750                      if(prop)
12751                      {
12752                         CreateFireWatcher(prop, object, stmt);
12753                      }
12754                      else
12755                         Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12756                   }
12757                }
12758                else
12759                {
12760                   // Fire all properties!
12761                   Property prop;
12762                   Class base;
12763                   for(base = _class; base; base = base.base)
12764                   {
12765                      for(prop = base.membersAndProperties.first; prop; prop = prop.next)
12766                      {
12767                         if(prop.isProperty && prop.isWatchable)
12768                         {
12769                            CreateFireWatcher(prop, object, stmt);
12770                         }
12771                      }
12772                   }
12773                }
12774
12775                if(object)
12776                   FreeExpression(object);
12777                FreeList(watches, FreeIdentifier);
12778             }
12779             else
12780                Compiler_Error($"Invalid object specified and not inside a class\n");
12781          }
12782          break;
12783       }
12784       case stopWatchingStmt:
12785       {
12786          OldList * watches = stmt._watch.watches;
12787          Expression object = stmt._watch.object;
12788          Expression watcher = stmt._watch.watcher;
12789          Class _class;
12790          if(object)
12791             ProcessExpressionType(object);
12792          if(watcher)
12793             ProcessExpressionType(watcher);
12794          if(inCompiler)
12795          {
12796             _class = (object && object.expType && object.expType.kind == classType && object.expType._class) ? object.expType._class.registered : null;
12797
12798             if(watcher || thisClass)
12799             {
12800                if(_class)
12801                {
12802                   Identifier propID;
12803
12804                   stmt.type = expressionStmt;
12805                   stmt.expressions = MkList();
12806
12807                   if(!watches)
12808                   {
12809                      OldList * args;
12810                      // eInstance_StopWatching(object, null, watcher);
12811                      args = MkList();
12812                      ListAdd(args, CopyExpression(object));
12813                      ListAdd(args, MkExpConstant("0"));
12814                      ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12815                      ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12816                   }
12817                   else
12818                   {
12819                      for(propID = watches->first; propID; propID = propID.next)
12820                      {
12821                         char propName[1024];
12822                         Property prop = eClass_FindProperty(_class, propID.string, privateModule);
12823                         if(prop)
12824                         {
12825                            char getName[1024], setName[1024];
12826                            OldList * args = MkList();
12827
12828                            DeclareProperty(curExternal, prop, setName, getName);
12829
12830                            // eInstance_StopWatching(object, prop, watcher);
12831                            strcpy(propName, "__ecereProp_");
12832                            FullClassNameCat(propName, prop._class.fullName, false);
12833                            strcat(propName, "_");
12834                            FullClassNameCat(propName, prop.name, true);
12835
12836                            ListAdd(args, CopyExpression(object));
12837                            ListAdd(args, MkExpIdentifier(MkIdentifier(propName)));
12838                            ListAdd(args, watcher ? CopyExpression(watcher) : MkExpIdentifier(MkIdentifier("this")));
12839                            ListAdd(stmt.expressions, MkExpCall(MkExpIdentifier(MkIdentifier("ecere::com::eInstance_StopWatching")), args));
12840                         }
12841                         else
12842                            Compiler_Error($"Property %s not found in class %s\n", propID.string, _class.fullName);
12843                      }
12844                   }
12845
12846                   if(object)
12847                      FreeExpression(object);
12848                   if(watcher)
12849                      FreeExpression(watcher);
12850                   FreeList(watches, FreeIdentifier);
12851                }
12852                else
12853                   Compiler_Error($"Invalid object specified and not inside a class\n");
12854             }
12855             else
12856                Compiler_Error($"No observer specified and not inside a class\n");
12857          }
12858          break;
12859       }
12860    }
12861 }
12862
12863 static void ProcessFunction(FunctionDefinition function)
12864 {
12865    Identifier id = GetDeclId(function.declarator);
12866    Symbol symbol = function.declarator ? function.declarator.symbol : null;
12867    Type type = symbol ? symbol.type : null;
12868    Class oldThisClass = thisClass;
12869    Context oldTopContext = topContext;
12870
12871    yylloc = function.loc;
12872    // Process thisClass
12873
12874    if(type && type.thisClass)
12875    {
12876       Symbol classSym = type.thisClass;
12877       Class _class = type.thisClass.registered;
12878       char className[1024];
12879       char structName[1024];
12880       Declarator funcDecl;
12881       Symbol thisSymbol;
12882
12883       bool typedObject = false;
12884
12885       if(_class && !_class.base)
12886       {
12887          _class = currentClass;
12888          if(_class && !_class.symbol)
12889             _class.symbol = FindClass(_class.fullName);
12890          classSym = _class ? _class.symbol : null;
12891          typedObject = true;
12892       }
12893
12894       thisClass = _class;
12895
12896       if(inCompiler && _class)
12897       {
12898          if(type.kind == functionType)
12899          {
12900             if(symbol.type.params.count == 1 && ((Type)symbol.type.params.first).kind == voidType)
12901             {
12902                //TypeName param = symbol.type.params.first;
12903                Type param = symbol.type.params.first;
12904                symbol.type.params.Remove(param);
12905                //FreeTypeName(param);
12906                FreeType(param);
12907             }
12908             if(type.classObjectType != classPointer)
12909             {
12910                symbol.type.params.Insert(null, MkClassType(_class.fullName));
12911                symbol.type.staticMethod = true;
12912                symbol.type.thisClass = null;
12913
12914                // HIGH DANGER: VERIFYING THIS...
12915                symbol.type.extraParam = false;
12916             }
12917          }
12918
12919          strcpy(className, "__ecereClass_");
12920          FullClassNameCat(className, _class.fullName, true);
12921
12922          structName[0] = 0;
12923          FullClassNameCat(structName, _class.fullName, false);
12924
12925          // [class] this
12926          funcDecl = GetFuncDecl(function.declarator);
12927          if(funcDecl)
12928          {
12929             if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12930             {
12931                TypeName param = funcDecl.function.parameters->first;
12932                if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12933                {
12934                   funcDecl.function.parameters->Remove(param);
12935                   FreeTypeName(param);
12936                }
12937             }
12938
12939             if(!function.propertyNoThis)
12940             {
12941                TypeName thisParam = null;
12942
12943                if(type.classObjectType != classPointer)
12944                {
12945                   thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12946                   if(!funcDecl.function.parameters)
12947                      funcDecl.function.parameters = MkList();
12948                   funcDecl.function.parameters->Insert(null, thisParam);
12949                }
12950
12951                if(typedObject)
12952                {
12953                   if(type.classObjectType != classPointer)
12954                   {
12955                      if(type.byReference || _class.type == unitClass || _class.type == systemClass || _class.type == enumClass || _class.type == bitClass)
12956                         thisParam.declarator = MkDeclaratorPointer(MkPointer(null,null), thisParam.declarator);
12957                   }
12958
12959                   thisParam = TypeName
12960                   {
12961                      declarator = MkDeclaratorPointer(MkPointer(null,null), MkDeclaratorIdentifier(MkIdentifier("class")));
12962                      qualifiers = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier("__ecereNameSpace__ecere__com__Class"), null));
12963                   };
12964                   DeclareStruct(curExternal, "ecere::com::Class", false, true);
12965                   funcDecl.function.parameters->Insert(null, thisParam);
12966                }
12967             }
12968          }
12969
12970          if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
12971          {
12972             InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
12973             funcDecl = GetFuncDecl(initDecl.declarator);
12974             if(funcDecl)
12975             {
12976                if(funcDecl.function.parameters && funcDecl.function.parameters->count == 1)
12977                {
12978                   TypeName param = funcDecl.function.parameters->first;
12979                   if(param.qualifiers && param.qualifiers->count == 1 && ((Specifier)param.qualifiers->first).specifier == VOID && !param.declarator)
12980                   {
12981                      funcDecl.function.parameters->Remove(param);
12982                      FreeTypeName(param);
12983                   }
12984                }
12985
12986                if(type.classObjectType != classPointer)
12987                {
12988                   if((_class.type != bitClass && _class.type != unitClass && _class.type != enumClass) || function != (FunctionDefinition)symbol.externalSet)
12989                   {
12990                      TypeName thisParam = QMkClass(_class.fullName, MkDeclaratorIdentifier(MkIdentifier("this")));
12991
12992                      if(!funcDecl.function.parameters)
12993                         funcDecl.function.parameters = MkList();
12994                      funcDecl.function.parameters->Insert(null, thisParam);
12995                   }
12996                }
12997             }
12998          }
12999       }
13000
13001       // Add this to the context
13002       if(function.body)
13003       {
13004          if(type.classObjectType != classPointer)
13005          {
13006             thisSymbol = Symbol
13007             {
13008                string = CopyString("this");
13009                type = classSym ? MkClassType(classSym.string) : null;
13010             };
13011             function.body.compound.context.symbols.Add((BTNode)thisSymbol);
13012
13013             if(typedObject && thisSymbol.type)
13014             {
13015                thisSymbol.type.classObjectType = ClassObjectType::typedObject;
13016                thisSymbol.type.byReference = type.byReference;
13017                thisSymbol.type.typedByReference = type.byReference;
13018             }
13019          }
13020       }
13021
13022       // Pointer to class data
13023       if(inCompiler && _class && _class.type == normalClass && type.classObjectType != classPointer)
13024       {
13025          DataMember member = null;
13026          {
13027             Class base;
13028             for(base = _class; base && base.type != systemClass; base = base.next)
13029             {
13030                for(member = base.membersAndProperties.first; member; member = member.next)
13031                   if(!member.isProperty)
13032                      break;
13033                if(member)
13034                   break;
13035             }
13036          }
13037          for(member = _class.membersAndProperties.first; member; member = member.next)
13038             if(!member.isProperty)
13039                break;
13040          if(member)
13041          {
13042             char pointerName[1024];
13043
13044             Declaration decl;
13045             Initializer initializer;
13046             Expression exp, bytePtr;
13047
13048             strcpy(pointerName, "__ecerePointer_");
13049             FullClassNameCat(pointerName, _class.fullName, false);
13050             {
13051                char className[1024];
13052                strcpy(className, "__ecereClass_");
13053                FullClassNameCat(className, classSym.string, true);
13054
13055                DeclareClass(curExternal, classSym, className);
13056             }
13057
13058             // ((byte *) this)
13059             bytePtr = QBrackets(MkExpCast(QMkType("char", QMkPtrDecl(null)), QMkExpId("this")));
13060
13061             if(_class.fixed)
13062             {
13063                Expression e;
13064                if(_class.offset && _class.offset == _class.base.structSize)
13065                {
13066                   e = MkExpClassSize(MkSpecifierName(_class.base.fullName));
13067                   ProcessExpressionType(e);
13068                }
13069                else
13070                {
13071                   char string[256];
13072                   sprintf(string, "%d", _class.offset);  // Need Bootstrap Fix
13073                   e = MkExpConstant(string);
13074                }
13075                exp = QBrackets(MkExpOp(bytePtr, '+', e));
13076             }
13077             else
13078             {
13079                // ([bytePtr] + [className]->offset)
13080                exp = QBrackets(MkExpOp(bytePtr, '+',
13081                   MkExpPointer(QMkExpId(className), MkIdentifier("offset"))));
13082             }
13083
13084             // (this ? [exp] : 0)
13085             exp = QBrackets(QMkExpCond(QMkExpId("this"), exp, MkExpConstant("0")));
13086             exp.expType = Type
13087             {
13088                refCount = 1;
13089                kind = pointerType;
13090                type = Type { refCount = 1, kind = voidType };
13091             };
13092
13093             if(function.body)
13094             {
13095                yylloc = function.body.loc;
13096                // ([structName] *) [exp]
13097                // initializer = MkInitializerAssignment(MkExpCast(QMkType(structName, QMkPtrDecl(null)), exp));
13098                initializer = MkInitializerAssignment(
13099                   MkExpCast(MkTypeName(MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null)), MkDeclaratorPointer(MkPointer(null, null), null)), exp));
13100
13101                // [structName] * [pointerName] = [initializer];
13102                // decl = QMkDeclaration(structName, MkInitDeclarator(QMkPtrDecl(pointerName), initializer));
13103
13104                {
13105                   Context prevContext = curContext;
13106                   OldList * list;
13107                   curContext = function.body.compound.context;
13108
13109                   decl = MkDeclaration((list = MkListOne(MkStructOrUnion(structSpecifier, MkIdentifier(structName), null))),
13110                      MkListOne(MkInitDeclarator(QMkPtrDecl(pointerName), initializer)));
13111                   list->Insert(null, MkSpecifierExtended(MkExtDeclAttrib(MkAttrib(ATTRIB, MkListOne(MkAttribute(CopyString("unused"), null))))));
13112
13113                   curContext = prevContext;
13114                }
13115
13116                // WHY?
13117                decl.symbol = null;
13118
13119                if(!function.body.compound.declarations)
13120                   function.body.compound.declarations = MkList();
13121                function.body.compound.declarations->Insert(null, decl);
13122             }
13123          }
13124       }
13125
13126
13127       // Loop through the function and replace undeclared identifiers
13128       // which are a member of the class (methods, properties or data)
13129       // by "this.[member]"
13130    }
13131    else
13132       thisClass = null;
13133
13134    if(id)
13135    {
13136       FreeSpecifier(id._class);
13137       id._class = null;
13138
13139       if(symbol && symbol.pointerExternal && symbol.pointerExternal.type == declarationExternal)
13140       {
13141          InitDeclarator initDecl = symbol.pointerExternal.declaration.declarators->first;
13142          id = GetDeclId(initDecl.declarator);
13143
13144          FreeSpecifier(id._class);
13145          id._class = null;
13146       }
13147    }
13148    if(function.body)
13149       topContext = function.body.compound.context;
13150    {
13151       FunctionDefinition oldFunction = curFunction;
13152       curFunction = function;
13153       if(function.body)
13154          ProcessStatement(function.body);
13155
13156       // If this is a property set and no firewatchers has been done yet, add one here
13157       if(inCompiler && function.propSet && !function.propSet.fireWatchersDone)
13158       {
13159          Statement prevCompound = curCompound;
13160          Context prevContext = curContext;
13161
13162          Statement fireWatchers = MkFireWatchersStmt(null, null);
13163          if(!function.body.compound.statements) function.body.compound.statements = MkList();
13164          ListAdd(function.body.compound.statements, fireWatchers);
13165
13166          curCompound = function.body;
13167          curContext = function.body.compound.context;
13168
13169          ProcessStatement(fireWatchers);
13170
13171          curContext = prevContext;
13172          curCompound = prevCompound;
13173
13174       }
13175
13176       curFunction = oldFunction;
13177    }
13178
13179    if(function.declarator)
13180    {
13181       ProcessDeclarator(function.declarator, true);
13182    }
13183
13184    topContext = oldTopContext;
13185    thisClass = oldThisClass;
13186 }
13187
13188 /////////// INSTANTIATIONS / DATA TYPES PASS /////////////////////////////////////////////
13189 static void ProcessClass(OldList definitions, Symbol symbol)
13190 {
13191    ClassDef def;
13192    External external = curExternal;
13193    Class regClass = symbol ? symbol.registered : null;
13194
13195    // Process all functions
13196    for(def = definitions.first; def; def = def.next)
13197    {
13198       if(def.type == functionClassDef)
13199       {
13200          if(def.function.declarator)
13201             curExternal = def.function.declarator.symbol.pointerExternal;
13202          else
13203             curExternal = external;
13204
13205          ProcessFunction((FunctionDefinition)def.function);
13206       }
13207       else if(def.type == declarationClassDef)
13208       {
13209          if(def.decl.type == instDeclaration)
13210          {
13211             thisClass = regClass;
13212             ProcessInstantiationType(def.decl.inst);
13213             thisClass = null;
13214          }
13215          // Testing this
13216          else
13217          {
13218             Class backThisClass = thisClass;
13219             if(regClass) thisClass = regClass;
13220             ProcessDeclaration(def.decl, symbol ? true : false);
13221             thisClass = backThisClass;
13222          }
13223       }
13224       else if(def.type == defaultPropertiesClassDef && def.defProperties)
13225       {
13226          MemberInit defProperty;
13227
13228          // Add this to the context
13229          Symbol thisSymbol = Symbol
13230          {
13231             string = CopyString("this");
13232             type = regClass ? MkClassType(regClass.fullName) : null;
13233          };
13234          globalContext.symbols.Add((BTNode)thisSymbol);
13235
13236          for(defProperty = def.defProperties->first; defProperty; defProperty = defProperty.next)
13237          {
13238             thisClass = regClass;
13239             ProcessMemberInitData(defProperty, regClass, null, null, null, null);
13240             thisClass = null;
13241          }
13242
13243          globalContext.symbols.Remove((BTNode)thisSymbol);
13244          FreeSymbol(thisSymbol);
13245       }
13246       else if(def.type == propertyClassDef && def.propertyDef)
13247       {
13248          PropertyDef prop = def.propertyDef;
13249
13250          // Add this to the context
13251          thisClass = regClass;
13252          if(prop.setStmt)
13253          {
13254             if(regClass)
13255             {
13256                Symbol thisSymbol
13257                {
13258                   string = CopyString("this");
13259                   type = MkClassType(regClass.fullName);
13260                };
13261                prop.setStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13262             }
13263
13264             curExternal = prop.symbol ? prop.symbol.externalSet : null;
13265             ProcessStatement(prop.setStmt);
13266          }
13267          if(prop.getStmt)
13268          {
13269             if(regClass)
13270             {
13271                Symbol thisSymbol
13272                {
13273                   string = CopyString("this");
13274                   type = MkClassType(regClass.fullName);
13275                };
13276                prop.getStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13277             }
13278
13279             curExternal = prop.symbol ? prop.symbol.externalGet : null;
13280             ProcessStatement(prop.getStmt);
13281          }
13282          if(prop.issetStmt)
13283          {
13284             if(regClass)
13285             {
13286                Symbol thisSymbol
13287                {
13288                   string = CopyString("this");
13289                   type = MkClassType(regClass.fullName);
13290                };
13291                prop.issetStmt.compound.context.symbols.Add((BTNode)thisSymbol);
13292             }
13293
13294             curExternal = prop.symbol ? prop.symbol.externalIsSet : null;
13295             ProcessStatement(prop.issetStmt);
13296          }
13297
13298          thisClass = null;
13299       }
13300       else if(def.type == propertyWatchClassDef && def.propertyWatch)
13301       {
13302          PropertyWatch propertyWatch = def.propertyWatch;
13303
13304          thisClass = regClass;
13305          if(propertyWatch.compound)
13306          {
13307             Symbol thisSymbol
13308             {
13309                string = CopyString("this");
13310                type = regClass ? MkClassType(regClass.fullName) : null;
13311             };
13312
13313             propertyWatch.compound.compound.context.symbols.Add((BTNode)thisSymbol);
13314
13315             curExternal = null;
13316             ProcessStatement(propertyWatch.compound);
13317          }
13318          thisClass = null;
13319       }
13320    }
13321 }
13322
13323 void DeclareFunctionUtil(External neededBy, const String s)
13324 {
13325    GlobalFunction function = eSystem_FindFunction(privateModule, s);
13326    if(function)
13327    {
13328       char name[1024];
13329       name[0] = 0;
13330       if(function.module.importType != staticImport && (!function.dataType || !function.dataType.dllExport))
13331          strcpy(name, "__ecereFunction_");
13332       FullClassNameCat(name, s, false); // Why is this using FullClassNameCat ?
13333       DeclareFunction(neededBy, function, name);
13334    }
13335    else if(neededBy)
13336       FindSymbol(s, globalContext, globalContext, false, false);
13337 }
13338
13339 void ComputeDataTypes()
13340 {
13341    External external;
13342
13343    currentClass = null;
13344
13345    containerClass = eSystem_FindClass(GetPrivateModule(), "Container");
13346
13347    DeclareStruct(null, "ecere::com::Class", false, true);
13348    DeclareStruct(null, "ecere::com::Instance", false, true);
13349    DeclareStruct(null, "ecere::com::Property", false, true);
13350    DeclareStruct(null, "ecere::com::DataMember", false, true);
13351    DeclareStruct(null, "ecere::com::Method", false, true);
13352    DeclareStruct(null, "ecere::com::SerialBuffer", false, true);
13353    DeclareStruct(null, "ecere::com::ClassTemplateArgument", false, true);
13354
13355    DeclareFunctionUtil(null, "eSystem_New");
13356    DeclareFunctionUtil(null, "eSystem_New0");
13357    DeclareFunctionUtil(null, "eSystem_Renew");
13358    DeclareFunctionUtil(null, "eSystem_Renew0");
13359    DeclareFunctionUtil(null, "eSystem_Delete");
13360    DeclareFunctionUtil(null, "eClass_GetProperty");
13361    DeclareFunctionUtil(null, "eClass_SetProperty");
13362    DeclareFunctionUtil(null, "eInstance_FireSelfWatchers");
13363    DeclareFunctionUtil(null, "eInstance_SetMethod");
13364    DeclareFunctionUtil(null, "eInstance_IncRef");
13365    DeclareFunctionUtil(null, "eInstance_StopWatching");
13366    DeclareFunctionUtil(null, "eInstance_Watch");
13367    DeclareFunctionUtil(null, "eInstance_FireWatchers");
13368
13369    for(external = ast->first; external; external = external.next)
13370    {
13371       afterExternal = curExternal = external;
13372       if(external.type == functionExternal)
13373       {
13374          if(memoryGuard)
13375          {
13376             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13377             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13378          }
13379
13380          currentClass = external.function._class;
13381          ProcessFunction(external.function);
13382       }
13383       // There shouldn't be any _class member access here anyways...
13384       else if(external.type == declarationExternal)
13385       {
13386          if(memoryGuard && external.declaration && external.declaration.type == instDeclaration)
13387          {
13388             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13389             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13390          }
13391
13392          currentClass = null;
13393          if(external.declaration)
13394             ProcessDeclaration(external.declaration, true);
13395       }
13396       else if(external.type == classExternal)
13397       {
13398          ClassDefinition _class = external._class;
13399          currentClass = external.symbol.registered;
13400          if(memoryGuard)
13401          {
13402             DeclareFunctionUtil(external, "MemoryGuard_PushLoc");
13403             DeclareFunctionUtil(external, "MemoryGuard_PopLoc");
13404          }
13405          if(_class.definitions)
13406          {
13407             ProcessClass(_class.definitions, _class.symbol);
13408          }
13409          if(inCompiler)
13410          {
13411             // Free class data...
13412             ast->Remove(external);
13413             delete external;
13414          }
13415       }
13416       else if(external.type == nameSpaceExternal)
13417       {
13418          thisNameSpace = external.id.string;
13419       }
13420    }
13421    currentClass = null;
13422    thisNameSpace = null;
13423    curExternal = null;
13424 }