Normalise line endings.
1 /* vim: set ts=4 sw=4 tw=99 et:
3 * Copyright (C) 2012 David Anderson
5 * This file is part of SourcePawn.
7 * SourcePawn is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License as published by the Free
9 * Software Foundation, either version 3 of the License, or (at your option)
12 * SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY
13 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with
17 * SourcePawn. If not, see http://www.gnu.org/licenses/.
19 #include "../Strings.h"
21 #include "../TypeManager.h"
22 #include "NameBinding.h"
24 #include "ConstantEvaluator.h"
25 #include "../Spaces-inl.h"
26 #include "../Heap-inl.h"
30 // Create symbol tables and symbols for every scope and declaration. For type
31 // declarations and methods, we also pre-allocate a Type object, so that
32 // circular dependencies between types will work.
33 class NamePopulator : public AstVisitor
36 // This class is analagous to a Scope, however, it allows us to create
37 // scopes lazily. If a scope is requested, and the current environment
38 // has no scope, then a scope is created. If no scope is ever requested,
39 // a scope does not need to be created.
43 SymbolEnv(SymbolEnv **prevp, Scope *scope = NULL)
57 void setScope(Scope *scope) {
61 SymbolEnv *prev() const {
80 FunctionScope(FunctionScope **prevp)
90 ReturnStatus returns() const {
93 void returns(ReturnStatus status) {
98 FunctionScope **prevp_;
100 ReturnStatus status_;
104 NamePopulator(Zone *zone, CompileContext &cc, TranslationUnit *unit)
115 ImportScope *importScope = ImportScope::New(pool_);
119 // At the import level, we declare system types.
120 if (!declareSystemTypes(importScope))
123 GlobalScope *globalScope = GlobalScope::New(pool_, importScope);
127 unit_->setImportScope(importScope);
128 unit_->setGlobalScope(globalScope);
130 SymbolEnv env(&env_, globalScope);
132 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
133 Statement *stmt = unit_->tree()->statements()->at(i);
140 bool declareSystemType(ImportScope *scope, const char *name, Handle<Type> effective) {
141 Local<String> tag(zone_, zone_->makeSymbol(name));
145 Local<Type> type(zone_, zone_->types()->getType());
147 TypeSymbol *sym = new (pool_) TypeSymbol(scope, tag, type, effective);
148 return scope->addSymbol(sym);
151 bool declareSystemType(ImportScope *scope, const char *name, PrimitiveType prim) {
152 Local<Type> primitive(zone_, zone_->types()->getPrimitive(prim));
154 return declareSystemType(scope, name, primitive);
157 bool declareSystemTypes(ImportScope *scope) {
158 if (!declareSystemType(scope, "float", PrimitiveType_Float))
160 if (!declareSystemType(scope, "_", PrimitiveType_Int32))
162 if (!declareSystemType(scope, "int", PrimitiveType_Int32))
164 if (!declareSystemType(scope, "bool", PrimitiveType_Bool))
166 if (!declareSystemType(scope, "char", PrimitiveType_Char))
169 Local<Type> voidType(zone_, zone_->types()->getVoid());
170 if (!declareSystemType(scope, "void", voidType))
176 void visitVariableDeclaration(VariableDeclaration *node) {
177 Scope *scope = env_->scope();
178 if (!scope || scope->kind() != Scope::GLOBAL) {
179 if ((scope = getOrCreateBlockScope()) == NULL)
183 if (scope->kind() == Scope::GLOBAL) {
184 // The symbol must be added now, since it could be an export.
185 VariableSymbol *sym = new (pool_) VariableSymbol(scope, node->name(), node->pos());
186 node->setSymbol(sym);
188 if (!registerName(scope, sym))
191 // We ensure the scope will exist at the name binding phase, but
192 // we don't actually register the variable symbol yet. Otherwise,
193 // when binding the initializer, we could encounter:
196 // And we don't necessarily want this to bind.
199 if (node->initialization())
200 node->initialization()->accept(this);
203 void visitEnumStatement(EnumStatement *node) {
204 Local<String> name(zone_, node->name());
205 Local<Type> type(zone_);
207 type = zone_->types()->newEnum(name);
209 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
214 Scope *scope = getGlobalOrCreateBlockScope();
219 Local<Type> symType(zone_, zone_->types()->getType());
220 TypeSymbol *sym = new (pool_) TypeSymbol(scope, name, symType, type);
221 if (!registerName(scope, sym))
224 if (scope->kind() == Scope::GLOBAL) {
225 if (!unit_->globalScope()->exported()->append(sym))
230 // We want each field of the expression to qualify as a constant expression.
231 if ((type = zone_->types()->qualify(type, TypeQual_ConstExpr)) == NULL)
235 for (size_t i = 0; i < node->entries()->length(); i++) {
236 EnumStatement::Entry &entry = node->entries()->at(i);
237 BoxedPrimitive box = BoxedPrimitive::Int(value);
239 if (!EvaluateForConstant(entry.expr, &box) || box.type() != PrimitiveType_Int32) {
240 cc_.reportError(entry.expr->pos(), Message_EnumFieldNotConstant);
244 assert(box.type() == PrimitiveType_Int32);
248 ConstantSymbol *sym = new (pool_) ConstantSymbol(scope, entry.name, entry.pos, type, box);
249 if (!registerName(scope, sym))
251 if (scope->kind() == Scope::GLOBAL) {
252 if (!unit_->globalScope()->exported()->append(sym))
261 void visitFunctionStatement(FunctionStatement *node) {
262 // We create function types ahead of time, not for any particular
263 // reason. It makes things consistent with FunctionTypeStatement,
264 // which actually does produce a type.
265 Local<FunctionType> type(zone_, FunctionType::New(zone_, node->name(), node->token()));
269 assert(env_->scope());
271 // Function statements are always named, so add the name to the outer scope.
272 FunctionSymbol *sym = new (pool_) FunctionSymbol(env_->scope(), node->name(), node->pos(), type);
273 if (!registerName(env_->scope(), sym))
276 if (node->token() == TOK_PUBLIC ||
277 node->token() == TOK_FORWARD ||
278 node->token() == TOK_NATIVE)
280 // We're in the global scope, for sure.
281 assert(env_->scope()->kind() == Scope::GLOBAL);
283 if (!unit_->globalScope()->exported()->append(sym))
287 node->setSymbol(sym);
289 // Scope for the function's arguments.
290 SymbolEnv argEnv(&env_);
291 if (!registerArguments(node->signature()))
294 // Scope for function body.
295 SymbolEnv localEnv(&env_);
296 FunctionScope fun(&fun_);
298 node->body()->accept(this);
300 // Function statements have quirky semantics around their return
301 // type. For reasonable compatibility with SP1, we use the following
302 // heuristics for when no explicit type is declared.
303 if (!node->signature().returnType()) {
304 Local<Type> type(zone_);
305 if (node->token() == TOK_FORWARD || node->token() == TOK_NATIVE) {
306 // If the function type is a native or forward, we always
307 // assume it returns an int32.
308 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
309 } else if (fun.returns() != ValueReturn) {
310 // This function never returns a value, so mark it as
312 type = zone_->types()->getVoid();
314 // No need to NULL check here, we'll catch OOM later.
315 node->sym()->type()->setReturnType(type);
318 node->setScopes(argEnv.scope(), localEnv.scope());
321 void visitStructureStatement(StructureStatement *node) {
325 void visiFunctionTypeStatementt(FunctionTypeStatement *node) {
329 void visitNameProxy(NameProxy *name) {
331 void visitAssignment(Assignment *node) {
332 node->lvalue()->accept(this);
333 node->expression()->accept(this);
335 void visitBinaryExpression(BinaryExpression *node) {
336 node->left()->accept(this);
337 node->right()->accept(this);
339 void visitReturnStatement(ReturnStatement *node) {
340 if (node->expression())
341 fun_->returns(ValueReturn);
343 fun_->returns(VoidReturn);
345 void visitForStatement(ForStatement *node) {
346 SymbolEnv env(&env_);
348 if (node->initialization())
349 node->initialization()->accept(this);
350 if (node->condition())
351 node->condition()->accept(this);
353 node->update()->accept(this);
354 node->body()->accept(this);
356 node->setScope(env.scope());
358 void visitBlockStatement(BlockStatement *node) {
359 if (node->type() == TOK_NEW) {
360 // Don't create a symbol environment for this block, since it
361 // was created solely to house multiple variable decls.
362 for (size_t i = 0; i < node->statements()->length(); i++)
363 node->statements()->at(i)->accept(this);
365 assert(node->type() == TOK_LBRACE);
367 SymbolEnv env(&env_);
369 for (size_t i = 0; i < node->statements()->length(); i++)
370 node->statements()->at(i)->accept(this);
372 if (node->type() == TOK_NEW) {
373 assert(!env.scope());
377 node->setScope(env.scope());
380 void visitIntegerLiteral(IntegerLiteral *node) {
382 void visitExpressionStatement(ExpressionStatement *node) {
383 node->expression()->accept(this);
385 void visitCallExpression(CallExpression *node) {
386 node->callee()->accept(this);
387 for (size_t i = 0; i < node->arguments()->length(); i++)
388 node->arguments()->at(i)->accept(this);
390 void visitIfStatement(IfStatement *node) {
391 node->ifTrue()->accept(this);
393 node->ifFalse()->accept(this);
395 void visitIndexExpression(IndexExpression *node) {
396 node->left()->accept(this);
397 node->right()->accept(this);
399 void visitFloatLiteral(FloatLiteral *node) {
401 void visitWhileStatement(WhileStatement *node) {
402 node->condition()->accept(this);
403 node->body()->accept(this);
405 void visitBreakStatement(BreakStatement *node) {
407 void visitContinueStatement(ContinueStatement *node) {
409 void visitStringLiteral(StringLiteral *node) {
411 void visitIncDecExpression(IncDecExpression *node) {
412 node->expression()->accept(this);
414 void visitUnaryExpression(UnaryExpression *node) {
415 node->expression()->accept(this);
417 void visitTernaryExpression(TernaryExpression *node) {
420 void visitBooleanLiteral(BooleanLiteral *node) {
422 void visitFieldExpression(FieldExpression *node) {
424 void visitSwitchStatement(SwitchStatement *node) {
425 if (node->defaultCase())
426 node->defaultCase()->accept(this);
428 for (size_t i = 0; i < node->cases()->length(); i++)
429 node->cases()->at(i)->statement()->accept(this);
431 void visitArrayLiteral(ArrayLiteral *node) {
433 void visitImportStatement(ImportStatement *node) {
437 Scope *getGlobalOrCreateBlockScope() {
439 assert(env_->scope()->kind() == Scope::BLOCK ||
440 env_->scope()->kind() == Scope::GLOBAL);
441 return env_->scope();
443 return getOrCreateBlockScope();
445 Scope *getOrCreateBlockScope() {
447 assert(env_->scope()->kind() == Scope::BLOCK);
448 return env_->scope();
451 LocalScope *scope = LocalScope::New(pool_);
455 env_->setScope(scope);
459 bool registerName(Scope *scope, Symbol *sym) {
463 if (Symbol *other = scope->localLookup(sym->name())) {
464 // Report, but allow errors to continue.
465 cc_.reportError(sym->pos(), Message_RedeclaredName,
466 sym->name()->chars(),
472 return scope->addSymbol(sym);
475 bool registerArguments(const FunctionSignature &sig) {
476 if (!sig.parameters()->length())
479 ArgumentScope *argScope = ArgumentScope::New(pool_);
482 env_->setScope(argScope);
484 for (size_t i = 0; i < sig.parameters()->length(); i++) {
485 Parameter *param = sig.parameters()->at(i);
486 VariableSymbol *sym = new (pool_) VariableSymbol(argScope, param->name(), param->pos());
487 if (!registerName(env_->scope(), sym))
489 param->setSymbol(sym);
497 PoolAllocator &pool_;
499 TranslationUnit *unit_;
505 ke::PopulateNamesAndTypes(Zone *zone, CompileContext &cc, TranslationUnit *unit)
507 AutoEnterCompileContext enter(cc, unit);
508 NamePopulator populator(zone, cc, unit);
512 static const int INFER_ARRAY_SIZE = 0;
513 static const int EVAL_ARRAY_SIZE = -1;
514 static const int DYNAMIC_ARRAY_SIZE = -2;
516 class NameBinderBase : public AstVisitor
519 NameBinderBase(Zone *zone, CompileContext &cc, TranslationUnit *unit)
528 Type *buildVariableType(VariableDeclaration *node) {
529 Local<Type> type(zone_, bindType(node->type(), node->quals()));
533 // We don't allow array typedefs yet.
534 assert(!type->isArray());
537 int dims[MAX_ARRAY_DEPTH];
538 int levels = evaluateDimensions(node->pos(), type, node->dims(), dims);
542 // Do some extra inference based on the initializer, if present.
543 Expression *init = node->initialization();
545 if (init->isArrayLiteral() && init->toArrayLiteral()->isFixed()) {
546 Local<Type> contained(zone_, type->isArray()
547 ? ArrayType::cast(type)->contained()
549 if (!inferFixedArrayDimensions(init->toArrayLiteral(), contained, dims, levels))
551 } else if (init->isStringLiteral()) {
552 dims[levels - 1] = init->toStringLiteral()->string()->length() + 1;
556 // If we got extra dimensions, we need to build a new type.
558 if ((type = buildArrayType(type, node->quals(), dims, node->dims()->length())) == NULL)
566 int evaluateDimensions(const SourcePosition &pos, Handle<Type> typeArg, ExpressionList *exprs, int dims[MAX_ARRAY_DEPTH]) {
568 Local<Type> type(zone_, typeArg);
569 while (type->isArray()) {
570 ArrayType *atype = ArrayType::cast(type);
571 dims[level] = atype->isFixedLength()
572 ? atype->fixedLength()
573 : DYNAMIC_ARRAY_SIZE;
574 type = atype->contained();
581 if (level + exprs->length() > MAX_ARRAY_DEPTH) {
582 cc_.reportError(pos, Message_MaximumArrayDepth);
586 bool hadEmptySize = false;
587 for (size_t i = 0; i < exprs->length(); i++) {
588 Expression *expr = exprs->at(i);
590 dims[i] = INFER_ARRAY_SIZE;
596 if (EvaluateForConstant(expr, &box) && box.type() == PrimitiveType_Int32) {
597 int size = box.toInt();
599 cc_.reportError(expr->pos(), Message_BadArraySize);
608 cc_.reportError(expr->pos(), Message_BadDynamicInitializer);
612 dims[i] = EVAL_ARRAY_SIZE;
615 return level + exprs->length();
618 // This function computes missing dimension sizes based on a literal
619 // initializer. We don't really handle any size rules here; we just
620 // do a really dumb inference.
621 bool inferFixedArrayDimensions(ArrayLiteral *lit, Handle<Type> contained, int dims[MAX_ARRAY_DEPTH], int levels) {
622 for (int i = 0; i < levels; i++) {
623 if (dims[i] == EVAL_ARRAY_SIZE || dims[i] == DYNAMIC_ARRAY_SIZE) {
624 // The following are invalid:
625 // new x[<expr>] = {...}
626 // new Type:x = {...} // where Type is a non-fixed array type
627 cc_.reportError(lit->pos(), Message_CannotInitializeEvalArray);
631 if (dims[i] == INFER_ARRAY_SIZE) {
632 // Character arrays are always dynamic when inferred from string literals.
633 if (i == levels - 1 && contained->isChar())
634 dims[i] = DYNAMIC_ARRAY_SIZE;
636 dims[i] = lit->expressions()->length();
639 if (i != levels - 1) {
640 // Fixed array literals are guaranteed to have at least one expression.
641 Expression *next = lit->expressions()->at(0);
642 if (!next->isArrayLiteral()) {
643 // Whelp... this array is just malformed. Not the best error message
645 cc_.reportError(next->pos(), Message_ArraySizeCannotBeDetermined);
648 lit = next->toArrayLiteral();
655 ArrayType *buildArrayType(Handle<Type> contained, TypeQualifiers quals, int dims[MAX_ARRAY_DEPTH], size_t postlevels) {
656 Local<Type> type(zone_, contained);
658 for (size_t i = postlevels - 1; i < postlevels; i--) {
659 int size = dims[i] > 0
661 : ArrayType::DYNAMIC_ARRAY_SIZE;
663 if ((type = zone_->types()->newArray(contained, size)) == NULL)
665 if ((type = zone_->types()->qualify(type, quals)) == NULL)
668 return ArrayType::cast(type);
671 bool fillFunctionType(Handle<FunctionType> fun, const FunctionSignature &sig) {
672 Local<Type> type(zone_);
673 if (!fun->returnType()) {
674 if ((type = bindType(sig.returnType(), TypeQual_None)) == NULL)
676 fun->setReturnType(type);
682 Local<FixedArray> params(zone_, FixedArray::New(zone_, sig.parameters()->length(), Heap::Tenure_Old));
686 for (size_t i = 0; i < sig.parameters()->length(); i++) {
687 Parameter *param = sig.parameters()->at(i);
688 if ((type = bindType(param->type(), param->quals())) == NULL)
691 assert(!type->isArray());
694 int dims[MAX_ARRAY_DEPTH];
695 int levels = evaluateDimensions(param->pos(), type, param->dims(), dims);
699 // If we got extra dimensions, we need to build a new type.
700 // Unlike variables, we do not infer anything about array
701 // sizes from its default initializer.
703 if ((type = buildArrayType(type, param->quals(), dims, param->dims()->length())) == NULL)
707 if (ArrayType::cast(type)->innermost()->isVoid()) {
708 cc_.reportError(param->type()->pos(), Message_CannotDeclareVoid);
713 if (param->reference()) {
714 if (!type->isPod()) {
715 cc_.reportError(param->pos(), Message_ArrayCantBeReference);
718 if (param->quals() & TypeQual_Const) {
719 cc_.reportError(param->pos(), Message_CannotConstReference);
722 if ((type = zone_->types()->getReference(type, false)) == NULL)
725 if (param->quals() & TypeQual_Const) {
726 if (!type->isArray() && !type->isStruct()) {
727 cc_.reportError(param->pos(), Message_InvalidConstOnFormal);
732 if (type->isVoid()) {
733 cc_.reportError(param->type()->pos(), Message_CannotDeclareVoid);
737 params->set(zone_, i, type);
738 param->sym()->setType(type);
741 fun->setParameterTypes(params);
746 Type *bindType(Expression *expr, TypeQualifiers quals) {
747 Local<Type> type(zone_);
750 // If no type was declared, we return int32.
751 type = zone_->types()->getPrimitive(PrimitiveType_Int32);
755 NameProxy *proxy = expr->asNameProxy();
758 Symbol *sym = proxy->sym();
762 if (!sym->isType()) {
763 cc_.reportError(expr->pos(), Message_IdentifierIsNotAType, sym->name()->chars());
767 type = sym->toType()->effective();
770 return zone_->types()->qualify(type, quals);
775 PoolAllocator &pool_;
777 TranslationUnit *unit_;
780 class GlobalBuilder : public NameBinderBase
782 typedef ScopedRoot<Descriptor> ScopedDescriptor;
783 struct PrimitiveFill {
784 ScopedDescriptor *desc;
787 PrimitiveFill(ScopedDescriptor *desc, BoxedPrimitive prim)
795 GlobalBuilder(Zone *zone, CompileContext &cc, TranslationUnit *unit)
796 : NameBinderBase(zone, cc, unit),
797 globalScope_(unit->globalScope())
802 for (size_t i = 0; i < unit_->tree()->imports()->length(); i++)
803 unit_->tree()->imports()->at(i)->accept(this);
805 // Next, enter the global scope and walk all statements.
806 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
807 Statement *stmt = unit_->tree()->statements()->at(i);
811 Local<Struct> globals(zone_, createGlobals());
821 Struct *createGlobals() {
822 Local<FixedArray> descs(zone_, FixedArray::New(zone_, descriptors_.length(), Heap::Tenure_Old));
826 for (unsigned i = 0; i < descriptors_.length(); i++)
827 descs->set(zone_, i, *descriptors_[i]);
829 Local<String> name(zone_, unit_->module()->name());
830 Local<StructType> type(zone_, StructType::New(zone_, name, descs));
834 Local<StructMap> map(zone_, type->newMap());
835 return Struct::New(zone_, map, Heap::Tenure_Old);
838 void populate(Handle<Struct> globals) {
839 // This is a huge hack, but it's probably better than a full extra
840 // pass. The problem is that until we have all the descriptors, we
841 // can't start setting constexprs in the struct, and we need to set
842 // them now so they're available during full semantic analysis. To
843 // work around this, we build up the list of values we need to set
844 // as we build up descriptors, and then populate the global struct
847 // Note, this code is also kind of dead until we support linking. We
848 // handle constexprs explicitly in importFrom(), by sniffing out the
849 // symbol type. That code will go away later.
850 for (size_t i = 0; i < primitiveFills_.length(); i++) {
851 const PrimitiveFill &fill = primitiveFills_[i];
852 assert(fill.prim.type() == PrimitiveType_Int32);
853 globals->set(*fill.desc, fill.prim.toInt());
858 void visitEnumStatement(EnumStatement *stmt) {
859 if (stmt->visibility() != TOK_PUBLIC || !stmt->name())
862 Local<Type> type(zone_, zone_->types()->getType());
863 Descriptor *desc = Descriptor::New(zone_, stmt->name(), type, Descriptor::Public);
866 if (!descriptors_.append(new (pool_) ScopedRoot<Descriptor>(desc)))
869 for (size_t i = 0; i < stmt->entries()->length(); i++) {
870 EnumStatement::Entry &e = stmt->entries()->at(i);
871 ScopedDescriptor *desc = new (pool_) ScopedDescriptor(Descriptor::New(zone_, e.name, e.sym->type(), Descriptor::Public));
872 if (!desc || !descriptors_.append(desc))
875 // Save the value so we can export it immediately.
876 if (!primitiveFills_.append(PrimitiveFill(desc, e.sym->value())))
881 void visitNameProxy(NameProxy *proxy) {
882 Scope *scope = unit_->globalScope();
883 Symbol *sym = scope->lookup(proxy->name());
885 cc_.reportError(proxy->pos(), Message_IdentifierNotFound, proxy->name()->chars());
889 void visitFunctionStatement(FunctionStatement *node) {
890 Local<FunctionType> type(zone_, node->sym()->type());
891 if (!fillFunctionType(type, node->signature()))
895 if (!builder_.add(type, &offset))
898 Descriptor::Visibility visibility = (node->token() == TOK_NATIVE || node->token() == TOK_FORWARD)
900 : Descriptor::Private;
902 Descriptor *desc = Descriptor::New(zone_, node->name(), type, visibility);
905 if (!descriptors_.append(new (pool_) ScopedRoot<Descriptor>(desc)))
909 void visitVariableDeclaration(VariableDeclaration *node) {
910 Local<Type> type(zone_, buildVariableType(node));
914 // If we're in global scope, and we received a |const| qualifier, then
915 // we extend this to array references as well. This is to sort of mimic
916 // SP1 functionality, but also means that you cannot have changeable
917 // const pointers in global scope.
918 if ((node->quals() & TypeQual_Const) && type->isArray()) {
919 if ((type = zone_->types()->qualify(type, TypeQual_Const)) == NULL)
923 node->sym()->setType(type);
926 if (!builder_.add(type, &offset))
929 Descriptor *desc = Descriptor::New(zone_, node->name(), type, Descriptor::Private);
932 if (!descriptors_.append(new (pool_) ScopedRoot<Descriptor>(desc)))
936 void visitImportStatement(ImportStatement *node) {
937 if (!node->names()) {
938 PathComponent *path = node->path();
942 // Imports automatically go into the importScope. For now, we
943 // error if there are any duplicate symbols entered into the
945 if (unit_->importScope()->localLookup(path->name)) {
946 cc_.reportError(node->pos(), Message_DuplicateImport, path->name->chars());
950 Local<Type> type(zone_, zone_->types()->getImportable());
951 ImportSymbol *sym = new (pool_) ImportSymbol(unit_->importScope(), path->name, node->pos(), type, node->importIndex());
952 if (!unit_->importScope()->addSymbol(sym))
954 } else if (node->importAllNames()) {
955 Local<Importable> importable(zone_, unit_->module()->getImportAt(node->importIndex()));
956 if (importable->isPackage()) {
959 Local<Module> module(zone_, Module::cast(importable));
960 if (!module->globals())
961 importAllFromTranslationUnit(node, module->translationUnit());
966 Local<Importable> importable(zone_, unit_->module()->getImportAt(node->importIndex()));
967 if (importable->isPackage()) {
970 Local<Module> module(zone_, Module::cast(importable));
972 // Always grab from the translation unit if we can, for now.
973 if (module->translationUnit())
974 importFromTranslationUnit(node, module->translationUnit());
982 bool importFrom(ImportStatement *node, Symbol *import) {
983 assert(import->type());
985 // Check for duplicate import names.
986 if (unit_->importScope()->localLookup(import->name())) {
987 cc_.reportError(node->pos(), Message_DuplicateImport, import->name()->chars());
992 if (import->isType()) {
993 // Fuck it, make a TypeSymbol instead of an ImplicitSymbol. This
994 // makes bindType() much simpler. We may run into problems
995 // implementing linking, but it seems unlikely, as long as we are
996 // exporting Types in module structs.
997 Local<Type> type(zone_, zone_->types()->getType());
998 sym = new (pool_) TypeSymbol(unit_->importScope(),
1001 import->toType()->effective());
1002 } else if (import->isConstant()) {
1003 // Same deal. No reason to lookup in the module globals if we
1004 // already have a symbol.
1005 sym = new (pool_) ConstantSymbol(unit_->importScope(),
1009 import->toConstant()->value());
1011 sym = new (pool_) ImplicitSymbol(unit_->importScope(),
1015 node->importIndex());
1018 if (!unit_->importScope()->addSymbol(sym))
1024 void importFromTranslationUnit(ImportStatement *node, TranslationUnit *other) {
1025 assert(!other->failed());
1027 for (size_t i = 0; i < node->names()->length(); i++) {
1028 Handle<String> name = *node->names()->at(i);
1030 // See if the name exists in the other translation unit.
1031 Symbol *import = other->globalScope()->findExported(name);
1033 FixedArray *path = unit_->module()->importPathAt(node->importIndex());
1034 cc_.reportError(node->pos(), Message_NotFoundInImportable,
1036 String::cast(path->at(path->length() - 1))->chars());
1040 if (!importFrom(node, import))
1045 void importAllFromTranslationUnit(ImportStatement *node, TranslationUnit *other) {
1046 assert(!other->failed());
1048 for (size_t i = 0; i < other->globalScope()->exported()->length(); i++) {
1049 Symbol *import = other->globalScope()->exported()->at(i);
1050 if (!importFrom(node, import))
1056 StructureBufferBuilder builder_;
1057 Vector<ScopedRoot<Descriptor> *> descriptors_;
1058 GlobalScope *globalScope_;
1059 Vector<PrimitiveFill> primitiveFills_;
1062 class NameBinder : public NameBinderBase
1068 AutoLinkScope(AutoLinkScope **prevp, Scope *scope)
1076 scope_->setParent(prev_->scope());
1081 assert(*prevp_ == this);
1085 Scope *scope() const {
1090 AutoLinkScope **prevp_;
1091 AutoLinkScope *prev_;
1096 NameBinder(Zone *zone, CompileContext &cc, TranslationUnit *unit)
1097 : NameBinderBase(zone, cc, unit),
1103 // Start with the import scope, and collect all imported names.
1104 AutoLinkScope importScope(&link_, unit_->importScope());
1106 for (size_t i = 0; i < unit_->tree()->imports()->length(); i++)
1107 unit_->tree()->imports()->at(i)->accept(this);
1109 // Next, enter the global scope and walk all statements.
1110 AutoLinkScope globalScope(&link_, unit_->globalScope());
1111 for (size_t i = 0; i < unit_->tree()->statements()->length(); i++) {
1112 Statement *stmt = unit_->tree()->statements()->at(i);
1117 void visitVariableDeclaration(VariableDeclaration *node) {
1118 // Bind the initializer before registering the declaration, so that we
1119 // can error on bogus initializers (new x = x).
1120 if (node->initialization())
1121 node->initialization()->accept(this);
1123 // If the node already has a symbol (meaning it was a global), then
1124 // we don't have to do anything more.
1128 Local<Type> type(zone_, buildVariableType(node));
1132 VariableSymbol *sym = new (pool_) VariableSymbol(link_->scope(), node->name(), node->pos(), type);
1133 node->setSymbol(sym);
1135 if (Symbol *other = link_->scope()->localLookup(sym->name())) {
1136 // Report, but allow errors to continue.
1137 cc_.reportError(sym->pos(), Message_RedeclaredName,
1138 sym->name()->chars(),
1144 link_->scope()->addSymbol(sym);
1146 void visitEnumStatement(EnumStatement *node) {
1148 void visitFunctionStatement(FunctionStatement *node) {
1149 AutoLinkScope argScope(&link_, node->argScope());
1150 AutoLinkScope varScope(&link_, node->varScope());
1152 // If the function is in the global scope, we've already computed its
1154 if (node->sym()->scope()->kind() != Scope::GLOBAL) {
1155 Local<FunctionType> type(zone_, node->sym()->type());
1156 if (!fillFunctionType(type, node->signature()))
1161 node->body()->accept(this);
1163 void visitStructureStatement(StructureStatement *node) {
1166 void visitFunctionTypeStatement(FunctionTypeStatement *node) {
1170 void visitNameProxy(NameProxy *proxy) {
1171 // We could have already bound globals.
1175 Scope *scope = link_->scope();
1176 Symbol *sym = scope->lookup(proxy->name());
1178 cc_.reportError(proxy->pos(), Message_IdentifierNotFound, proxy->name()->chars());
1181 void visitAssignment(Assignment *node) {
1182 node->lvalue()->accept(this);
1183 node->expression()->accept(this);
1185 void visitBinaryExpression(BinaryExpression *node) {
1186 node->left()->accept(this);
1187 node->right()->accept(this);
1189 void visitReturnStatement(ReturnStatement *node) {
1190 node->expression()->accept(this);
1192 void visitForStatement(ForStatement *node) {
1193 AutoLinkScope scope(&link_, node->scope());
1195 if (node->initialization())
1196 node->initialization()->accept(this);
1197 if (node->condition())
1198 node->condition()->accept(this);
1200 node->update()->accept(this);
1201 node->body()->accept(this);
1203 void visitBlockStatement(BlockStatement *node) {
1204 AutoLinkScope scope(&link_, node->scope());
1205 for (size_t i = 0; i < node->statements()->length(); i++)
1206 node->statements()->at(i)->accept(this);
1208 void visitIntegerLiteral(IntegerLiteral *node) {
1210 void visitExpressionStatement(ExpressionStatement *node) {
1211 node->expression()->accept(this);
1213 void visitCallExpression(CallExpression *node) {
1214 node->callee()->accept(this);
1215 for (size_t i = 0; i < node->arguments()->length(); i++)
1216 node->arguments()->at(i)->accept(this);
1218 void visitIfStatement(IfStatement *node) {
1219 node->condition()->accept(this);
1220 node->ifTrue()->accept(this);
1221 if (node->ifFalse())
1222 node->ifFalse()->accept(this);
1224 void visitIndexExpression(IndexExpression *node) {
1225 node->left()->accept(this);
1226 node->right()->accept(this);
1228 void visitFloatLiteral(FloatLiteral *node) {
1230 void visitWhileStatement(WhileStatement *node) {
1231 node->condition()->accept(this);
1232 node->body()->accept(this);
1234 void visitBreakStatement(BreakStatement *node) {
1236 void visitContinueStatement(ContinueStatement *node) {
1238 void visitStringLiteral(StringLiteral *node) {
1240 void visitIncDecExpression(IncDecExpression *node) {
1241 node->expression()->accept(this);
1243 void visitUnaryExpression(UnaryExpression *node) {
1245 node->tag()->accept(this);
1246 node->expression()->accept(this);
1248 void visitTernaryExpression(TernaryExpression *node) {
1249 node->condition()->accept(this);
1250 node->left()->accept(this);
1251 node->right()->accept(this);
1253 void visitBooleanLiteral(BooleanLiteral *node) {
1255 void visitFieldExpression(FieldExpression *node) {
1256 node->left()->accept(this);
1258 void visitSwitchStatement(SwitchStatement *node) {
1259 node->expression()->accept(this);
1260 node->defaultCase()->accept(this);
1261 for (size_t i = 0; i < node->cases()->length(); i++) {
1262 // We don't test case expressions because they are literals.
1263 Case *c = node->cases()->at(i);
1264 c->statement()->accept(this);
1267 void visitArrayLiteral(ArrayLiteral *node) {
1268 for (size_t i = 0; i < node->expressions()->length(); i++)
1269 node->expressions()->at(i)->accept(this);
1271 void visitImportStatement(ImportStatement *node) {
1275 AutoLinkScope *link_;
1279 ke::BindGlobals(Zone *zone, CompileContext &cc, TranslationUnit *unit)
1281 AutoEnterCompileContext enter(cc, unit);
1283 GlobalBuilder builder(zone, cc, unit);
1284 Local<Struct> globals(zone, builder.build());
1285 if (!globals || unit->failed())
1288 unit->module()->setGlobals(globals);
1292 ke::BindNamesAndTypes(Zone *zone, CompileContext &cc, TranslationUnit *unit)
1294 AutoEnterCompileContext enter(cc, unit);
1295 NameBinder binder(zone, cc, unit);