blob: e59c5b114ddb48401fea225f6b657ebd599f4cd3 [file] [log] [blame]
/* Compiler implementation of the D programming language
* Copyright (C) 1999-2019 by The D Language Foundation, All Rights Reserved
* written by Walter Bright
* http://www.digitalmars.com
* Distributed under the Boost Software License, Version 1.0.
* http://www.boost.org/LICENSE_1_0.txt
* https://github.com/D-Programming-Language/dmd/blob/master/src/expression.c
*/
#include "root/dsystem.h"
#include "root/rmem.h"
#include "root/root.h"
#include "errors.h"
#include "mtype.h"
#include "init.h"
#include "expression.h"
#include "template.h"
#include "utf.h"
#include "enum.h"
#include "scope.h"
#include "statement.h"
#include "declaration.h"
#include "aggregate.h"
#include "import.h"
#include "id.h"
#include "dsymbol.h"
#include "module.h"
#include "attrib.h"
#include "hdrgen.h"
#include "parse.h"
#include "doc.h"
#include "root/aav.h"
#include "nspace.h"
#include "ctfe.h"
#include "target.h"
bool walkPostorder(Expression *e, StoppableVisitor *v);
bool checkParamArgumentEscape(Scope *sc, FuncDeclaration *fdc, Identifier *par, Expression *arg, bool gag);
bool checkAccess(AggregateDeclaration *ad, Loc loc, Scope *sc, Dsymbol *smember);
VarDeclaration *copyToTemp(StorageClass stc, const char *name, Expression *e);
Expression *extractSideEffect(Scope *sc, const char *name, Expression **e0, Expression *e, bool alwaysCopy = false);
char *MODtoChars(MOD mod);
bool MODimplicitConv(MOD modfrom, MOD modto);
MOD MODmerge(MOD mod1, MOD mod2);
void MODMatchToBuffer(OutBuffer *buf, unsigned char lhsMod, unsigned char rhsMod);
Expression *trySemantic(Expression *e, Scope *sc);
Expression *semantic(Expression *e, Scope *sc);
Expression *semanticX(DotIdExp *exp, Scope *sc);
Expression *semanticY(DotIdExp *exp, Scope *sc, int flag);
Expression *semanticY(DotTemplateInstanceExp *exp, Scope *sc, int flag);
Expression *resolve(Loc loc, Scope *sc, Dsymbol *s, bool hasOverloads);
bool checkUnsafeAccess(Scope *sc, Expression *e, bool readonly, bool printmsg);
/*************************************************************
* Given var, we need to get the
* right 'this' pointer if var is in an outer class, but our
* existing 'this' pointer is in an inner class.
* Input:
* e1 existing 'this'
* ad struct or class we need the correct 'this' for
* var the specific member of ad we're accessing
*/
Expression *getRightThis(Loc loc, Scope *sc, AggregateDeclaration *ad,
Expression *e1, Declaration *var, int flag = 0)
{
//printf("\ngetRightThis(e1 = %s, ad = %s, var = %s)\n", e1->toChars(), ad->toChars(), var->toChars());
L1:
Type *t = e1->type->toBasetype();
//printf("e1->type = %s, var->type = %s\n", e1->type->toChars(), var->type->toChars());
/* If e1 is not the 'this' pointer for ad
*/
if (ad &&
!(t->ty == Tpointer && t->nextOf()->ty == Tstruct &&
((TypeStruct *)t->nextOf())->sym == ad)
&&
!(t->ty == Tstruct &&
((TypeStruct *)t)->sym == ad)
)
{
ClassDeclaration *cd = ad->isClassDeclaration();
ClassDeclaration *tcd = t->isClassHandle();
/* e1 is the right this if ad is a base class of e1
*/
if (!cd || !tcd ||
!(tcd == cd || cd->isBaseOf(tcd, NULL))
)
{
/* Only classes can be inner classes with an 'outer'
* member pointing to the enclosing class instance
*/
if (tcd && tcd->isNested())
{
/* e1 is the 'this' pointer for an inner class: tcd.
* Rewrite it as the 'this' pointer for the outer class.
*/
e1 = new DotVarExp(loc, e1, tcd->vthis);
e1->type = tcd->vthis->type;
e1->type = e1->type->addMod(t->mod);
// Do not call checkNestedRef()
//e1 = semantic(e1, sc);
// Skip up over nested functions, and get the enclosing
// class type.
int n = 0;
Dsymbol *s;
for (s = tcd->toParent();
s && s->isFuncDeclaration();
s = s->toParent())
{
FuncDeclaration *f = s->isFuncDeclaration();
if (f->vthis)
{
//printf("rewriting e1 to %s's this\n", f->toChars());
n++;
e1 = new VarExp(loc, f->vthis);
}
else
{
e1->error("need 'this' of type %s to access member %s"
" from static function %s",
ad->toChars(), var->toChars(), f->toChars());
e1 = new ErrorExp();
return e1;
}
}
if (s && s->isClassDeclaration())
{
e1->type = s->isClassDeclaration()->type;
e1->type = e1->type->addMod(t->mod);
if (n > 1)
e1 = semantic(e1, sc);
}
else
e1 = semantic(e1, sc);
goto L1;
}
/* Can't find a path from e1 to ad
*/
if (flag)
return NULL;
e1->error("this for %s needs to be type %s not type %s",
var->toChars(), ad->toChars(), t->toChars());
return new ErrorExp();
}
}
return e1;
}
/*****************************************
* Determine if 'this' is available.
* If it is, return the FuncDeclaration that has it.
*/
FuncDeclaration *hasThis(Scope *sc)
{
//printf("hasThis()\n");
Dsymbol *p = sc->parent;
while (p && p->isTemplateMixin())
p = p->parent;
FuncDeclaration *fdthis = p ? p->isFuncDeclaration() : NULL;
//printf("fdthis = %p, '%s'\n", fdthis, fdthis ? fdthis->toChars() : "");
// Go upwards until we find the enclosing member function
FuncDeclaration *fd = fdthis;
while (1)
{
if (!fd)
{
goto Lno;
}
if (!fd->isNested())
break;
Dsymbol *parent = fd->parent;
while (1)
{
if (!parent)
goto Lno;
TemplateInstance *ti = parent->isTemplateInstance();
if (ti)
parent = ti->parent;
else
break;
}
fd = parent->isFuncDeclaration();
}
if (!fd->isThis())
{ //printf("test '%s'\n", fd->toChars());
goto Lno;
}
assert(fd->vthis);
return fd;
Lno:
return NULL; // don't have 'this' available
}
bool isNeedThisScope(Scope *sc, Declaration *d)
{
if (sc->intypeof == 1)
return false;
AggregateDeclaration *ad = d->isThis();
if (!ad)
return false;
//printf("d = %s, ad = %s\n", d->toChars(), ad->toChars());
for (Dsymbol *s = sc->parent; s; s = s->toParent2())
{
//printf("\ts = %s %s, toParent2() = %p\n", s->kind(), s->toChars(), s->toParent2());
if (AggregateDeclaration *ad2 = s->isAggregateDeclaration())
{
if (ad2 == ad)
return false;
else if (ad2->isNested())
continue;
else
return true;
}
if (FuncDeclaration *f = s->isFuncDeclaration())
{
if (f->isMember2())
break;
}
}
return true;
}
/***************************************
* Pull out any properties.
*/
Expression *resolvePropertiesX(Scope *sc, Expression *e1, Expression *e2 = NULL)
{
//printf("resolvePropertiesX, e1 = %s %s, e2 = %s\n", Token::toChars(e1->op), e1->toChars(), e2 ? e2->toChars() : NULL);
Loc loc = e1->loc;
OverloadSet *os;
Dsymbol *s;
Objects *tiargs;
Type *tthis;
if (e1->op == TOKdot)
{
DotExp *de = (DotExp *)e1;
if (de->e2->op == TOKoverloadset)
{
tiargs = NULL;
tthis = de->e1->type;
os = ((OverExp *)de->e2)->vars;
goto Los;
}
}
else if (e1->op == TOKoverloadset)
{
tiargs = NULL;
tthis = NULL;
os = ((OverExp *)e1)->vars;
Los:
assert(os);
FuncDeclaration *fd = NULL;
if (e2)
{
e2 = semantic(e2, sc);
if (e2->op == TOKerror)
return new ErrorExp();
e2 = resolveProperties(sc, e2);
Expressions a;
a.push(e2);
for (size_t i = 0; i < os->a.dim; i++)
{
FuncDeclaration *f = resolveFuncCall(loc, sc, os->a[i], tiargs, tthis, &a, 1);
if (f)
{
if (f->errors)
return new ErrorExp();
fd = f;
assert(fd->type->ty == Tfunction);
}
}
if (fd)
{
Expression *e = new CallExp(loc, e1, e2);
return semantic(e, sc);
}
}
{
for (size_t i = 0; i < os->a.dim; i++)
{
FuncDeclaration *f = resolveFuncCall(loc, sc, os->a[i], tiargs, tthis, NULL, 1);
if (f)
{
if (f->errors)
return new ErrorExp();
fd = f;
assert(fd->type->ty == Tfunction);
TypeFunction *tf = (TypeFunction *)fd->type;
if (!tf->isref && e2)
goto Leproplvalue;
}
}
if (fd)
{
Expression *e = new CallExp(loc, e1);
if (e2)
e = new AssignExp(loc, e, e2);
return semantic(e, sc);
}
}
if (e2)
goto Leprop;
}
else if (e1->op == TOKdotti)
{
DotTemplateInstanceExp* dti = (DotTemplateInstanceExp *)e1;
if (!dti->findTempDecl(sc))
goto Leprop;
if (!dti->ti->semanticTiargs(sc))
goto Leprop;
tiargs = dti->ti->tiargs;
tthis = dti->e1->type;
if ((os = dti->ti->tempdecl->isOverloadSet()) != NULL)
goto Los;
if ((s = dti->ti->tempdecl) != NULL)
goto Lfd;
}
else if (e1->op == TOKdottd)
{
DotTemplateExp *dte = (DotTemplateExp *)e1;
s = dte->td;
tiargs = NULL;
tthis = dte->e1->type;
goto Lfd;
}
else if (e1->op == TOKscope)
{
s = ((ScopeExp *)e1)->sds;
TemplateInstance *ti = s->isTemplateInstance();
if (ti && !ti->semanticRun && ti->tempdecl)
{
//assert(ti->needsTypeInference(sc));
if (!ti->semanticTiargs(sc))
goto Leprop;
tiargs = ti->tiargs;
tthis = NULL;
if ((os = ti->tempdecl->isOverloadSet()) != NULL)
goto Los;
if ((s = ti->tempdecl) != NULL)
goto Lfd;
}
}
else if (e1->op == TOKtemplate)
{
s = ((TemplateExp *)e1)->td;
tiargs = NULL;
tthis = NULL;
goto Lfd;
}
else if (e1->op == TOKdotvar && e1->type && e1->type->toBasetype()->ty == Tfunction)
{
DotVarExp *dve = (DotVarExp *)e1;
s = dve->var->isFuncDeclaration();
tiargs = NULL;
tthis = dve->e1->type;
goto Lfd;
}
else if (e1->op == TOKvar && e1->type && e1->type->toBasetype()->ty == Tfunction)
{
s = ((VarExp *)e1)->var->isFuncDeclaration();
tiargs = NULL;
tthis = NULL;
Lfd:
assert(s);
if (e2)
{
e2 = semantic(e2, sc);
if (e2->op == TOKerror)
return new ErrorExp();
e2 = resolveProperties(sc, e2);
Expressions a;
a.push(e2);
FuncDeclaration *fd = resolveFuncCall(loc, sc, s, tiargs, tthis, &a, 1);
if (fd && fd->type)
{
if (fd->errors)
return new ErrorExp();
assert(fd->type->ty == Tfunction);
Expression *e = new CallExp(loc, e1, e2);
return semantic(e, sc);
}
}
{
FuncDeclaration *fd = resolveFuncCall(loc, sc, s, tiargs, tthis, NULL, 1);
if (fd && fd->type)
{
if (fd->errors)
return new ErrorExp();
assert(fd->type->ty == Tfunction);
TypeFunction *tf = (TypeFunction *)fd->type;
if (!e2 || tf->isref)
{
Expression *e = new CallExp(loc, e1);
if (e2)
e = new AssignExp(loc, e, e2);
return semantic(e, sc);
}
}
}
if (FuncDeclaration *fd = s->isFuncDeclaration())
{
// Keep better diagnostic message for invalid property usage of functions
assert(fd->type->ty == Tfunction);
Expression *e = new CallExp(loc, e1, e2);
return semantic(e, sc);
}
if (e2)
goto Leprop;
}
if (e1->op == TOKvar)
{
VarExp *ve = (VarExp *)e1;
VarDeclaration *v = ve->var->isVarDeclaration();
if (v && ve->checkPurity(sc, v))
return new ErrorExp();
}
if (e2)
return NULL;
if (e1->type &&
e1->op != TOKtype) // function type is not a property
{
/* Look for e1 being a lazy parameter; rewrite as delegate call
*/
if (e1->op == TOKvar)
{
VarExp *ve = (VarExp *)e1;
if (ve->var->storage_class & STClazy)
{
Expression *e = new CallExp(loc, e1);
return semantic(e, sc);
}
}
else if (e1->op == TOKdotvar)
{
// Check for reading overlapped pointer field in @safe code.
if (checkUnsafeAccess(sc, e1, true, true))
return new ErrorExp();
}
else if (e1->op == TOKdot)
{
e1->error("expression has no value");
return new ErrorExp();
}
else if (e1->op == TOKcall)
{
CallExp *ce = (CallExp *)e1;
// Check for reading overlapped pointer field in @safe code.
if (checkUnsafeAccess(sc, ce->e1, true, true))
return new ErrorExp();
}
}
if (!e1->type)
{
error(loc, "cannot resolve type for %s", e1->toChars());
e1 = new ErrorExp();
}
return e1;
Leprop:
error(loc, "not a property %s", e1->toChars());
return new ErrorExp();
Leproplvalue:
error(loc, "%s is not an lvalue", e1->toChars());
return new ErrorExp();
}
Expression *resolveProperties(Scope *sc, Expression *e)
{
//printf("resolveProperties(%s)\n", e->toChars());
e = resolvePropertiesX(sc, e);
if (e->checkRightThis(sc))
return new ErrorExp();
return e;
}
/******************************
* Check the tail CallExp is really property function call.
*/
static bool checkPropertyCall(Expression *e)
{
while (e->op == TOKcomma)
e = ((CommaExp *)e)->e2;
if (e->op == TOKcall)
{
CallExp *ce = (CallExp *)e;
TypeFunction *tf;
if (ce->f)
{
tf = (TypeFunction *)ce->f->type;
/* If a forward reference to ce->f, try to resolve it
*/
if (!tf->deco && ce->f->_scope)
{
ce->f->semantic(ce->f->_scope);
tf = (TypeFunction *)ce->f->type;
}
}
else if (ce->e1->type->ty == Tfunction)
tf = (TypeFunction *)ce->e1->type;
else if (ce->e1->type->ty == Tdelegate)
tf = (TypeFunction *)ce->e1->type->nextOf();
else if (ce->e1->type->ty == Tpointer && ce->e1->type->nextOf()->ty == Tfunction)
tf = (TypeFunction *)ce->e1->type->nextOf();
else
assert(0);
}
return false;
}
/******************************
* If e1 is a property function (template), resolve it.
*/
Expression *resolvePropertiesOnly(Scope *sc, Expression *e1)
{
//printf("e1 = %s %s\n", Token::toChars(e1->op), e1->toChars());
OverloadSet *os;
FuncDeclaration *fd;
TemplateDeclaration *td;
if (e1->op == TOKdot)
{
DotExp *de = (DotExp *)e1;
if (de->e2->op == TOKoverloadset)
{
os = ((OverExp *)de->e2)->vars;
goto Los;
}
}
else if (e1->op == TOKoverloadset)
{
os = ((OverExp *)e1)->vars;
Los:
assert(os);
for (size_t i = 0; i < os->a.dim; i++)
{
Dsymbol *s = os->a[i];
fd = s->isFuncDeclaration();
td = s->isTemplateDeclaration();
if (fd)
{
if (((TypeFunction *)fd->type)->isproperty)
return resolveProperties(sc, e1);
}
else if (td && td->onemember &&
(fd = td->onemember->isFuncDeclaration()) != NULL)
{
if (((TypeFunction *)fd->type)->isproperty ||
(fd->storage_class2 & STCproperty) ||
(td->_scope->stc & STCproperty))
{
return resolveProperties(sc, e1);
}
}
}
}
else if (e1->op == TOKdotti)
{
DotTemplateInstanceExp* dti = (DotTemplateInstanceExp *)e1;
if (dti->ti->tempdecl && (td = dti->ti->tempdecl->isTemplateDeclaration()) != NULL)
goto Ltd;
}
else if (e1->op == TOKdottd)
{
td = ((DotTemplateExp *)e1)->td;
goto Ltd;
}
else if (e1->op == TOKscope)
{
Dsymbol *s = ((ScopeExp *)e1)->sds;
TemplateInstance *ti = s->isTemplateInstance();
if (ti && !ti->semanticRun && ti->tempdecl)
{
if ((td = ti->tempdecl->isTemplateDeclaration()) != NULL)
goto Ltd;
}
}
else if (e1->op == TOKtemplate)
{
td = ((TemplateExp *)e1)->td;
Ltd:
assert(td);
if (td->onemember &&
(fd = td->onemember->isFuncDeclaration()) != NULL)
{
if (((TypeFunction *)fd->type)->isproperty ||
(fd->storage_class2 & STCproperty) ||
(td->_scope->stc & STCproperty))
{
return resolveProperties(sc, e1);
}
}
}
else if (e1->op == TOKdotvar && e1->type->ty == Tfunction)
{
DotVarExp *dve = (DotVarExp *)e1;
fd = dve->var->isFuncDeclaration();
goto Lfd;
}
else if (e1->op == TOKvar && e1->type->ty == Tfunction &&
(sc->intypeof || !((VarExp *)e1)->var->needThis()))
{
fd = ((VarExp *)e1)->var->isFuncDeclaration();
Lfd:
assert(fd);
if (((TypeFunction *)fd->type)->isproperty)
return resolveProperties(sc, e1);
}
return e1;
}
// TODO: merge with Scope::search::searchScopes()
static Dsymbol *searchScopes(Scope *sc, Loc loc, Identifier *ident, int flags)
{
Dsymbol *s = NULL;
for (Scope *scx = sc; scx; scx = scx->enclosing)
{
if (!scx->scopesym)
continue;
if (scx->scopesym->isModule())
flags |= SearchUnqualifiedModule; // tell Module.search() that SearchLocalsOnly is to be obeyed
s = scx->scopesym->search(loc, ident, flags);
if (s)
{
// overload set contains only module scope symbols.
if (s->isOverloadSet())
break;
// selective/renamed imports also be picked up
if (AliasDeclaration *ad = s->isAliasDeclaration())
{
if (ad->_import)
break;
}
// See only module scope symbols for UFCS target.
Dsymbol *p = s->toParent2();
if (p && p->isModule())
break;
}
s = NULL;
// Stop when we hit a module, but keep going if that is not just under the global scope
if (scx->scopesym->isModule() && !(scx->enclosing && !scx->enclosing->enclosing))
break;
}
return s;
}
/******************************
* Find symbol in accordance with the UFCS name look up rule
*/
Expression *searchUFCS(Scope *sc, UnaExp *ue, Identifier *ident)
{
//printf("searchUFCS(ident = %s)\n", ident->toChars());
Loc loc = ue->loc;
int flags = 0;
Dsymbol *s = NULL;
if (sc->flags & SCOPEignoresymbolvisibility)
flags |= IgnoreSymbolVisibility;
Dsymbol *sold = NULL;
if (global.params.bug10378 || global.params.check10378)
{
sold = searchScopes(sc, loc, ident, flags | IgnoreSymbolVisibility);
if (!global.params.check10378)
{
s = sold;
goto Lsearchdone;
}
}
// First look in local scopes
s = searchScopes(sc, loc, ident, flags | SearchLocalsOnly);
if (!s)
{
// Second look in imported modules
s = searchScopes(sc, loc, ident, flags | SearchImportsOnly);
/** Still find private symbols, so that symbols that weren't access
* checked by the compiler remain usable. Once the deprecation is over,
* this should be moved to search_correct instead.
*/
if (!s && !(flags & IgnoreSymbolVisibility))
{
s = searchScopes(sc, loc, ident, flags | SearchLocalsOnly | IgnoreSymbolVisibility);
if (!s)
s = searchScopes(sc, loc, ident, flags | SearchImportsOnly | IgnoreSymbolVisibility);
if (s)
::deprecation(loc, "%s is not visible from module %s", s->toPrettyChars(), sc->_module->toChars());
}
}
if (global.params.check10378)
{
Dsymbol *snew = s;
if (sold != snew)
Scope::deprecation10378(loc, sold, snew);
if (global.params.bug10378)
s = sold;
}
Lsearchdone:
if (!s)
return ue->e1->type->Type::getProperty(loc, ident, 0);
FuncDeclaration *f = s->isFuncDeclaration();
if (f)
{
TemplateDeclaration *td = getFuncTemplateDecl(f);
if (td)
{
if (td->overroot)
td = td->overroot;
s = td;
}
}
if (ue->op == TOKdotti)
{
DotTemplateInstanceExp *dti = (DotTemplateInstanceExp *)ue;
TemplateInstance *ti = new TemplateInstance(loc, s->ident);
ti->tiargs = dti->ti->tiargs; // for better diagnostic message
if (!ti->updateTempDecl(sc, s))
return new ErrorExp();
return new ScopeExp(loc, ti);
}
else
{
//printf("-searchUFCS() %s\n", s->toChars());
return new DsymbolExp(loc, s);
}
}
/******************************
* check e is exp.opDispatch!(tiargs) or not
* It's used to switch to UFCS the semantic analysis path
*/
bool isDotOpDispatch(Expression *e)
{
return e->op == TOKdotti &&
((DotTemplateInstanceExp *)e)->ti->name == Id::opDispatch;
}
/******************************
* Pull out callable entity with UFCS.
*/
Expression *resolveUFCS(Scope *sc, CallExp *ce)
{
Loc loc = ce->loc;
Expression *eleft;
Expression *e;
if (ce->e1->op == TOKdotid)
{
DotIdExp *die = (DotIdExp *)ce->e1;
Identifier *ident = die->ident;
Expression *ex = semanticX(die, sc);
if (ex != die)
{
ce->e1 = ex;
return NULL;
}
eleft = die->e1;
Type *t = eleft->type->toBasetype();
if (t->ty == Tarray || t->ty == Tsarray ||
t->ty == Tnull || (t->isTypeBasic() && t->ty != Tvoid))
{
/* Built-in types and arrays have no callable properties, so do shortcut.
* It is necessary in: e.init()
*/
}
else if (t->ty == Taarray)
{
if (ident == Id::remove)
{
/* Transform:
* aa.remove(arg) into delete aa[arg]
*/
if (!ce->arguments || ce->arguments->dim != 1)
{
ce->error("expected key as argument to aa.remove()");
return new ErrorExp();
}
if (!eleft->type->isMutable())
{
ce->error("cannot remove key from %s associative array %s",
MODtoChars(t->mod), eleft->toChars());
return new ErrorExp();
}
Expression *key = (*ce->arguments)[0];
key = semantic(key, sc);
key = resolveProperties(sc, key);
TypeAArray *taa = (TypeAArray *)t;
key = key->implicitCastTo(sc, taa->index);
if (key->checkValue())
return new ErrorExp();
semanticTypeInfo(sc, taa->index);
return new RemoveExp(loc, eleft, key);
}
}
else
{
if (Expression *ey = semanticY(die, sc, 1))
{
if (ey->op == TOKerror)
return ey;
ce->e1 = ey;
if (isDotOpDispatch(ey))
{
unsigned errors = global.startGagging();
e = semantic(ce->syntaxCopy(), sc);
if (!global.endGagging(errors))
return e;
/* fall down to UFCS */
}
else
return NULL;
}
}
e = searchUFCS(sc, die, ident);
}
else if (ce->e1->op == TOKdotti)
{
DotTemplateInstanceExp *dti = (DotTemplateInstanceExp *)ce->e1;
if (Expression *ey = semanticY(dti, sc, 1))
{
ce->e1 = ey;
return NULL;
}
eleft = dti->e1;
e = searchUFCS(sc, dti, dti->ti->name);
}
else
return NULL;
// Rewrite
ce->e1 = e;
if (!ce->arguments)
ce->arguments = new Expressions();
ce->arguments->shift(eleft);
return NULL;
}
/******************************
* Pull out property with UFCS.
*/
Expression *resolveUFCSProperties(Scope *sc, Expression *e1, Expression *e2 = NULL)
{
Loc loc = e1->loc;
Expression *eleft;
Expression *e;
if (e1->op == TOKdotid)
{
DotIdExp *die = (DotIdExp *)e1;
eleft = die->e1;
e = searchUFCS(sc, die, die->ident);
}
else if (e1->op == TOKdotti)
{
DotTemplateInstanceExp *dti;
dti = (DotTemplateInstanceExp *)e1;
eleft = dti->e1;
e = searchUFCS(sc, dti, dti->ti->name);
}
else
return NULL;
if (e == NULL)
return NULL;
// Rewrite
if (e2)
{
// run semantic without gagging
e2 = semantic(e2, sc);
/* f(e1) = e2
*/
Expression *ex = e->copy();
Expressions *a1 = new Expressions();
a1->setDim(1);
(*a1)[0] = eleft;
ex = new CallExp(loc, ex, a1);
ex = trySemantic(ex, sc);
/* f(e1, e2)
*/
Expressions *a2 = new Expressions();
a2->setDim(2);
(*a2)[0] = eleft;
(*a2)[1] = e2;
e = new CallExp(loc, e, a2);
if (ex)
{ // if fallback setter exists, gag errors
e = trySemantic(e, sc);
if (!e)
{ checkPropertyCall(ex);
ex = new AssignExp(loc, ex, e2);
return semantic(ex, sc);
}
}
else
{ // strict setter prints errors if fails
e = semantic(e, sc);
}
checkPropertyCall(e);
return e;
}
else
{
/* f(e1)
*/
Expressions *arguments = new Expressions();
arguments->setDim(1);
(*arguments)[0] = eleft;
e = new CallExp(loc, e, arguments);
e = semantic(e, sc);
checkPropertyCall(e);
return semantic(e, sc);
}
}
/******************************
* Perform semantic() on an array of Expressions.
*/
bool arrayExpressionSemantic(Expressions *exps, Scope *sc, bool preserveErrors)
{
bool err = false;
if (exps)
{
for (size_t i = 0; i < exps->dim; i++)
{
Expression *e = (*exps)[i];
if (e)
{
e = semantic(e, sc);
if (e->op == TOKerror)
err = true;
if (preserveErrors || e->op != TOKerror)
(*exps)[i] = e;
}
}
}
return err;
}
/****************************************
* Expand tuples.
* Input:
* exps aray of Expressions
* Output:
* exps rewritten in place
*/
void expandTuples(Expressions *exps)
{
//printf("expandTuples()\n");
if (exps)
{
for (size_t i = 0; i < exps->dim; i++)
{
Expression *arg = (*exps)[i];
if (!arg)
continue;
// Look for tuple with 0 members
if (arg->op == TOKtype)
{
TypeExp *e = (TypeExp *)arg;
if (e->type->toBasetype()->ty == Ttuple)
{
TypeTuple *tt = (TypeTuple *)e->type->toBasetype();
if (!tt->arguments || tt->arguments->dim == 0)
{
exps->remove(i);
if (i == exps->dim)
return;
i--;
continue;
}
}
}
// Inline expand all the tuples
while (arg->op == TOKtuple)
{
TupleExp *te = (TupleExp *)arg;
exps->remove(i); // remove arg
exps->insert(i, te->exps); // replace with tuple contents
if (i == exps->dim)
return; // empty tuple, no more arguments
(*exps)[i] = Expression::combine(te->e0, (*exps)[i]);
arg = (*exps)[i];
}
}
}
}
/****************************************
* Expand alias this tuples.
*/
TupleDeclaration *isAliasThisTuple(Expression *e)
{
if (!e->type)
return NULL;
Type *t = e->type->toBasetype();
Lagain:
if (Dsymbol *s = t->toDsymbol(NULL))
{
AggregateDeclaration *ad = s->isAggregateDeclaration();
if (ad)
{
s = ad->aliasthis;
if (s && s->isVarDeclaration())
{
TupleDeclaration *td = s->isVarDeclaration()->toAlias()->isTupleDeclaration();
if (td && td->isexp)
return td;
}
if (Type *att = t->aliasthisOf())
{
t = att;
goto Lagain;
}
}
}
return NULL;
}
int expandAliasThisTuples(Expressions *exps, size_t starti)
{
if (!exps || exps->dim == 0)
return -1;
for (size_t u = starti; u < exps->dim; u++)
{
Expression *exp = (*exps)[u];
TupleDeclaration *td = isAliasThisTuple(exp);
if (td)
{
exps->remove(u);
for (size_t i = 0; i<td->objects->dim; ++i)
{
Expression *e = isExpression((*td->objects)[i]);
assert(e);
assert(e->op == TOKdsymbol);
DsymbolExp *se = (DsymbolExp *)e;
Declaration *d = se->s->isDeclaration();
assert(d);
e = new DotVarExp(exp->loc, exp, d);
assert(d->type);
e->type = d->type;
exps->insert(u + i, e);
}
return (int)u;
}
}
return -1;
}
/****************************************
* The common type is determined by applying ?: to each pair.
* Output:
* exps[] properties resolved, implicitly cast to common type, rewritten in place
* *pt if pt is not NULL, set to the common type
* Returns:
* true a semantic error was detected
*/
bool arrayExpressionToCommonType(Scope *sc, Expressions *exps, Type **pt)
{
/* Still have a problem with:
* ubyte[][] = [ cast(ubyte[])"hello", [1]];
* which works if the array literal is initialized top down with the ubyte[][]
* type, but fails with this function doing bottom up typing.
*/
//printf("arrayExpressionToCommonType()\n");
IntegerExp integerexp(0);
CondExp condexp(Loc(), &integerexp, NULL, NULL);
Type *t0 = NULL;
Expression *e0 = NULL; // dead-store to prevent spurious warning
size_t j0 = ~0; // dead-store to prevent spurious warning
for (size_t i = 0; i < exps->dim; i++)
{
Expression *e = (*exps)[i];
if (!e)
continue;
e = resolveProperties(sc, e);
if (!e->type)
{
e->error("%s has no value", e->toChars());
t0 = Type::terror;
continue;
}
if (e->op == TOKtype)
{
e->checkValue(); // report an error "type T has no value"
t0 = Type::terror;
continue;
}
if (e->type->ty == Tvoid)
{
// void expressions do not concur to the determination of the common
// type.
continue;
}
if (checkNonAssignmentArrayOp(e))
{
t0 = Type::terror;
continue;
}
e = doCopyOrMove(sc, e);
if (t0 && !t0->equals(e->type))
{
/* This applies ?: to merge the types. It's backwards;
* ?: should call this function to merge types.
*/
condexp.type = NULL;
condexp.e1 = e0;
condexp.e2 = e;
condexp.loc = e->loc;
Expression *ex = semantic(&condexp, sc);
if (ex->op == TOKerror)
e = ex;
else
{
(*exps)[j0] = condexp.e1;
e = condexp.e2;
}
}
j0 = i;
e0 = e;
t0 = e->type;
if (e->op != TOKerror)
(*exps)[i] = e;
}
if (!t0)
t0 = Type::tvoid; // [] is typed as void[]
else if (t0->ty != Terror)
{
for (size_t i = 0; i < exps->dim; i++)
{
Expression *e = (*exps)[i];
if (!e)
continue;
e = e->implicitCastTo(sc, t0);
//assert(e->op != TOKerror);
if (e->op == TOKerror)
{
/* Bugzilla 13024: a workaround for the bug in typeMerge -
* it should paint e1 and e2 by deduced common type,
* but doesn't in this particular case.
*/
t0 = Type::terror;
break;
}
(*exps)[i] = e;
}
}
if (pt)
*pt = t0;
return (t0 == Type::terror);
}
/****************************************
* Get TemplateDeclaration enclosing FuncDeclaration.
*/
TemplateDeclaration *getFuncTemplateDecl(Dsymbol *s)
{
FuncDeclaration *f = s->isFuncDeclaration();
if (f && f->parent)
{
TemplateInstance *ti = f->parent->isTemplateInstance();
if (ti && !ti->isTemplateMixin() &&
ti->tempdecl && ((TemplateDeclaration *)ti->tempdecl)->onemember &&
ti->tempdecl->ident == f->ident)
{
return (TemplateDeclaration *)ti->tempdecl;
}
}
return NULL;
}
/************************************************
* If we want the value of this expression, but do not want to call
* the destructor on it.
*/
Expression *valueNoDtor(Expression *e)
{
if (e->op == TOKcall)
{
/* The struct value returned from the function is transferred
* so do not call the destructor on it.
* Recognize:
* ((S _ctmp = S.init), _ctmp).this(...)
* and make sure the destructor is not called on _ctmp
* BUG: if e is a CommaExp, we should go down the right side.
*/
CallExp *ce = (CallExp *)e;
if (ce->e1->op == TOKdotvar)
{
DotVarExp *dve = (DotVarExp *)ce->e1;
if (dve->var->isCtorDeclaration())
{
// It's a constructor call
if (dve->e1->op == TOKcomma)
{
CommaExp *comma = (CommaExp *)dve->e1;
if (comma->e2->op == TOKvar)
{
VarExp *ve = (VarExp *)comma->e2;
VarDeclaration *ctmp = ve->var->isVarDeclaration();
if (ctmp)
{
ctmp->storage_class |= STCnodtor;
assert(!ce->isLvalue());
}
}
}
}
}
}
else if (e->op == TOKvar)
{
VarDeclaration *vtmp = ((VarExp *)e)->var->isVarDeclaration();
if (vtmp && vtmp->storage_class & STCrvalue)
{
vtmp->storage_class |= STCnodtor;
}
}
return e;
}
/********************************************
* Issue an error if default construction is disabled for type t.
* Default construction is required for arrays and 'out' parameters.
* Returns:
* true an error was issued
*/
bool checkDefCtor(Loc loc, Type *t)
{
t = t->baseElemOf();
if (t->ty == Tstruct)
{
StructDeclaration *sd = ((TypeStruct *)t)->sym;
if (sd->noDefaultCtor)
{
sd->error(loc, "default construction is disabled");
return true;
}
}
return false;
}
/*********************************************
* If e is an instance of a struct, and that struct has a copy constructor,
* rewrite e as:
* (tmp = e),tmp
* Input:
* sc just used to specify the scope of created temporary variable
*/
Expression *callCpCtor(Scope *sc, Expression *e)
{
Type *tv = e->type->baseElemOf();
if (tv->ty == Tstruct)
{
StructDeclaration *sd = ((TypeStruct *)tv)->sym;
if (sd->postblit)
{
/* Create a variable tmp, and replace the argument e with:
* (tmp = e),tmp
* and let AssignExp() handle the construction.
* This is not the most efficent, ideally tmp would be constructed
* directly onto the stack.
*/
VarDeclaration *tmp = copyToTemp(STCrvalue, "__copytmp", e);
tmp->storage_class |= STCnodtor;
tmp->semantic(sc);
Expression *de = new DeclarationExp(e->loc, tmp);
Expression *ve = new VarExp(e->loc, tmp);
de->type = Type::tvoid;
ve->type = e->type;
e = Expression::combine(de, ve);
}
}
return e;
}
/************************************************
* Handle the postblit call on lvalue, or the move of rvalue.
*/
Expression *doCopyOrMove(Scope *sc, Expression *e)
{
if (e->op == TOKquestion)
{
CondExp *ce = (CondExp *)e;
ce->e1 = doCopyOrMove(sc, ce->e1);
ce->e2 = doCopyOrMove(sc, ce->e2);
}
else
{
e = e->isLvalue() ? callCpCtor(sc, e) : valueNoDtor(e);
}
return e;
}
/****************************************
* Now that we know the exact type of the function we're calling,
* the arguments[] need to be adjusted:
* 1. implicitly convert argument to the corresponding parameter type
* 2. add default arguments for any missing arguments
* 3. do default promotions on arguments corresponding to ...
* 4. add hidden _arguments[] argument
* 5. call copy constructor for struct value arguments
* Input:
* tf type of the function
* fd the function being called, NULL if called indirectly
* Output:
* *prettype return type of function
* *peprefix expression to execute before arguments[] are evaluated, NULL if none
* Returns:
* true errors happened
*/
bool functionParameters(Loc loc, Scope *sc, TypeFunction *tf,
Type *tthis, Expressions *arguments, FuncDeclaration *fd, Type **prettype, Expression **peprefix)
{
//printf("functionParameters()\n");
assert(arguments);
assert(fd || tf->next);
size_t nargs = arguments ? arguments->dim : 0;
size_t nparams = Parameter::dim(tf->parameters);
unsigned olderrors = global.errors;
bool err = false;
*prettype = Type::terror;
Expression *eprefix = NULL;
*peprefix = NULL;
if (nargs > nparams && tf->varargs == 0)
{
error(loc, "expected %llu arguments, not %llu for non-variadic function type %s", (ulonglong)nparams, (ulonglong)nargs, tf->toChars());
return true;
}
// If inferring return type, and semantic3() needs to be run if not already run
if (!tf->next && fd->inferRetType)
{
fd->functionSemantic();
}
else if (fd && fd->parent)
{
TemplateInstance *ti = fd->parent->isTemplateInstance();
if (ti && ti->tempdecl)
{
fd->functionSemantic3();
}
}
bool isCtorCall = fd && fd->needThis() && fd->isCtorDeclaration();
size_t n = (nargs > nparams) ? nargs : nparams; // n = max(nargs, nparams)
/* If the function return type has wildcards in it, we'll need to figure out the actual type
* based on the actual argument types.
*/
MOD wildmatch = 0;
if (tthis && tf->isWild() && !isCtorCall)
{
Type *t = tthis;
if (t->isImmutable())
wildmatch = MODimmutable;
else if (t->isWildConst())
wildmatch = MODwildconst;
else if (t->isWild())
wildmatch = MODwild;
else if (t->isConst())
wildmatch = MODconst;
else
wildmatch = MODmutable;
}
int done = 0;
for (size_t i = 0; i < n; i++)
{
Expression *arg;
if (i < nargs)
arg = (*arguments)[i];
else
arg = NULL;
if (i < nparams)
{
Parameter *p = Parameter::getNth(tf->parameters, i);
if (!arg)
{
if (!p->defaultArg)
{
if (tf->varargs == 2 && i + 1 == nparams)
goto L2;
error(loc, "expected %llu function arguments, not %llu", (ulonglong)nparams, (ulonglong)nargs);
return true;
}
arg = p->defaultArg;
arg = inlineCopy(arg, sc);
// __FILE__, __LINE__, __MODULE__, __FUNCTION__, and __PRETTY_FUNCTION__
arg = arg->resolveLoc(loc, sc);
arguments->push(arg);
nargs++;
}
if (tf->varargs == 2 && i + 1 == nparams)
{
//printf("\t\tvarargs == 2, p->type = '%s'\n", p->type->toChars());
{
MATCH m;
if ((m = arg->implicitConvTo(p->type)) > MATCHnomatch)
{
if (p->type->nextOf() && arg->implicitConvTo(p->type->nextOf()) >= m)
goto L2;
else if (nargs != nparams)
{ error(loc, "expected %llu function arguments, not %llu", (ulonglong)nparams, (ulonglong)nargs);
return true;
}
goto L1;
}
}
L2:
Type *tb = p->type->toBasetype();
Type *tret = p->isLazyArray();
switch (tb->ty)
{
case Tsarray:
case Tarray:
{
/* Create a static array variable v of type arg->type:
* T[dim] __arrayArg = [ arguments[i], ..., arguments[nargs-1] ];
*
* The array literal in the initializer of the hidden variable
* is now optimized. See Bugzilla 2356.
*/
Type *tbn = ((TypeArray *)tb)->next;
Expressions *elements = new Expressions();
elements->setDim(nargs - i);
for (size_t u = 0; u < elements->dim; u++)
{
Expression *a = (*arguments)[i + u];
if (tret && a->implicitConvTo(tret))
{
a = a->implicitCastTo(sc, tret);
a = a->optimize(WANTvalue);
a = toDelegate(a, a->type, sc);
}
else
a = a->implicitCastTo(sc, tbn);
(*elements)[u] = a;
}
// Bugzilla 14395: Convert to a static array literal, or its slice.
arg = new ArrayLiteralExp(loc, tbn->sarrayOf(nargs - i), elements);
if (tb->ty == Tarray)
{
arg = new SliceExp(loc, arg, NULL, NULL);
arg->type = p->type;
}
break;
}
case Tclass:
{
/* Set arg to be:
* new Tclass(arg0, arg1, ..., argn)
*/
Expressions *args = new Expressions();
args->setDim(nargs - i);
for (size_t u = i; u < nargs; u++)
(*args)[u - i] = (*arguments)[u];
arg = new NewExp(loc, NULL, NULL, p->type, args);
break;
}
default:
if (!arg)
{
error(loc, "not enough arguments");
return true;
}
break;
}
arg = semantic(arg, sc);
//printf("\targ = '%s'\n", arg->toChars());
arguments->setDim(i + 1);
(*arguments)[i] = arg;
nargs = i + 1;
done = 1;
}
L1:
if (!(p->storageClass & STClazy && p->type->ty == Tvoid))
{
bool isRef = (p->storageClass & (STCref | STCout)) != 0;
if (unsigned char wm = arg->type->deduceWild(p->type, isRef))
{
if (wildmatch)
wildmatch = MODmerge(wildmatch, wm);
else
wildmatch = wm;
//printf("[%d] p = %s, a = %s, wm = %d, wildmatch = %d\n", i, p->type->toChars(), arg->type->toChars(), wm, wildmatch);
}
}
}
if (done)
break;
}
if ((wildmatch == MODmutable || wildmatch == MODimmutable) &&
tf->next->hasWild() &&
(tf->isref || !tf->next->implicitConvTo(tf->next->immutableOf())))
{
if (fd)
{
/* If the called function may return the reference to
* outer inout data, it should be rejected.
*
* void foo(ref inout(int) x) {
* ref inout(int) bar(inout(int)) { return x; }
* struct S { ref inout(int) bar() inout { return x; } }
* bar(int.init) = 1; // bad!
* S().bar() = 1; // bad!
* }
*/
Dsymbol *s = NULL;
if (fd->isThis() || fd->isNested())
s = fd->toParent2();
for (; s; s = s->toParent2())
{
if (AggregateDeclaration *ad = s->isAggregateDeclaration())
{
if (ad->isNested())
continue;
break;
}
if (FuncDeclaration *ff = s->isFuncDeclaration())
{
if (((TypeFunction *)ff->type)->iswild)
goto Linouterr;
if (ff->isNested() || ff->isThis())
continue;
}
break;
}
}
else if (tf->isWild())
{
Linouterr:
const char *s = wildmatch == MODmutable ? "mutable" : MODtoChars(wildmatch);
error(loc, "modify inout to %s is not allowed inside inout function", s);
return true;
}
}
assert(nargs >= nparams);
for (size_t i = 0; i < nargs; i++)
{
Expression *arg = (*arguments)[i];
assert(arg);
if (i < nparams)
{
Parameter *p = Parameter::getNth(tf->parameters, i);
if (!(p->storageClass & STClazy && p->type->ty == Tvoid))
{
Type *tprm = p->type;
if (p->type->hasWild())
tprm = p->type->substWildTo(wildmatch);
if (!tprm->equals(arg->type))
{
//printf("arg->type = %s, p->type = %s\n", arg->type->toChars(), p->type->toChars());
arg = arg->implicitCastTo(sc, tprm);
arg = arg->optimize(WANTvalue, (p->storageClass & (STCref | STCout)) != 0);
}
}
if (p->storageClass & STCref)
{
arg = arg->toLvalue(sc, arg);
// Look for mutable misaligned pointer, etc., in @safe mode
err |= checkUnsafeAccess(sc, arg, false, true);
}
else if (p->storageClass & STCout)
{
Type *t = arg->type;
if (!t->isMutable() || !t->isAssignable()) // check blit assignable
{
arg->error("cannot modify struct %s with immutable members", arg->toChars());
err = true;
}
else
{
// Look for misaligned pointer, etc., in @safe mode
err |= checkUnsafeAccess(sc, arg, false, true);
err |= checkDefCtor(arg->loc, t); // t must be default constructible
}
arg = arg->toLvalue(sc, arg);
}
else if (p->storageClass & STClazy)
{
// Convert lazy argument to a delegate
if (p->type->ty == Tvoid)
arg = toDelegate(arg, p->type, sc);
else
arg = toDelegate(arg, arg->type, sc);
}
//printf("arg: %s\n", arg->toChars());
//printf("type: %s\n", arg->type->toChars());
if (tf->parameterEscapes(p))
{
/* Argument value can escape from the called function.
* Check arg to see if it matters.
*/
if (global.params.vsafe)
err |= checkParamArgumentEscape(sc, fd, p->ident, arg, false);
}
else
{
/* Argument value cannot escape from the called function.
*/
Expression *a = arg;
if (a->op == TOKcast)
a = ((CastExp *)a)->e1;
if (a->op == TOKfunction)
{
/* Function literals can only appear once, so if this
* appearance was scoped, there cannot be any others.
*/
FuncExp *fe = (FuncExp *)a;
fe->fd->tookAddressOf = 0;
}
else if (a->op == TOKdelegate)
{
/* For passing a delegate to a scoped parameter,
* this doesn't count as taking the address of it.
* We only worry about 'escaping' references to the function.
*/
DelegateExp *de = (DelegateExp *)a;
if (de->e1->op == TOKvar)
{ VarExp *ve = (VarExp *)de->e1;
FuncDeclaration *f = ve->var->isFuncDeclaration();
if (f)
{ f->tookAddressOf--;
//printf("tookAddressOf = %d\n", f->tookAddressOf);
}
}
}
}
arg = arg->optimize(WANTvalue, (p->storageClass & (STCref | STCout)) != 0);
}
else
{
// These will be the trailing ... arguments
// If not D linkage, do promotions
if (tf->linkage != LINKd)
{
// Promote bytes, words, etc., to ints
arg = integralPromotions(arg, sc);
// Promote floats to doubles
switch (arg->type->ty)
{
case Tfloat32:
arg = arg->castTo(sc, Type::tfloat64);
break;
case Timaginary32:
arg = arg->castTo(sc, Type::timaginary64);
break;
}
if (tf->varargs == 1)
{
const char *p = tf->linkage == LINKc ? "extern(C)" : "extern(C++)";
if (arg->type->ty == Tarray)
{
arg->error("cannot pass dynamic arrays to %s vararg functions", p);
err = true;
}
if (arg->type->ty == Tsarray)
{
arg->error("cannot pass static arrays to %s vararg functions", p);
err = true;
}
}
}
// Do not allow types that need destructors
if (arg->type->needsDestruction())
{
arg->error("cannot pass types that need destruction as variadic arguments");
err = true;
}
// Convert static arrays to dynamic arrays
// BUG: I don't think this is right for D2
Type *tb = arg->type->toBasetype();
if (tb->ty == Tsarray)
{
TypeSArray *ts = (TypeSArray *)tb;
Type *ta = ts->next->arrayOf();
if (ts->size(arg->loc) == 0)
arg = new NullExp(arg->loc, ta);
else
arg = arg->castTo(sc, ta);
}
if (tb->ty == Tstruct)
{
//arg = callCpCtor(sc, arg);
}
// Give error for overloaded function addresses
if (arg->op == TOKsymoff)
{ SymOffExp *se = (SymOffExp *)arg;
if (se->hasOverloads &&
!se->var->isFuncDeclaration()->isUnique())
{ arg->error("function %s is overloaded", arg->toChars());
err = true;
}
}
if (arg->checkValue())
err = true;
arg = arg->optimize(WANTvalue);
}
(*arguments)[i] = arg;
}
/* Remaining problems:
* 1. order of evaluation - some function push L-to-R, others R-to-L. Until we resolve what array assignment does (which is
* implemented by calling a function) we'll defer this for now.
* 2. value structs (or static arrays of them) that need to be copy constructed
* 3. value structs (or static arrays of them) that have destructors, and subsequent arguments that may throw before the
* function gets called (functions normally destroy their parameters)
* 2 and 3 are handled by doing the argument construction in 'eprefix' so that if a later argument throws, they are cleaned
* up properly. Pushing arguments on the stack then cannot fail.
*/
if (1)
{
/* TODO: tackle problem 1)
*/
const bool leftToRight = true; // TODO: something like !fd.isArrayOp
if (!leftToRight)
assert(nargs == nparams); // no variadics for RTL order, as they would probably be evaluated LTR and so add complexity
const ptrdiff_t start = (leftToRight ? 0 : (ptrdiff_t)nargs - 1);
const ptrdiff_t end = (leftToRight ? (ptrdiff_t)nargs : -1);
const ptrdiff_t step = (leftToRight ? 1 : -1);
/* Compute indices of last throwing argument and first arg needing destruction.
* Used to not set up destructors unless an arg needs destruction on a throw
* in a later argument.
*/
ptrdiff_t lastthrow = -1;
ptrdiff_t firstdtor = -1;
for (ptrdiff_t i = start; i != end; i += step)
{
Expression *arg = (*arguments)[i];
if (canThrow(arg, sc->func, false))
lastthrow = i;
if (firstdtor == -1 && arg->type->needsDestruction())
{
Parameter *p = (i >= (ptrdiff_t)nparams ? NULL : Parameter::getNth(tf->parameters, i));
if (!(p && (p->storageClass & (STClazy | STCref | STCout))))
firstdtor = i;
}
}
/* Does problem 3) apply to this call?
*/
const bool needsPrefix = (firstdtor >= 0 && lastthrow >= 0
&& (lastthrow - firstdtor) * step > 0);
/* If so, initialize 'eprefix' by declaring the gate
*/
VarDeclaration *gate = NULL;
if (needsPrefix)
{
// eprefix => bool __gate [= false]
Identifier *idtmp = Identifier::generateId("__gate");
gate = new VarDeclaration(loc, Type::tbool, idtmp, NULL);
gate->storage_class |= STCtemp | STCctfe | STCvolatile;
gate->semantic(sc);
Expression *ae = new DeclarationExp(loc, gate);
eprefix = semantic(ae, sc);
}
for (ptrdiff_t i = start; i != end; i += step)
{
Expression *arg = (*arguments)[i];
Parameter *parameter = (i >= (ptrdiff_t)nparams ? NULL : Parameter::getNth(tf->parameters, i));
const bool isRef = (parameter && (parameter->storageClass & (STCref | STCout)));
const bool isLazy = (parameter && (parameter->storageClass & STClazy));
/* Skip lazy parameters
*/
if (isLazy)
continue;
/* Do we have a gate? Then we have a prefix and we're not yet past the last throwing arg.
* Declare a temporary variable for this arg and append that declaration to 'eprefix',
* which will implicitly take care of potential problem 2) for this arg.
* 'eprefix' will therefore finally contain all args up to and including the last
* potentially throwing arg, excluding all lazy parameters.
*/
if (gate)
{
const bool needsDtor = (!isRef && arg->type->needsDestruction() && i != lastthrow);
/* Declare temporary 'auto __pfx = arg' (needsDtor) or 'auto __pfy = arg' (!needsDtor)
*/
VarDeclaration *tmp = copyToTemp(0,
needsDtor ? "__pfx" : "__pfy",
!isRef ? arg : arg->addressOf());
tmp->semantic(sc);
/* Modify the destructor so it only runs if gate==false, i.e.,
* only if there was a throw while constructing the args
*/
if (!needsDtor)
{
if (tmp->edtor)
{
assert(i == lastthrow);
tmp->edtor = NULL;
}
}
else
{
// edtor => (__gate || edtor)
assert(tmp->edtor);
Expression *e = tmp->edtor;
e = new OrOrExp(e->loc, new VarExp(e->loc, gate), e);
tmp->edtor = semantic(e, sc);
//printf("edtor: %s\n", tmp->edtor->toChars());
}
// eprefix => (eprefix, auto __pfx/y = arg)
DeclarationExp *ae = new DeclarationExp(loc, tmp);
eprefix = Expression::combine(eprefix, semantic(ae, sc));
// arg => __pfx/y
arg = new VarExp(loc, tmp);
arg = semantic(arg, sc);
if (isRef)
{
arg = new PtrExp(loc, arg);
arg = semantic(arg, sc);
}
/* Last throwing arg? Then finalize eprefix => (eprefix, gate = true),
* i.e., disable the dtors right after constructing the last throwing arg.
* From now on, the callee will take care of destructing the args because
* the args are implicitly moved into function parameters.
*
* Set gate to null to let the next iterations know they don't need to
* append to eprefix anymore.
*/
if (i == lastthrow)
{
Expression *e = new AssignExp(gate->loc, new VarExp(gate->loc, gate), new IntegerExp(gate->loc, 1, Type::tbool));
eprefix = Expression::combine(eprefix, semantic(e, sc));
gate = NULL;
}
}
else
{
/* No gate, no prefix to append to.
* Handle problem 2) by calling the copy constructor for value structs
* (or static arrays of them) if appropriate.
*/
Type *tv = arg->type->baseElemOf();
if (!isRef && tv->ty == Tstruct)
arg = doCopyOrMove(sc, arg);
}
(*arguments)[i] = arg;
}
}
//if (eprefix) printf("eprefix: %s\n", eprefix->toChars());
// If D linkage and variadic, add _arguments[] as first argument
if (tf->linkage == LINKd && tf->varargs == 1)
{
assert(arguments->dim >= nparams);
Parameters *args = new Parameters;
args->setDim(arguments->dim - nparams);
for (size_t i = 0; i < arguments->dim - nparams; i++)
{
Parameter *arg = new Parameter(STCin, (*arguments)[nparams + i]->type, NULL, NULL);
(*args)[i] = arg;
}
TypeTuple *tup = new TypeTuple(args);
Expression *e = new TypeidExp(loc, tup);
e = semantic(e, sc);
arguments->insert(0, e);
}
Type *tret = tf->next;
if (isCtorCall)
{
//printf("[%s] fd = %s %s, %d %d %d\n", loc.toChars(), fd->toChars(), fd->type->toChars(),
// wildmatch, tf->isWild(), fd->isolateReturn());
if (!tthis)
{
assert(sc->intypeof || global.errors);
tthis = fd->isThis()->type->addMod(fd->type->mod);
}
if (tf->isWild() && !fd->isolateReturn())
{
if (wildmatch)
tret = tret->substWildTo(wildmatch);
int offset;
if (!tret->implicitConvTo(tthis) &&
!(MODimplicitConv(tret->mod, tthis->mod) && tret->isBaseOf(tthis, &offset) && offset == 0))
{
const char* s1 = tret ->isNaked() ? " mutable" : tret ->modToChars();
const char* s2 = tthis->isNaked() ? " mutable" : tthis->modToChars();
::error(loc, "inout constructor %s creates%s object, not%s",
fd->toPrettyChars(), s1, s2);
err = true;
}
}
tret = tthis;
}
else if (wildmatch && tret)
{
/* Adjust function return type based on wildmatch
*/
//printf("wildmatch = x%x, tret = %s\n", wildmatch, tret->toChars());
tret = tret->substWildTo(wildmatch);
}
*prettype = tret;
*peprefix = eprefix;
return (err || olderrors != global.errors);
}
/******************************** Expression **************************/
Expression::Expression(Loc loc, TOK op, int size)
{
//printf("Expression::Expression(op = %d) this = %p\n", op, this);
this->loc = loc;
this->op = op;
this->size = (unsigned char)size;
this->parens = 0;
type = NULL;
}
void Expression::_init()
{
CTFEExp::cantexp = new CTFEExp(TOKcantexp);
CTFEExp::voidexp = new CTFEExp(TOKvoidexp);
CTFEExp::breakexp = new CTFEExp(TOKbreak);
CTFEExp::continueexp = new CTFEExp(TOKcontinue);
CTFEExp::gotoexp = new CTFEExp(TOKgoto);
}
Expression *Expression::syntaxCopy()
{
//printf("Expression::syntaxCopy()\n");
//print();
return copy();
}
/*********************************
* Does *not* do a deep copy.
*/
Expression *Expression::copy()
{
Expression *e;
if (!size)
{
assert(0);
}
void *pe = mem.xmalloc(size);
//printf("Expression::copy(op = %d) e = %p\n", op, pe);
e = (Expression *)memcpy(pe, (void *)this, size);
return e;
}
void Expression::print()
{
fprintf(stderr, "%s\n", toChars());
fflush(stderr);
}
const char *Expression::toChars()
{
OutBuffer buf;
HdrGenState hgs;
toCBuffer(this, &buf, &hgs);
return buf.extractString();
}
void Expression::error(const char *format, ...) const
{
if (type != Type::terror)
{
va_list ap;
va_start(ap, format);
::verror(loc, format, ap);
va_end( ap );
}
}
void Expression::warning(const char *format, ...) const
{
if (type != Type::terror)
{
va_list ap;
va_start(ap, format);
::vwarning(loc, format, ap);
va_end( ap );
}
}
void Expression::deprecation(const char *format, ...) const
{
if (type != Type::terror)
{
va_list ap;
va_start(ap, format);
::vdeprecation(loc, format, ap);
va_end( ap );
}
}
/**********************************
* Combine e1 and e2 by CommaExp if both are not NULL.
*/
Expression *Expression::combine(Expression *e1, Expression *e2)
{
if (e1)
{
if (e2)
{
e1 = new CommaExp(e1->loc, e1, e2);
e1->type = e2->type;
}
}
else
e1 = e2;
return e1;
}
/**********************************
* If 'e' is a tree of commas, returns the leftmost expression
* by stripping off it from the tree. The remained part of the tree
* is returned via *pe0.
* Otherwise 'e' is directly returned and *pe0 is set to NULL.
*/
Expression *Expression::extractLast(Expression *e, Expression **pe0)
{
if (e->op != TOKcomma)
{
*pe0 = NULL;
return e;
}
CommaExp *ce = (CommaExp *)e;
if (ce->e2->op != TOKcomma)
{
*pe0 = ce->e1;
return ce->e2;
}
else
{
*pe0 = e;
Expression **pce = &ce->e2;
while (((CommaExp *)(*pce))->e2->op == TOKcomma)
{
pce = &((CommaExp *)(*pce))->e2;
}
assert((*pce)->op == TOKcomma);
ce = (CommaExp *)(*pce);
*pce = ce->e1;
return ce->e2;
}
}
dinteger_t Expression::toInteger()
{
//printf("Expression %s\n", Token::toChars(op));
error("integer constant expression expected instead of %s", toChars());
return 0;
}
uinteger_t Expression::toUInteger()
{
//printf("Expression %s\n", Token::toChars(op));
return (uinteger_t)toInteger();
}
real_t Expression::toReal()
{
error("floating point constant expression expected instead of %s", toChars());
return CTFloat::zero;
}
real_t Expression::toImaginary()
{
error("floating point constant expression expected instead of %s", toChars());
return CTFloat::zero;
}
complex_t Expression::toComplex()
{
error("floating point constant expression expected instead of %s", toChars());
return complex_t(CTFloat::zero);
}
StringExp *Expression::toStringExp()
{
return NULL;
}
/***************************************
* Return !=0 if expression is an lvalue.
*/
bool Expression::isLvalue()
{
return false;
}
/*******************************
* Give error if we're not an lvalue.
* If we can, convert expression to be an lvalue.
*/
Expression *Expression::toLvalue(Scope *, Expression *e)
{
if (!e)
e = this;
else if (!loc.filename)
loc = e->loc;
if (e->op == TOKtype)
error("%s '%s' is a type, not an lvalue", e->type->kind(), e->type->toChars());
else
error("%s is not an lvalue", e->toChars());
return new ErrorExp();
}
/***************************************
* Parameters:
* sc: scope
* flag: 1: do not issue error message for invalid modification
* Returns:
* 0: is not modifiable
* 1: is modifiable in default == being related to type->isMutable()
* 2: is modifiable, because this is a part of initializing.
*/
int Expression::checkModifiable(Scope *, int)
{
return type ? 1 : 0; // default modifiable
}
Expression *Expression::modifiableLvalue(Scope *sc, Expression *e)
{
//printf("Expression::modifiableLvalue() %s, type = %s\n", toChars(), type->toChars());
// See if this expression is a modifiable lvalue (i.e. not const)
if (checkModifiable(sc) == 1)
{
assert(type);
if (!type->isMutable())
{
error("cannot modify %s expression %s", MODtoChars(type->mod), toChars());
return new ErrorExp();
}
else if (!type->isAssignable())
{
error("cannot modify struct %s %s with immutable members", toChars(), type->toChars());
return new ErrorExp();
}
}
return toLvalue(sc, e);
}
/****************************************
* Check that the expression has a valid type.
* If not, generates an error "... has no type".
* Returns:
* true if the expression is not valid.
* Note:
* When this function returns true, `checkValue()` should also return true.
*/
bool Expression::checkType()
{
return false;
}
/****************************************
* Check that the expression has a valid value.
* If not, generates an error "... has no value".
* Returns:
* true if the expression is not valid or has void type.
*/
bool Expression::checkValue()
{
if (type && type->toBasetype()->ty == Tvoid)
{
error("expression %s is void and has no value", toChars());
//print(); halt();
if (!global.gag)
type = Type::terror;
return true;
}
return false;
}
bool Expression::checkScalar()
{
if (op == TOKerror)
return true;
if (type->toBasetype()->ty == Terror)
return true;
if (!type->isscalar())
{
error("'%s' is not a scalar, it is a %s", toChars(), type->toChars());
return true;
}
return checkValue();
}
bool Expression::checkNoBool()
{
if (op == TOKerror)
return true;
if (type->toBasetype()->ty == Terror)
return true;
if (type->toBasetype()->ty == Tbool)
{
error("operation not allowed on bool '%s'", toChars());
return true;
}
return false;
}
bool Expression::checkIntegral()
{
if (op == TOKerror)
return true;
if (type->toBasetype()->ty == Terror)
return true;
if (!type->isintegral())
{
error("'%s' is not of integral type, it is a %s", toChars(), type->toChars());
return true;
}
return checkValue();
}
bool Expression::checkArithmetic()
{
if (op == TOKerror)
return true;
if (type->toBasetype()->ty == Terror)
return true;
if (!type->isintegral() && !type->isfloating())
{
error("'%s' is not of arithmetic type, it is a %s", toChars(), type->toChars());
return true;
}
return checkValue();
}
void Expression::checkDeprecated(Scope *sc, Dsymbol *s)
{
s->checkDeprecated(loc, sc);
}
/*********************************************
* Calling function f.
* Check the purity, i.e. if we're in a pure function
* we can only call other pure functions.
* Returns true if error occurs.
*/
bool Expression::checkPurity(Scope *sc, FuncDeclaration *f)
{
if (!sc->func)
return false;
if (sc->func == f)
return false;
if (sc->intypeof == 1)
return false;
if (sc->flags & (SCOPEctfe | SCOPEdebug))
return false;
/* Given:
* void f() {
* pure void g() {
* /+pure+/ void h() {
* /+pure+/ void i() { }
* }
* }
* }
* g() can call h() but not f()
* i() can call h() and g() but not f()
*/
// Find the closest pure parent of the calling function
FuncDeclaration *outerfunc = sc->func;
FuncDeclaration *calledparent = f;
if (outerfunc->isInstantiated())
{
// The attributes of outerfunc should be inferred from the call of f.
}
else if (f->isInstantiated())
{
// The attributes of f are inferred from its body.
}
else if (f->isFuncLiteralDeclaration())
{
// The attributes of f are always inferred in its declared place.
}
else
{
/* Today, static local functions are impure by default, but they cannot
* violate purity of enclosing functions.
*
* auto foo() pure { // non instantiated funciton
* static auto bar() { // static, without pure attribute
* impureFunc(); // impure call
* // Although impureFunc is called inside bar, f(= impureFunc)
* // is not callable inside pure outerfunc(= foo <- bar).
* }
*
* bar();
* // Although bar is called inside foo, f(= bar) is callable
* // bacause calledparent(= foo) is same with outerfunc(= foo).
* }
*/
while (outerfunc->toParent2() &&
outerfunc->isPureBypassingInference() == PUREimpure &&
outerfunc->toParent2()->isFuncDeclaration())
{
outerfunc = outerfunc->toParent2()->isFuncDeclaration();
if (outerfunc->type->ty == Terror)
return true;
}
while (calledparent->toParent2() &&
calledparent->isPureBypassingInference() == PUREimpure &&
calledparent->toParent2()->isFuncDeclaration())
{
calledparent = calledparent->toParent2()->isFuncDeclaration();
if (calledparent->type->ty == Terror)
return true;
}
}
// If the caller has a pure parent, then either the called func must be pure,
// OR, they must have the same pure parent.
if (!f->isPure() && calledparent != outerfunc)
{
FuncDeclaration *ff = outerfunc;
if (sc->flags & SCOPEcompile ? ff->isPureBypassingInference() >= PUREweak : ff->setImpure())
{
error("pure %s '%s' cannot call impure %s '%s'",
ff->kind(), ff->toPrettyChars(), f->kind(), f->toPrettyChars());
return true;
}
}
return false;
}
/*******************************************
* Accessing variable v.
* Check for purity and safety violations.
* Returns true if error occurs.
*/
bool Expression::checkPurity(Scope *sc, VarDeclaration *v)
{
//printf("v = %s %s\n", v->type->toChars(), v->toChars());
/* Look for purity and safety violations when accessing variable v
* from current function.
*/
if (!sc->func)
return false;
if (sc->intypeof == 1)
return false; // allow violations inside typeof(expression)
if (sc->flags & (SCOPEctfe | SCOPEdebug))
return false; // allow violations inside compile-time evaluated expressions and debug conditionals
if (v->ident == Id::ctfe)
return false; // magic variable never violates pure and safe
if (v->isImmutable())
return false; // always safe and pure to access immutables...
if (v->isConst() && !v->isRef() && (v->isDataseg() || v->isParameter()) &&
v->type->implicitConvTo(v->type->immutableOf()))
return false; // or const global/parameter values which have no mutable indirections
if (v->storage_class & STCmanifest)
return false; // ...or manifest constants
bool err = false;
if (v->isDataseg())
{
// Bugzilla 7533: Accessing implicit generated __gate is pure.
if (v->ident == Id::gate)
return false;
/* Accessing global mutable state.
* Therefore, this function and all its immediately enclosing
* functions must be pure.
*/
/* Today, static local functions are impure by default, but they cannot
* violate purity of enclosing functions.
*
* auto foo() pure { // non instantiated funciton
* static auto bar() { // static, without pure attribute
* globalData++; // impure access
* // Although globalData is accessed inside bar,
* // it is not accessible inside pure foo.
* }
* }
*/
for (Dsymbol *s = sc->func; s; s = s->toParent2())
{
FuncDeclaration *ff = s->isFuncDeclaration();
if (!ff)
break;
if (sc->flags & SCOPEcompile ? ff->isPureBypassingInference() >= PUREweak : ff->setImpure())
{
error("pure %s '%s' cannot access mutable static data '%s'",
ff->kind(), ff->toPrettyChars(), v->toChars());
err = true;
break;
}
/* If the enclosing is an instantiated function or a lambda, its
* attribute inference result is preferred.
*/
if (ff->isInstantiated())
break;
if (ff->isFuncLiteralDeclaration())
break;
}
}
else
{
/* Given:
* void f() {
* int fx;
* pure void g() {
* int gx;
* /+pure+/ void h() {
* int hx;
* /+pure+/ void i() { }
* }
* }
* }
* i() can modify hx and gx but not fx
*/
Dsymbol *vparent = v->toParent2();
for (Dsymbol *s = sc->func; !err && s; s = s->toParent2())
{
if (s == vparent)
break;
if (AggregateDeclaration *ad = s->isAggregateDeclaration())
{
if (ad->isNested())
continue;
break;
}
FuncDeclaration *ff = s->isFuncDeclaration();
if (!ff)
break;
if (ff->isNested() || ff->isThis())
{
if (ff->type->isImmutable() ||
(ff->type->isShared() && !MODimplicitConv(ff->type->mod, v->type->mod)))
{
OutBuffer ffbuf;
OutBuffer vbuf;
MODMatchToBuffer(&ffbuf, ff->type->mod, v->type->mod);
MODMatchToBuffer(&vbuf, v->type->mod, ff->type->mod);
error("%s%s '%s' cannot access %sdata '%s'",
ffbuf.peekString(), ff->kind(), ff->toPrettyChars(), vbuf.peekString(), v->toChars());
err = true;
break;
}
continue;
}
break;
}
}
/* Do not allow safe functions to access __gshared data
*/
if (v->storage_class & STCgshared)
{
if (sc->func->setUnsafe())
{
error("safe %s '%s' cannot access __gshared data '%s'",
sc->func->kind(), sc->func->toChars(), v->toChars());
err = true;
}
}
return err;
}
/*********************************************
* Calling function f.
* Check the safety, i.e. if we're in a @safe function
* we can only call @safe or @trusted functions.
* Returns true if error occurs.
*/
bool Expression::checkSafety(Scope *sc, FuncDeclaration *f)
{
if (!sc->func)
return false;
if (sc->func == f)
return false;
if (sc->intypeof == 1)
return false;
if (sc->flags & SCOPEctfe)
return false;
if (!f->isSafe() && !f->isTrusted())
{
if (sc->flags & SCOPEcompile ? sc->func->isSafeBypassingInference() : sc->func->setUnsafe())
{
if (loc.linnum == 0) // e.g. implicitly generated dtor
loc = sc->func->loc;
error("@safe %s '%s' cannot call @system %s '%s'",
sc->func->kind(), sc->func->toPrettyChars(), f->kind(), f->toPrettyChars());
return true;
}
}
return false;
}
/*********************************************
* Calling function f.
* Check the @nogc-ness, i.e. if we're in a @nogc function
* we can only call other @nogc functions.
* Returns true if error occurs.
*/
bool Expression::checkNogc(Scope *sc, FuncDeclaration *f)
{
if (!sc->func)
return false;
if (sc->func == f)
return false;
if (sc->intypeof == 1)
return false;
if (sc->flags & SCOPEctfe)
return false;
if (!f->isNogc())
{
if (sc->flags & SCOPEcompile ? sc->func->isNogcBypassingInference() : sc->func->setGC())
{
if (loc.linnum == 0) // e.g. implicitly generated dtor
loc = sc->func->loc;
error("@nogc %s '%s' cannot call non-@nogc %s '%s'",
sc->func->kind(), sc->func->toPrettyChars(), f->kind(), f->toPrettyChars());
return true;
}
}
return false;
}
/********************************************
* Check that the postblit is callable if t is an array of structs.
* Returns true if error happens.
*/
bool Expression::checkPostblit(Scope *sc, Type *t)
{
t = t->baseElemOf();
if (t->ty == Tstruct)
{
if (global.params.useTypeInfo)
{
// Bugzilla 11395: Require TypeInfo generation for array concatenation
semanticTypeInfo(sc, t);
}
StructDeclaration *sd = ((TypeStruct *)t)->sym;
if (sd->postblit)
{
if (sd->postblit->storage_class & STCdisable)
{
sd->error(loc, "is not copyable because it is annotated with @disable");
return true;
}
//checkDeprecated(sc, sd->postblit); // necessary?
checkPurity(sc, sd->postblit);
checkSafety(sc, sd->postblit);
checkNogc(sc, sd->postblit);
//checkAccess(sd, loc, sc, sd->postblit); // necessary?
return false;
}
}
return false;
}
bool Expression::checkRightThis(Scope *sc)
{
if (op == TOKerror)
return true;
if (op == TOKvar && type->ty != Terror)
{
VarExp *ve = (VarExp *)this;
if (isNeedThisScope(sc, ve->var))
{
//printf("checkRightThis sc->intypeof = %d, ad = %p, func = %p, fdthis = %p\n",
// sc->intypeof, sc->getStructClassScope(), func, fdthis);
error("need 'this' for '%s' of type '%s'", ve->var->toChars(), ve->var->type->toChars());
return true;
}
}
return false;
}
/*******************************
* Check whether the expression allows RMW operations, error with rmw operator diagnostic if not.
* ex is the RHS expression, or NULL if ++/-- is used (for diagnostics)
* Returns true if error occurs.
*/
bool Expression::checkReadModifyWrite(TOK rmwOp, Expression *ex)
{
//printf("Expression::checkReadModifyWrite() %s %s", toChars(), ex ? ex->toChars() : "");
if (!type || !type->isShared())
return false;
// atomicOp uses opAssign (+=/-=) rather than opOp (++/--) for the CT string literal.
switch (rmwOp)
{
case TOKplusplus:
case TOKpreplusplus:
rmwOp = TOKaddass;
break;
case TOKminusminus:
case TOKpreminusminus:
rmwOp = TOKminass;
break;
default:
break;
}
deprecation("read-modify-write operations are not allowed for shared variables. "
"Use core.atomic.atomicOp!\"%s\"(%s, %s) instead.",
Token::tochars[rmwOp], toChars(), ex ? ex->toChars() : "1");
return false;
// note: enable when deprecation becomes an error.
// return true;
}
/*****************************
* If expression can be tested for true or false,
* returns the modified expression.
* Otherwise returns ErrorExp.
*/
Expression *Expression::toBoolean(Scope *sc)
{
// Default is 'yes' - do nothing
Expression *e = this;
Type *t = type;
Type *tb = type->toBasetype();
Type *att = NULL;
Lagain:
// Structs can be converted to bool using opCast(bool)()
if (tb->ty == Tstruct)
{
AggregateDeclaration *ad = ((TypeStruct *)tb)->sym;
/* Don't really need to check for opCast first, but by doing so we
* get better error messages if it isn't there.
*/
Dsymbol *fd = search_function(ad, Id::_cast);
if (fd)
{
e = new CastExp(loc, e, Type::tbool);
e = semantic(e, sc);
return e;
}
// Forward to aliasthis.
if (ad->aliasthis && tb != att)
{
if (!att && tb->checkAliasThisRec())
att = tb;
e = resolveAliasThis(sc, e);
t = e->type;
tb = e->type->toBasetype();
goto Lagain;
}
}
if (!t->isBoolean())
{
if (tb != Type::terror)
error("expression %s of type %s does not have a boolean value", toChars(), t->toChars());
return new ErrorExp();
}
return e;
}
/******************************
* Take address of expression.
*/
Expression *Expression::addressOf()
{
//printf("Expression::addressOf()\n");
Expression *e = new AddrExp(loc, this);
e->type = type->pointerTo();
return e;
}
/******************************
* If this is a reference, dereference it.
*/
Expression *Expression::deref()
{
//printf("Expression::deref()\n");
// type could be null if forward referencing an 'auto' variable
if (type && type->ty == Treference)
{
Expression *e = new PtrExp(loc, this);
e->type = ((TypeReference *)type)->next;
return e;
}
return this;
}
/********************************
* Does this expression statically evaluate to a boolean 'result' (true or false)?
*/
bool Expression::isBool(bool)
{
return false;
}
/****************************************
* Resolve __FILE__, __LINE__, __MODULE__, __FUNCTION__, __PRETTY_FUNCTION__ to loc.
*/
Expression *Expression::resolveLoc(Loc, Scope *)
{
return this;
}
Expressions *Expression::arraySyntaxCopy(Expressions *exps)
{
Expressions *a = NULL;
if (exps)
{
a = new Expressions();
a->setDim(exps->dim);
for (size_t i = 0; i < a->dim; i++)
{
Expression *e = (*exps)[i];
(*a)[i] = e ? e->syntaxCopy() : NULL;
}
}
return a;
}
/************************************************
* Destructors are attached to VarDeclarations.
* Hence, if expression returns a temp that needs a destructor,
* make sure and create a VarDeclaration for that temp.
*/
Expression *Expression::addDtorHook(Scope *)
{
return this;
}
/******************************** IntegerExp **************************/
IntegerExp::IntegerExp(Loc loc, dinteger_t value, Type *type)
: Expression(loc, TOKint64, sizeof(IntegerExp))
{
//printf("IntegerExp(value = %lld, type = '%s')\n", value, type ? type->toChars() : "");
assert(type);
if (!type->isscalar())
{
//printf("%s, loc = %d\n", toChars(), loc.linnum);
if (type->ty != Terror)
error("integral constant must be scalar type, not %s", type->toChars());
type = Type::terror;
}
this->type = type;
setInteger(value);
}
IntegerExp::IntegerExp(dinteger_t value)
: Expression(Loc(), TOKint64, sizeof(IntegerExp))
{
this->type = Type::tint32;
this->value = (d_int32) value;
}
IntegerExp *IntegerExp::create(Loc loc, dinteger_t value, Type *type)
{
return new IntegerExp(loc, value, type);
}
bool IntegerExp::equals(RootObject *o)
{
if (this == o)
return true;
if (((Expression *)o)->op == TOKint64)
{
IntegerExp *ne = (IntegerExp *)o;
if (type->toHeadMutable()->equals(ne->type->toHeadMutable()) &&
value == ne->value)
{
return true;
}
}
return false;
}
void IntegerExp::setInteger(dinteger_t value)
{
this->value = value;
normalize();
}
void IntegerExp::normalize()
{
/* 'Normalize' the value of the integer to be in range of the type
*/
switch (type->toBasetype()->ty)
{
case Tbool: value = (value != 0); break;
case Tint8: value = (d_int8) value; break;
case Tchar:
case Tuns8: value = (d_uns8) value; break;
case Tint16: value = (d_int16) value; break;
case Twchar:
case Tuns16: value = (d_uns16) value; break;
case Tint32: value = (d_int32) value; break;
case Tdchar:
case Tuns32: value = (d_uns32) value; break;