aboutsummaryrefslogtreecommitdiff
path: root/gcc/d/dmd/lambdacomp.d
blob: 91df9cc9f255fce0446df041a8df058b373c1ef4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/**
 * Implements the serialization of a lambda function.
 *
 * The serializationis computed by visiting the abstract syntax subtree of the given lambda function.
 * The serialization is a string which contains the type of the parameters and the string
 * represantation of the lambda expression.
 *
 * Copyright:   Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved
 * Authors:     $(LINK2 https://www.digitalmars.com, Walter Bright)
 * License:     $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
 * Source:      $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/lamdbacomp.d, _lambdacomp.d)
 * Documentation:  https://dlang.org/phobos/dmd_lambdacomp.html
 * Coverage:    https://codecov.io/gh/dlang/dmd/src/master/src/dmd/lambdacomp.d
 */

module dmd.lambdacomp;

import core.stdc.stdio;
import core.stdc.string;

import dmd.astenums;
import dmd.declaration;
import dmd.denum;
import dmd.dsymbol;
import dmd.dtemplate;
import dmd.expression;
import dmd.func;
import dmd.dmangle;
import dmd.hdrgen;
import dmd.mtype;
import dmd.common.outbuffer;
import dmd.root.rmem;
import dmd.root.stringtable;
import dmd.dscope;
import dmd.statement;
import dmd.tokens;
import dmd.visitor;

enum LOG = false;

/**
 * The type of the visited expression.
 */
private enum ExpType
{
    None,
    EnumDecl,
    Arg
}

/**
 * Compares 2 lambda functions described by their serialization.
 *
 * Params:
 *  l1 = first lambda to be compared
 *  l2 = second lambda to be compared
 *  sc = the scope where the lambdas are compared
 *
 * Returns:
 *  `true` if the 2 lambda functions are equal, `false` otherwise
 */
bool isSameFuncLiteral(FuncLiteralDeclaration l1, FuncLiteralDeclaration l2, Scope* sc)
{
    bool result;
    if (auto ser1 = getSerialization(l1, sc))
    {
        //printf("l1 serialization: %.*s\n", cast(int)ser1.length, &ser1[0]);
        if (auto ser2 = getSerialization(l2, sc))
        {
            //printf("l2 serialization: %.*s\n", cast(int)ser2.length, &ser2[0]);
            if (ser1 == ser2)
                result = true;
            mem.xfree(cast(void*)ser2.ptr);
        }
        mem.xfree(cast(void*)ser1.ptr);
    }
    return result;
}

/**
 * Computes the string representation of a
 * lambda function described by the subtree starting from a
 * $(REF dmd, func, FuncLiteralDeclaration).
 *
 * Limitations: only IntegerExps, Enums and function
 * arguments are supported in the lambda function body. The
 * arguments may be of any type (basic types, user defined types),
 * except template instantiations. If a function call, a local
 * variable or a template instance is encountered, the
 * serialization is dropped and the function is considered
 * uncomparable.
 *
 * Params:
 *  fld = the starting AST node for the lambda function
 *  sc = the scope in which the lambda function is located
 *
 * Returns:
 *  The serialization of `fld` allocated with mem.
 */
private string getSerialization(FuncLiteralDeclaration fld, Scope* sc)
{
    scope serVisitor = new SerializeVisitor(fld.parent._scope);
    fld.accept(serVisitor);
    const len = serVisitor.buf.length;
    if (len == 0)
        return null;

    return cast(string)serVisitor.buf.extractSlice();
}

