@@ -99,6 +99,8 @@ static void diagSelfAssignment(TypeChecker &TC, const Expr *E) {
9999// / - 'self.init' and 'super.init' cannot be wrapped in a larger expression
100100// / or statement.
101101// / - Warn about promotions to optional in specific syntactic forms.
102+ // / - Error about collection literals that default to Any collections in
103+ // / invalid positions.
102104// /
103105static void diagSyntacticUseRestrictions (TypeChecker &TC, const Expr *E,
104106 const DeclContext *DC,
@@ -238,10 +240,13 @@ static void diagSyntacticUseRestrictions(TypeChecker &TC, const Expr *E,
238240 while (auto Conv = dyn_cast<ImplicitConversionExpr>(Base))
239241 Base = Conv->getSubExpr ();
240242
243+ if (auto collection = dyn_cast<CollectionExpr>(E))
244+ if (collection->isTypeDefaulted ())
245+ checkTypeDefaultedCollectionExpr (collection);
246+
241247 // Record call arguments.
242- if (auto Call = dyn_cast<CallExpr>(Base)) {
248+ if (auto Call = dyn_cast<CallExpr>(Base))
243249 CallArgs.insert (Call->getArg ());
244- }
245250
246251 if (auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
247252 // Verify metatype uses.
@@ -381,6 +386,29 @@ static void diagSyntacticUseRestrictions(TypeChecker &TC, const Expr *E,
381386 return E;
382387 }
383388
389+ // / We have a collection literal with a defaulted type, e.g. of [Any]. Emit
390+ // / an error if it was inferred to this type in an invalid context, which is
391+ // / one in which the parent expression is not itself a collection literal.
392+ void checkTypeDefaultedCollectionExpr (CollectionExpr *c) {
393+ if (auto *ParentExpr = Parent.getAsExpr ())
394+ if (isa<CollectionExpr>(ParentExpr))
395+ return ;
396+
397+ // If the parent is a non-expression, or is not itself a literal, then
398+ // produce an error with a fixit to add the type as an explicit
399+ // annotation.
400+ if (c->getNumElements () == 0 )
401+ TC.diagnose (c->getLoc (), diag::collection_literal_empty)
402+ .highlight (c->getSourceRange ());
403+ else {
404+ TC.diagnose (c->getLoc (), diag::collection_literal_heterogenous,
405+ c->getType ())
406+ .highlight (c->getSourceRange ())
407+ .fixItInsertAfter (c->getEndLoc (), " as " + c->getType ()->getString ());
408+ }
409+ }
410+
411+
384412 // / Scout out the specified destination of an AssignExpr to recursively
385413 // / identify DiscardAssignmentExpr in legal places. We can only allow them
386414 // / in simple pattern-like expressions, so we reject anything complex here.
0 commit comments