declaration-visitor.cc 15 KB
Newer Older
1 2 3 4 5
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/torque/declaration-visitor.h"
6

7
#include "src/torque/ast.h"
8
#include "src/torque/server-data.h"
9
#include "src/torque/type-inference.h"
10
#include "src/torque/type-visitor.h"
11 12 13 14 15

namespace v8 {
namespace internal {
namespace torque {

16 17 18 19 20 21 22 23 24 25
Namespace* GetOrCreateNamespace(const std::string& name) {
  std::vector<Namespace*> existing_namespaces = FilterDeclarables<Namespace>(
      Declarations::TryLookupShallow(QualifiedName(name)));
  if (existing_namespaces.empty()) {
    return Declarations::DeclareNamespace(name);
  }
  DCHECK_EQ(1, existing_namespaces.size());
  return existing_namespaces.front();
}

26
void PredeclarationVisitor::Predeclare(Declaration* decl) {
27 28 29 30 31 32 33 34 35
  CurrentSourcePosition::Scope scope(decl->pos);
  switch (decl->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Predeclare(name::cast(decl));
    AST_TYPE_DECLARATION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    case AstNode::Kind::kNamespaceDeclaration:
      return Predeclare(NamespaceDeclaration::cast(decl));
36 37 38 39 40
    case AstNode::Kind::kGenericCallableDeclaration:
      return Predeclare(GenericCallableDeclaration::cast(decl));
    case AstNode::Kind::kGenericTypeDeclaration:
      return Predeclare(GenericTypeDeclaration::cast(decl));

41
    default:
42
      // Only processes type declaration nodes, namespaces and generics.
43 44 45 46
      break;
  }
}

47
void DeclarationVisitor::Visit(Declaration* decl) {
48
  CurrentSourcePosition::Scope scope(decl->pos);
49 50 51 52 53 54 55 56 57 58 59
  switch (decl->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Visit(name::cast(decl));
    AST_DECLARATION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
      UNIMPLEMENTED();
  }
}

60
Builtin* DeclarationVisitor::CreateBuiltin(BuiltinDeclaration* decl,
61 62 63
                                           std::string external_name,
                                           std::string readable_name,
                                           Signature signature,
64
                                           base::Optional<Statement*> body) {
65
  const bool javascript = decl->javascript_linkage;
66
  const bool varargs = decl->parameters.has_varargs;
67 68 69
  Builtin::Kind kind = !javascript ? Builtin::kStub
                                   : varargs ? Builtin::kVarArgsJavaScript
                                             : Builtin::kFixedArgsJavaScript;
70

71
  if (varargs && !javascript) {
72 73
    Error("Rest parameters require ", decl->name,
          " to be a JavaScript builtin");
74
  }
75

76 77 78 79 80 81 82 83
  if (javascript) {
    if (!signature.return_type->IsSubtypeOf(TypeOracle::GetJSAnyType())) {
      Error("Return type of JavaScript-linkage builtins has to be JSAny.")
          .Position(decl->return_type->pos);
    }
    for (size_t i = signature.implicit_count;
         i < signature.parameter_types.types.size(); ++i) {
      const Type* parameter_type = signature.parameter_types.types[i];
84 85 86 87
      if (!TypeOracle::GetJSAnyType()->IsSubtypeOf(parameter_type)) {
        Error(
            "Parameters of JavaScript-linkage builtins have to be a supertype "
            "of JSAny.")
88 89 90 91 92
            .Position(decl->parameters.types[i]->pos);
      }
    }
  }

93
  for (size_t i = 0; i < signature.types().size(); ++i) {
94 95 96 97
    if (signature.types()[i]->StructSupertype()) {
      Error("Builtin do not support structs as arguments, but argument ",
            signature.parameter_names[i], " has type ", *signature.types()[i],
            ".");
98 99 100
    }
  }

101 102 103
  if (signature.return_type->StructSupertype()) {
    Error("Builtins cannot return structs, but the return type is ",
          *signature.return_type, ".");
104 105
  }

106 107 108 109
  if (signature.return_type == TypeOracle::GetVoidType()) {
    Error("Builtins cannot have return type void.");
  }

110 111 112 113 114 115 116 117 118 119
  return Declarations::CreateBuiltin(std::move(external_name),
                                     std::move(readable_name), kind,
                                     std::move(signature), body);
}

void DeclarationVisitor::Visit(ExternalBuiltinDeclaration* decl) {
  Declarations::Declare(
      decl->name->value,
      CreateBuiltin(decl, decl->name->value, decl->name->value,
                    TypeVisitor::MakeSignature(decl), base::nullopt));
120 121
}

122 123
void DeclarationVisitor::Visit(ExternalRuntimeDeclaration* decl) {
  Signature signature = TypeVisitor::MakeSignature(decl);
124 125 126 127 128
  if (signature.parameter_types.types.size() == 0) {
    ReportError(
        "Missing parameters for runtime function, at least the context "
        "parameter is required.");
  }
129 130
  if (!(signature.parameter_types.types[0] == TypeOracle::GetContextType() ||
        signature.parameter_types.types[0] == TypeOracle::GetNoContextType())) {
131 132
    ReportError(
        "first parameter to runtime functions has to be the context and have "
133 134
        "type Context or NoContext, but found type ",
        *signature.parameter_types.types[0]);
135
  }
136 137 138 139 140 141 142 143 144 145 146 147 148 149
  if (!(signature.return_type->IsSubtypeOf(TypeOracle::GetObjectType()) ||
        signature.return_type == TypeOracle::GetVoidType() ||
        signature.return_type == TypeOracle::GetNeverType())) {
    ReportError(
        "runtime functions can only return tagged values, but found type ",
        signature.return_type);
  }
  for (const Type* parameter_type : signature.parameter_types.types) {
    if (!parameter_type->IsSubtypeOf(TypeOracle::GetObjectType())) {
      ReportError(
          "runtime functions can only take tagged values as parameters, but "
          "found type ",
          *parameter_type);
    }
150 151
  }

152
  Declarations::DeclareRuntimeFunction(decl->name->value, signature);
153 154
}

155 156 157 158
void DeclarationVisitor::Visit(ExternalMacroDeclaration* decl) {
  Declarations::DeclareMacro(
      decl->name->value, true, decl->external_assembler_name,
      TypeVisitor::MakeSignature(decl), base::nullopt, decl->op);
159 160
}

161
void DeclarationVisitor::Visit(TorqueBuiltinDeclaration* decl) {
162
  Declarations::Declare(
163 164 165
      decl->name->value,
      CreateBuiltin(decl, decl->name->value, decl->name->value,
                    TypeVisitor::MakeSignature(decl), decl->body));
166 167
}

168
void DeclarationVisitor::Visit(TorqueMacroDeclaration* decl) {
169
  Macro* macro = Declarations::DeclareMacro(
170 171
      decl->name->value, decl->export_to_csa, base::nullopt,
      TypeVisitor::MakeSignature(decl), decl->body, decl->op);
172 173 174
  // TODO(szuend): Set identifier_position to decl->name->pos once all callable
  // names are changed from std::string to Identifier*.
  macro->SetPosition(decl->pos);
175 176
}

177 178 179
void DeclarationVisitor::Visit(IntrinsicDeclaration* decl) {
  Declarations::DeclareIntrinsic(decl->name->value,
                                 TypeVisitor::MakeSignature(decl));
180 181
}

182
void DeclarationVisitor::Visit(ConstDeclaration* decl) {
183
  Declarations::DeclareNamespaceConstant(
184
      decl->name, TypeVisitor::ComputeType(decl->type), decl->expression);
185 186
}

187
void DeclarationVisitor::Visit(SpecializationDeclaration* decl) {
188
  std::vector<GenericCallable*> generic_list =
189
      Declarations::LookupGeneric(decl->name->value);
190 191
  // Find the matching generic specialization based on the concrete parameter
  // list.
192
  GenericCallable* matching_generic = nullptr;
193
  Signature signature_with_types = TypeVisitor::MakeSignature(decl);
194
  for (GenericCallable* generic : generic_list) {
195 196 197 198 199 200
    // This argument inference is just to trigger constraint checking on the
    // generic arguments.
    TypeArgumentInference inference = generic->InferSpecializationTypes(
        TypeVisitor::ComputeTypeVector(decl->generic_parameters),
        signature_with_types.GetExplicitTypes());
    if (inference.HasFailed()) continue;
201
    Signature generic_signature_with_types =
202
        MakeSpecializedSignature(SpecializationKey<GenericCallable>{
203
            generic, TypeVisitor::ComputeTypeVector(decl->generic_parameters)});
204 205
    if (signature_with_types.HasSameTypesAs(generic_signature_with_types,
                                            ParameterMode::kIgnoreImplicit)) {
206
      if (matching_generic != nullptr) {
207
        std::stringstream stream;
208
        stream << "specialization of " << decl->name
209
               << " is ambigous, it matches more than one generic declaration ("
210
               << *matching_generic << " and " << *generic << ")";
211 212
        ReportError(stream.str());
      }
213
      matching_generic = generic;
214
    }
215
  }
216

217
  if (matching_generic == nullptr) {
218
    std::stringstream stream;
219
    if (generic_list.size() == 0) {
220 221 222
      stream << "no generic defined with the name " << decl->name;
      ReportError(stream.str());
    }
223
    stream << "specialization of " << decl->name
224 225 226 227
           << " doesn't match any generic declaration\n";
    stream << "specialization signature:";
    stream << "\n  " << signature_with_types;
    stream << "\ncandidates are:";
228
    for (GenericCallable* generic : generic_list) {
229
      stream << "\n  "
230
             << MakeSpecializedSignature(SpecializationKey<GenericCallable>{
231 232
                    generic,
                    TypeVisitor::ComputeTypeVector(decl->generic_parameters)});
233
    }
234 235 236
    ReportError(stream.str());
  }

237 238 239 240 241
  if (GlobalContext::collect_language_server_data()) {
    LanguageServerData::AddDefinition(decl->name->pos,
                                      matching_generic->IdentifierPosition());
  }

242 243
  CallableDeclaration* generic_declaration = matching_generic->declaration();

244 245 246
  Specialize(SpecializationKey<GenericCallable>{matching_generic,
                                                TypeVisitor::ComputeTypeVector(
                                                    decl->generic_parameters)},
247
             generic_declaration, decl, decl->body, decl->pos);
248 249
}

250
void DeclarationVisitor::Visit(ExternConstDeclaration* decl) {
251
  const Type* type = TypeVisitor::ComputeType(decl->type);
252 253 254 255 256 257 258
  if (!type->IsConstexpr()) {
    std::stringstream stream;
    stream << "extern constants must have constexpr type, but found: \""
           << *type << "\"\n";
    ReportError(stream.str());
  }

259
  Declarations::DeclareExternConstant(decl->name, type, decl->literal);
260 261
}

262 263 264 265
void DeclarationVisitor::Visit(CppIncludeDeclaration* decl) {
  GlobalContext::AddCppInclude(decl->include_path);
}

266
void DeclarationVisitor::DeclareSpecializedTypes(
267
    const SpecializationKey<GenericCallable>& key) {
268
  size_t i = 0;
269
  const std::size_t generic_parameter_count =
270
      key.generic->generic_parameters().size();
271
  if (generic_parameter_count != key.specialized_types.size()) {
272 273
    std::stringstream stream;
    stream << "Wrong generic argument count for specialization of \""
274 275
           << key.generic->name() << "\", expected: " << generic_parameter_count
           << ", actual: " << key.specialized_types.size();
276 277 278
    ReportError(stream.str());
  }

279
  for (auto type : key.specialized_types) {
280
    Identifier* generic_type_name = key.generic->generic_parameters()[i++].name;
281 282
    TypeAlias* alias = Declarations::DeclareType(generic_type_name, type);
    alias->SetIsUserDefined(false);
283 284 285
  }
}

286
Signature DeclarationVisitor::MakeSpecializedSignature(
287
    const SpecializationKey<GenericCallable>& key) {
288
  CurrentScope::Scope generic_scope(key.generic->ParentScope());
289
  // Create a temporary fake-namespace just to temporarily declare the
290
  // specialization aliases for the generic types to create a signature.
291 292
  Namespace tmp_namespace("_tmp");
  CurrentScope::Scope tmp_namespace_scope(&tmp_namespace);
293
  DeclareSpecializedTypes(key);
294
  return TypeVisitor::MakeSignature(key.generic->declaration());
295
}
296

297
Callable* DeclarationVisitor::SpecializeImplicit(
298
    const SpecializationKey<GenericCallable>& key) {
299 300 301
  base::Optional<Statement*> body = key.generic->CallableBody();
  if (!body && IntrinsicDeclaration::DynamicCast(key.generic->declaration()) ==
                   nullptr) {
302 303
    ReportError("missing specialization of ", key.generic->name(),
                " with types <", key.specialized_types, "> declared at ",
304
                key.generic->Position());
305
  }
306 307
  SpecializationRequester requester{CurrentSourcePosition::Get(),
                                    CurrentScope::Get(), ""};
308
  CurrentScope::Scope generic_scope(key.generic->ParentScope());
309 310
  Callable* result = Specialize(key, key.generic->declaration(), base::nullopt,
                                body, CurrentSourcePosition::Get());
311
  result->SetIsUserDefined(false);
312 313
  requester.name = result->ReadableName();
  result->SetSpecializationRequester(requester);
314 315 316 317 318 319
  CurrentScope::Scope callable_scope(result);
  DeclareSpecializedTypes(key);
  return result;
}

Callable* DeclarationVisitor::Specialize(
320 321
    const SpecializationKey<GenericCallable>& key,
    CallableDeclaration* declaration,
322
    base::Optional<const SpecializationDeclaration*> explicit_specialization,
323 324
    base::Optional<Statement*> body, SourcePosition position) {
  CurrentSourcePosition::Scope pos_scope(position);
325
  size_t generic_parameter_count = key.generic->generic_parameters().size();
326
  if (generic_parameter_count != key.specialized_types.size()) {
327 328
    std::stringstream stream;
    stream << "number of template parameters ("
329 330
           << std::to_string(key.specialized_types.size())
           << ") to intantiation of generic " << declaration->name
331
           << " doesnt match the generic's declaration ("
332
           << std::to_string(generic_parameter_count) << ")";
333 334
    ReportError(stream.str());
  }
335
  if (key.generic->GetSpecialization(key.specialized_types)) {
336 337
    ReportError("cannot redeclare specialization of ", key.generic->name(),
                " with types <", key.specialized_types, ">");
338 339
  }

340 341 342 343
  Signature type_signature =
      explicit_specialization
          ? TypeVisitor::MakeSignature(*explicit_specialization)
          : MakeSpecializedSignature(key);
344 345

  std::string generated_name = Declarations::GetGeneratedCallableName(
346
      declaration->name->value, key.specialized_types);
347
  std::stringstream readable_name;
348
  readable_name << declaration->name->value << "<";
349 350 351 352 353 354 355
  bool first = true;
  for (const Type* t : key.specialized_types) {
    if (!first) readable_name << ", ";
    readable_name << *t;
    first = false;
  }
  readable_name << ">";
356 357
  Callable* callable;
  if (MacroDeclaration::DynamicCast(declaration) != nullptr) {
358 359 360
    callable =
        Declarations::CreateTorqueMacro(generated_name, readable_name.str(),
                                        false, type_signature, *body, true);
361
  } else if (IntrinsicDeclaration::DynamicCast(declaration) != nullptr) {
362 363
    callable =
        Declarations::CreateIntrinsic(declaration->name->value, type_signature);
364 365
  } else {
    BuiltinDeclaration* builtin = BuiltinDeclaration::cast(declaration);
366 367 368
    callable =
        CreateBuiltin(builtin, GlobalContext::MakeUniqueName(generated_name),
                      readable_name.str(), type_signature, *body);
369
  }
370
  key.generic->AddSpecialization(key.specialized_types, callable);
371
  return callable;
372 373
}

374
void PredeclarationVisitor::ResolvePredeclarations() {
375 376 377 378 379
  for (auto& p : GlobalContext::AllDeclarables()) {
    if (const TypeAlias* alias = TypeAlias::DynamicCast(p.get())) {
      CurrentScope::Scope scope_activator(alias->ParentScope());
      CurrentSourcePosition::Scope position_activator(alias->Position());
      alias->Resolve();
380
    }
381 382 383
  }
}

384 385 386
}  // namespace torque
}  // namespace internal
}  // namespace v8