private extern (C++) class SerializeVisitor : SemanticTimeTransitiveVisitor
{
private:
    StringTable!(const(char)[]) arg_hash;
    Scope* sc;
    ExpType et;
    Dsymbol d;

public:
    OutBuffer buf;
    alias visit = SemanticTimeTransitiveVisitor.visit;

    this(Scope* sc)
    {
        this.sc = sc;
    }

    /**
     * Entrypoint of the SerializeVisitor.
     *
     * Params:
     *     fld = the lambda function for which the serialization is computed
     */
    override void visit(FuncLiteralDeclaration fld)
    {
        assert(fld.type.ty != Terror);
        static if (LOG)
            printf("FuncLiteralDeclaration: %s\n", fld.toChars());

        TypeFunction tf = cast(TypeFunction) fld.type;
        const dim = cast(uint) tf.parameterList.length;
        // Start the serialization by printing the number of
        // arguments the lambda has.
        buf.printf("%d:", dim);

        arg_hash._init(dim + 1);
        // For each argument
        foreach (i, fparam; tf.parameterList)
        {
            if (fparam.ident !is null)
            {
                // the variable name is introduced into a hashtable
                // where the key is the user defined name and the
                // value is the cannonically name (arg0, arg1 ...)
                auto key = fparam.ident.toString();
                OutBuffer value;
                value.writestring("arg");
                value.print(i);
                arg_hash.insert(key, value.extractSlice());
                // and the type of the variable is serialized.
                fparam.accept(this);
            }
        }

        // Now the function body can be serialized.
        ReturnStatement rs = fld.fbody.endsWithReturnStatement();
        if (rs && rs.exp)
        {
            rs.exp.accept(this);
        }
        else
        {
            buf.setsize(0);
        }
    }

    override void visit(DotIdExp exp)
    {
        static if (LOG)
            printf("DotIdExp: %s\n", exp.toChars());
        if (buf.length == 0)
            return;

        // First we need to see what kind of expression e1 is.
        // It might an enum member (enum.value)  or the field of
        // an argument (argX.value) if the argument is an aggregate
        // type. This is reported through the et variable.
        exp.e1.accept(this);
        if (buf.length == 0)
            return;

        if (et == ExpType.EnumDecl)
        {
            Dsymbol s = d.search(exp.loc, exp.ident);
            if (s)
            {
                if (auto em = s.isEnumMember())
                {
                    em.value.accept(this);
                }
                et = ExpType.None;
                d = null;
            }
        }

        else if (et == ExpType.Arg)
        {
            buf.setsize(buf.length -1);
            buf.writeByte('.');
            buf.writestring(exp.ident.toString());
            buf.writeByte('_');
        }
    }

    bool checkArgument(const(char)* id)
    {
        // The identifier may be an argument
        auto stringtable_value = arg_hash.lookup(id, strlen(id));
        if (stringtable_value)
        {
            // In which case we need to update the serialization accordingly
            const(char)[] gen_id = stringtable_value.value;
            buf.write(gen_id);
            buf.writeByte('_');
            et = ExpType.Arg;
            return true;
        }
        return false;
    }

    override void visit(IdentifierExp exp)
    {
        static if (LOG)
            printf("IdentifierExp: %s\n", exp.toChars());

        if (buf.length == 0)
            return;

        auto id = exp.ident.toChars();

        // If it's not an argument
        if (!checkArgument(id))
        {
            // we must check what the identifier expression is.
            Dsymbol scopesym;
            Dsymbol s = sc.search(exp.loc, exp.ident, &scopesym);
            if (s)
            {
                auto v = s.isVarDeclaration();
                // If it's a VarDeclaration, it must be a manifest constant
                if (v && (v.storage_class & STC.manifest))
                {
                    v.getConstInitializer.accept(this);
                }
                else if (auto em = s.isEnumDeclaration())
                {
                    d = em;
                    et = ExpType.EnumDecl;
                }
                else if (auto fd = s.isFuncDeclaration())
                {
                    writeMangledName(fd);
                }
                // For anything else, the function is deemed uncomparable
                else
                {
                    buf.setsize(0);
                }
            }
            // If it's an unknown symbol, consider the function incomparable
            else
            {
                buf.setsize(0);
            }
        }
    }

    override void visit(DotVarExp exp)
    {
        static if (LOG)
            printf("DotVarExp: %s, var: %s, e1: %s\n", exp.toChars(),
                    exp.var.toChars(), exp.e1.toChars());

        exp.e1.accept(this);
        if (buf.length == 0)
            return;

        buf.setsize(buf.length -1);
        buf.writeByte('.');
        buf.writestring(exp.var.toChars());
        buf.writeByte('_');
    }

    override void visit(VarExp exp)
    {
        static if (LOG)
            printf("VarExp: %s, var: %s\n", exp.toChars(), exp.var.toChars());

        if (buf.length == 0)
            return;

        auto id = exp.var.ident.toChars();
        if (!checkArgument(id))
        {
            buf.setsize(0);
        }
    }

    // serialize function calls
    override void visit(CallExp exp)
    {
        static if (LOG)
            printf("CallExp: %s\n", exp.toChars());

        if (buf.length == 0)
            return;

        if (!exp.f)
        {
            exp.e1.accept(this);
        }
        else
        {
            writeMangledName(exp.f);
        }

        buf.writeByte('(');
        foreach (arg; *(exp.arguments))
        {
            arg.accept(this);
        }
        buf.writeByte(')');
    }

    override void visit(UnaExp exp)
    {
        if (buf.length == 0)
            return;

        buf.writeByte('(');
        buf.writestring(EXPtoString(exp.op));
        exp.e1.accept(this);
        if (buf.length != 0)
            buf.writestring(")_");
    }

    override void visit(IntegerExp exp)
    {
        if (buf.length == 0)
            return;

        buf.print(exp.toInteger());
        buf.writeByte('_');
    }

    override void visit(RealExp exp)
    {
        if (buf.length == 0)
            return;

        buf.writestring(exp.toChars());
        buf.writeByte('_');
    }

    override void visit(BinExp exp)
    {
        static if (LOG)
            printf("BinExp: %s\n", exp.toChars());

        if (buf.length == 0)
            return;

        buf.writeByte('(');
        buf.writestring(EXPtoString(exp.op).ptr);

        exp.e1.accept(this);
        if (buf.length == 0)
            return;

        exp.e2.accept(this);
        if (buf.length == 0)
            return;

        buf.writeByte(')');
    }

    override void visit(TypeBasic t)
    {
        buf.writestring(t.dstring);
        buf.writeByte('_');
    }

    void writeMangledName(Dsymbol s)
    {
        if (s)
        {
            OutBuffer mangledName;
            mangleToBuffer(s, &mangledName);
            buf.writestring(mangledName[]);
            buf.writeByte('_');
        }
        else
            buf.setsize(0);
    }

    private bool checkTemplateInstance(T)(T t)
        if (is(T == TypeStruct) || is(T == TypeClass))
    {
        if (t.sym.parent && t.sym.parent.isTemplateInstance())
        {
            buf.setsize(0);
            return true;
        }
        return false;
    }

    override void visit(TypeStruct t)
    {
        static if (LOG)
            printf("TypeStruct: %s\n", t.toChars);

        if (!checkTemplateInstance!TypeStruct(t))
            writeMangledName(t.sym);
    }

    override void visit(TypeClass t)
    {
        static if (LOG)
            printf("TypeClass: %s\n", t.toChars());

        if (!checkTemplateInstance!TypeClass(t))
            writeMangledName(t.sym);
    }

    override void visit(Parameter p)
    {
        if (p.type.ty == Tident
            && (cast(TypeIdentifier)p.type).ident.toString().length > 3
            && strncmp((cast(TypeIdentifier)p.type).ident.toChars(), "__T", 3) == 0)
        {
            buf.writestring("none_");
        }
        else
            visitType(p.type);
    }

    override void visit(StructLiteralExp e) {
        static if (LOG)
            printf("StructLiteralExp: %s\n", e.toChars);

        auto ty = cast(TypeStruct)e.stype;
        if (ty)
        {
            writeMangledName(ty.sym);
            auto dim = e.elements.dim;
            foreach (i; 0..dim)
            {
                auto elem = (*e.elements)[i];
                if (elem)
                    elem.accept(this);
                else
                    buf.writestring("null_");
            }
        }
        else
            buf.setsize(0);
    }

    override void visit(ArrayLiteralExp) { buf.setsize(0); }
    override void visit(AssocArrayLiteralExp) { buf.setsize(0); }
    override void visit(MixinExp) { buf.setsize(0); }
    override void visit(ComplexExp) { buf.setsize(0); }
    override void visit(DeclarationExp) { buf.setsize(0); }
    override void visit(DefaultInitExp) { buf.setsize(0); }
    override void visit(DsymbolExp) { buf.setsize(0); }
    override void visit(ErrorExp) { buf.setsize(0); }
    override void visit(FuncExp) { buf.setsize(0); }
    override void visit(HaltExp) { buf.setsize(0); }
    override void visit(IntervalExp) { buf.setsize(0); }
    override void visit(IsExp) { buf.setsize(0); }
    override void visit(NewAnonClassExp) { buf.setsize(0); }
    override void visit(NewExp) { buf.setsize(0); }
    override void visit(NullExp) { buf.setsize(0); }
    override void visit(ObjcClassReferenceExp) { buf.setsize(0); }
    override void visit(OverExp) { buf.setsize(0); }
    override void visit(ScopeExp) { buf.setsize(0); }
    override void visit(StringExp) { buf.setsize(0); }
    override void visit(SymbolExp) { buf.setsize(0); }
    override void visit(TemplateExp) { buf.setsize(0); }
    override void visit(ThisExp) { buf.setsize(0); }
    override void visit(TraitsExp) { buf.setsize(0); }
    override void visit(TupleExp) { buf.setsize(0); }
    override void visit(TypeExp) { buf.setsize(0); }
    override void visit(TypeidExp) { buf.setsize(0); }
    override void visit(VoidInitExp) { buf.setsize(0); }
}