Debian Codegraph @

gcc/d/dmd/arrayop.d

raw
1 /**
2 * Implement array operations, such as `a[] = b[] + c[]`.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/arrays.html#array-operations, Array Operations)
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/arrayop.d, _arrayop.d)
10 * Documentation: https://dlang.org/phobos/dmd_arrayop.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/arrayop.d
12 */
13
14 module dmd.arrayop;
15
16 import core.stdc.stdio;
17 import dmd.arraytypes;
18 import dmd.astenums;
19 import dmd.dcast : implicitConvTo;
20 import dmd.declaration;
21 import dmd.dscope;
22 import dmd.dsymbol;
23 import dmd.errors;
24 import dmd.expression;
25 import dmd.expressionsem;
26 import dmd.funcsem;
27 import dmd.hdrgen;
28 import dmd.id;
29 import dmd.identifier;
30 import dmd.location;
31 import dmd.mtype;
32 import dmd.common.outbuffer;
33 import dmd.tokens;
34 import dmd.visitor;
35
36 /**********************************************
37 * Check that there are no uses of arrays without [].
38 */
39 bool isArrayOpValid(Expression e)
40 {
41 //printf("isArrayOpValid() %s\n", e.toChars());
42 if (e.op == EXP.slice)
43 return true;
44 if (e.op == EXP.arrayLiteral)
45 {
46 Type t = e.type.toBasetype();
47 while (t.isStaticOrDynamicArray())
48 t = t.nextOf().toBasetype();
49 return (t.ty != Tvoid);
50 }
51 Type tb = e.type.toBasetype();
52 if (tb.isStaticOrDynamicArray())
53 {
54 if (isUnaArrayOp(e.op))
55 {
56 return isArrayOpValid(e.isUnaExp().e1);
57 }
58 if (isBinArrayOp(e.op) || isBinAssignArrayOp(e.op) || e.op == EXP.assign)
59 {
60 BinExp be = e.isBinExp();
61 return isArrayOpValid(be.e1) && isArrayOpValid(be.e2);
62 }
63 if (e.op == EXP.construct)
64 {
65 BinExp be = e.isBinExp();
66 return be.e1.op == EXP.slice && isArrayOpValid(be.e2);
67 }
68 // if (e.op == EXP.call)
69 // {
70 // TODO: Decide if [] is required after arrayop calls.
71 // }
72 return false;
73 }
74 return true;
75 }
76
77 bool isNonAssignmentArrayOp(Expression e)
78 {
79 if (e.op == EXP.slice)
80 return isNonAssignmentArrayOp(e.isSliceExp().e1);
81
82 Type tb = e.type.toBasetype();
83 if (tb.isStaticOrDynamicArray())
84 {
85 return (isUnaArrayOp(e.op) || isBinArrayOp(e.op));
86 }
87 return false;
88 }
89
90 bool checkNonAssignmentArrayOp(Expression e, bool suggestion = false)
91 {
92 if (isNonAssignmentArrayOp(e))
93 {
94 const(char)* s = "";
95 if (suggestion)
96 s = " (possible missing [])";
97 error(e.loc, "array operation `%s` without destination memory not allowed%s", e.toChars(), s);
98 return true;
99 }
100 return false;
101 }
102
103 /***********************************
104 * Construct the array operation expression, call object._arrayOp!(tiargs)(args).
105 *
106 * Encode operand types and operations into tiargs using reverse polish notation (RPN) to preserve precedence.
107 * Unary operations are prefixed with "u" (e.g. "u~").
108 * Pass operand values (slices or scalars) as args.
109 *
110 * Scalar expression sub-trees of `e` are evaluated before calling
111 * into druntime to hoist them out of the loop. This is a valid
112 * evaluation order as the actual array operations have no
113 * side-effect.
114 * References:
115 * https://github.com/dlang/dmd/blob/cdfadf8a18f474e6a1b8352af2541efe3e3467cc/druntime/src/object.d#L4694
116 * https://github.com/dlang/dmd/blob/master/druntime/src/core/internal/array/operations.d
117 */
118 Expression arrayOp(BinExp e, Scope* sc)
119 {
120 //printf("BinExp.arrayOp() %s\n", e.toChars());
121 Type tb = e.type.toBasetype();
122 assert(tb.isStaticOrDynamicArray());
123 Type tbn = tb.nextOf().toBasetype();
124 if (tbn.ty == Tvoid)
125 {
126 error(e.loc, "cannot perform array operations on `void[]` arrays");
127 return ErrorExp.get();
128 }
129 if (!isArrayOpValid(e))
130 return arrayOpInvalidError(e);
131
132 auto tiargs = new Objects();
133 auto args = buildArrayOp(sc, e, tiargs);
134
135 import dmd.dtemplate : TemplateDeclaration;
136 __gshared TemplateDeclaration arrayOp;
137 if (arrayOp is null)
138 {
139 // Create .object._arrayOp
140 Identifier idArrayOp = Identifier.idPool("_arrayOp");
141 Expression id = new IdentifierExp(e.loc, Id.empty);
142 id = new DotIdExp(e.loc, id, Id.object);
143 id = new DotIdExp(e.loc, id, idArrayOp);
144
145 id = id.expressionSemantic(sc);
146 if (auto te = id.isTemplateExp())
147 arrayOp = te.td;
148 else
149 {
150 ObjectNotFound(e.loc, idArrayOp); // fatal error
151 return ErrorExp.get();
152 }
153 }
154
155 auto fd = resolveFuncCall(e.loc, sc, arrayOp, tiargs, null, ArgumentList(args), FuncResolveFlag.standard);
156 if (!fd || fd.errors)
157 return ErrorExp.get();
158 return new CallExp(e.loc, new VarExp(e.loc, fd, false), args).expressionSemantic(sc);
159 }
160
161 /// ditto
162 Expression arrayOp(BinAssignExp e, Scope* sc)
163 {
164 //printf("BinAssignExp.arrayOp() %s\n", e.toChars());
165
166 /* Check that the elements of e1 can be assigned to
167 */
168 Type tn = e.e1.type.toBasetype().nextOf();
169
170 if (tn && (!tn.isMutable() || !tn.isAssignable()))
171 {
172 error(e.loc, "slice `%s` is not mutable", e.e1.toChars());
173 if (e.op == EXP.addAssign)
174 checkPossibleAddCatError!(AddAssignExp, CatAssignExp)(e.isAddAssignExp);
175 return ErrorExp.get();
176 }
177 if (e.e1.op == EXP.arrayLiteral)
178 {
179 return e.e1.modifiableLvalue(sc);
180 }
181
182 return arrayOp(e.isBinExp(), sc);
183 }
184
185 /******************************************
186 * Convert the expression tree e to template and function arguments,
187 * using reverse polish notation (RPN) to encode order of operations.
188 * Encode operations as string arguments, using a "u" prefix for unary operations.
189 */
190 private Expressions* buildArrayOp(Scope* sc, Expression e, Objects* tiargs)
191 {
192 extern (C++) final class BuildArrayOpVisitor : Visitor
193 {
194 alias visit = Visitor.visit;
195 Scope* sc;
196 Objects* tiargs;
197 Expressions* args;
198
199 public:
200 extern (D) this(Scope* sc, Objects* tiargs) scope @safe
201 {
202 this.sc = sc;
203 this.tiargs = tiargs;
204 this.args = new Expressions();
205 }
206
207 override void visit(Expression e)
208 {
209 tiargs.push(e.type);
210 args.push(e);
211 }
212
213 override void visit(SliceExp e)
214 {
215 visit(cast(Expression) e);
216 }
217
218 override void visit(CastExp e)
219 {
220 visit(cast(Expression) e);
221 }
222
223 override void visit(UnaExp e)
224 {
225 Type tb = e.type.toBasetype();
226 if (tb.ty != Tarray && tb.ty != Tsarray) // hoist scalar expressions
227 {
228 visit(cast(Expression) e);
229 }
230 else
231 {
232 // RPN, prefix unary ops with u
233 OutBuffer buf;
234 buf.writestring("u");
235 buf.writestring(EXPtoString(e.op));
236 e.e1.accept(this);
237 tiargs.push(new StringExp(Loc.initial, buf.extractSlice()).expressionSemantic(sc));
238 }
239 }
240
241 override void visit(BinExp e)
242 {
243 Type tb = e.type.toBasetype();
244 if (tb.ty != Tarray && tb.ty != Tsarray) // hoist scalar expressions
245 {
246 visit(cast(Expression) e);
247 }
248 else
249 {
250 // RPN
251 e.e1.accept(this);
252 e.e2.accept(this);
253 tiargs.push(new StringExp(Loc.initial, EXPtoString(e.op)).expressionSemantic(sc));
254 }
255 }
256 }
257
258 scope v = new BuildArrayOpVisitor(sc, tiargs);
259 e.accept(v);
260 return v.args;
261 }
262
263 /***********************************************
264 * Some implicit casting can be performed by the _arrayOp template.
265 * Params:
266 * tfrom = type converting from
267 * tto = type converting to
268 * Returns:
269 * true if can be performed by _arrayOp
270 */
271 bool isArrayOpImplicitCast(TypeDArray tfrom, TypeDArray tto)
272 {
273 const tyf = tfrom.nextOf().toBasetype().ty;
274 const tyt = tto .nextOf().toBasetype().ty;
275 return tyf == tyt ||
276 tyf == Tint32 && tyt == Tfloat64;
277 }
278
279 /***********************************************
280 * Test if expression is a unary array op.
281 */
282 bool isUnaArrayOp(EXP op) @safe
283 {
284 switch (op)
285 {
286 case EXP.negate:
287 case EXP.tilde:
288 return true;
289 default:
290 return false;
291 }
292 }
293
294 /***********************************************
295 * Test if expression is a binary array op.
296 */
297 bool isBinArrayOp(EXP op) @safe
298 {
299 switch (op)
300 {
301 case EXP.add:
302 case EXP.min:
303 case EXP.mul:
304 case EXP.div:
305 case EXP.mod:
306 case EXP.xor:
307 case EXP.and:
308 case EXP.or:
309 case EXP.pow:
310 return true;
311 default:
312 return false;
313 }
314 }
315
316 /***********************************************
317 * Test if expression is a binary assignment array op.
318 */
319 bool isBinAssignArrayOp(EXP op) @safe
320 {
321 switch (op)
322 {
323 case EXP.addAssign:
324 case EXP.minAssign:
325 case EXP.mulAssign:
326 case EXP.divAssign:
327 case EXP.modAssign:
328 case EXP.xorAssign:
329 case EXP.andAssign:
330 case EXP.orAssign:
331 case EXP.powAssign:
332 return true;
333 default:
334 return false;
335 }
336 }
337
338 /***********************************************
339 * Test if operand is a valid array op operand.
340 */
341 bool isArrayOpOperand(Expression e)
342 {
343 //printf("Expression.isArrayOpOperand() %s\n", e.toChars());
344 if (e.op == EXP.slice)
345 return true;
346 if (e.op == EXP.arrayLiteral)
347 {
348 Type t = e.type.toBasetype();
349 while (t.isStaticOrDynamicArray())
350 t = t.nextOf().toBasetype();
351 return (t.ty != Tvoid);
352 }
353 Type tb = e.type.toBasetype();
354 if (tb.ty == Tarray)
355 {
356 return (isUnaArrayOp(e.op) ||
357 isBinArrayOp(e.op) ||
358 isBinAssignArrayOp(e.op) ||
359 e.op == EXP.assign);
360 }
361 return false;
362 }
363
364
365 /***************************************************
366 * Print error message about invalid array operation.
367 * Params:
368 * e = expression with the invalid array operation
369 * Returns:
370 * instance of ErrorExp
371 */
372
373 ErrorExp arrayOpInvalidError(Expression e)
374 {
375 error(e.loc, "invalid array operation `%s` (possible missing [])", e.toChars());
376 if (e.op == EXP.add)
377 checkPossibleAddCatError!(AddExp, CatExp)(e.isAddExp());
378 else if (e.op == EXP.addAssign)
379 checkPossibleAddCatError!(AddAssignExp, CatAssignExp)(e.isAddAssignExp());
380 return ErrorExp.get();
381 }
382
383 private void checkPossibleAddCatError(AddT, CatT)(AddT ae)
384 {
385 if (!ae.e2.type || ae.e2.type.ty != Tarray || !ae.e2.type.implicitConvTo(ae.e1.type))
386 return;
387 CatT ce = new CatT(ae.loc, ae.e1, ae.e2);
388 errorSupplemental(ae.loc, "did you mean to concatenate (`%s`) instead ?", ce.toChars());
389 }