Example usage for org.antlr.v4.runtime Token getLine

List of usage examples for org.antlr.v4.runtime Token getLine

Introduction

In this page you can find the example usage for org.antlr.v4.runtime Token getLine.

Prototype

int getLine();

Source Link

Document

The line number on which the 1st character of this token was matched, line=1..n

Usage

From source file:info.fulloo.trygve.parser.Pass1Listener.java

License:Open Source License

public <ExprType> Expression newExpr(final List<ParseTree> ctxChildren, final Token ctxGetStart,
        final ExprType ctxExpr, final MessageContext ctxMessage) {
    // : NEW message
    // | NEW type_name '[' expr ']'

    // Called in all passes.
    Expression expression = null; // guaranteed non-null return
    final Message message = parsingData_.popMessage();
    final Type enclosingMegaType = Expression.nearestEnclosingMegaTypeOf(currentScope_);
    if (null == ctxExpr && null != ctxMessage) {
        // : 'new' message
        final String classOrContextName = message.selectorName(); // I know -- kludge ...
        final Type type = currentScope_.lookupTypeDeclarationRecursive(classOrContextName);
        if ((type instanceof ClassType) == false && (type instanceof ContextType) == false
                && (type instanceof BuiltInType) == false) {
            if (type instanceof TemplateParameterType) {
                // then it's Ok
                expression = new NewExpression(type, message, ctxMessage.getStart().getLine(),
                        enclosingMegaType);
                addSelfAccordingToPass(type, message, currentScope_);
            } else {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "`new ", classOrContextName,
                        "': can apply `new' only to a class or Context type", "");
                expression = new ErrorExpression(null);
            }// w ww .j a v  a2  s  . c o m
        } else {
            // On the first pass, message doesn't yet have an argument list
            expression = new NewExpression(type, message, ctxMessage.getStart().getLine(), enclosingMegaType);

            // This adds a hokey argument to the message that
            // is used mainly for signature checking - to see
            // if there is a constructor that matches the
            // arguments of the "new" message.
            addSelfAccordingToPass(type, message, currentScope_);
        }

        // Is there a constructor?
        // This does anything on Passes 2 and 3 only
        ctorCheck(type, message, ctxGetStart.getLine());
    } else if (null != ctxExpr && null == ctxMessage) {
        // | 'new' type_name '[' abelian_expr ']'
        final Expression expr = parsingData_.popExpression();
        final ExpressionStackAPI raw_type_expression = parsingData_.popRawExpression();
        assert raw_type_expression instanceof Type;
        final Type type_name_expression = (Type) raw_type_expression;
        final String typeName = type_name_expression.name();
        final Type type = currentScope_.lookupTypeDeclarationRecursive(typeName);
        if (null == type) {
            if (expr.isntError()) {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "'new ", typeName,
                        " [] for undefined type: ", typeName);
            }
            expression = new ErrorExpression(expr);
        } else {
            expr.setResultIsConsumed(true);
            expression = new NewArrayExpression(type, expr, enclosingMegaType);
        }
    } else {
        assert false; // internal error of some kind
    }

    assert null != expression;
    return expression;
}

From source file:info.fulloo.trygve.parser.Pass1Listener.java

License:Open Source License

public <ExprType> Expression messageSend(final Token ctxGetStart, final ExprType ctx_abelianAtom,
        final Builtin_type_nameContext ctx_typeName) {
    // | expr '.' message
    // | message/* ww w. j  a  v  a2  s. co  m*/
    // Pass 1 version
    // Pop the expression for the indicated object and message
    Expression object = null;
    Type type = null, enclosingMegaType = null;
    MethodDeclaration mdecl = null;

    if (null != ctx_abelianAtom) {
        if (parsingData_.currentExpressionExists()) {
            object = parsingData_.popExpression();
        } else {
            object = new ErrorExpression(null);
        }
    } else if (null != ctx_typeName) {
        // e.g. String.join
        final String typeName = ctx_typeName.getText();
        final Type theType = currentScope_.lookupTypeDeclarationRecursive(typeName);
        final Type classType = StaticScope.globalScope().lookupTypeDeclaration("Class");
        object = new IdentifierExpression(theType.name(), classType, classType.enclosedScope().parentScope(),
                ctxGetStart.getLine());
    } else {
        final StaticScope nearestMethodScope = Expression.nearestEnclosingMethodScopeAround(currentScope_);
        enclosingMegaType = Expression.nearestEnclosingMegaTypeOf(currentScope_);
        if (null == enclosingMegaType) {
            object = new ErrorExpression(null);
        } else {
            object = new IdentifierExpression("this", enclosingMegaType, nearestMethodScope,
                    ctxGetStart.getLine());
        }
    }
    assert null != object;

    final Message message = parsingData_.popMessage();

    if (null == enclosingMegaType && (object instanceof NullExpression || object.isError())) {
        // Because this here is Pass 1 code this really does nothing.
        // We'll catch it again on Pass 2
        errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Invoking method `",
                message.selectorName(), "' on implied object `this' in a non-object context.", "");
    } else {
        final Type objectType = object.type();
        if (null == objectType)
            return new ErrorExpression(object); // error stumbling avoidance

        final String methodSelectorName = message.selectorName();
        final ClassDeclaration classdecl = currentScope_.lookupClassDeclarationRecursive(objectType.name());
        mdecl = classdecl != null
                ? classdecl.enclosedScope().lookupMethodDeclaration(methodSelectorName, null, true)
                : null;

        if (null != mdecl) {
            if (objectType.name().equals("Class")) {
                // Is of the form ClassType.classMethod()
                assert object instanceof IdentifierExpression;
                if (false == mdecl.signature().isStatic()) {
                    errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                            "Attempt to call instance method `" + mdecl.signature().getText(),
                            "' as though it were a static method of class `", objectType.name(), "'.");
                }
            }
        }

        if (null == mdecl) {
            // final String className = classdecl != null? classdecl.name(): " <unresolved>.";
            // skip it - we'll barked at the user in pass 2
            // errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `", methodSelectorName, "' not declared in class ", className);
            type = StaticScope.globalScope().lookupTypeDeclaration("void");
        } else {
            type = mdecl.returnType();

            // This is tautological a no-op, because we
            // castrate this stuff within Pass 1
            // checkForMessageSendViolatingConstness(mdecl.signature(), ctxGetStart);
        }

        // If there is an error in the method return type, type might still be null
        if (null == type) {
            type = StaticScope.globalScope().lookupTypeDeclaration("void");
        }

        if (null != type && type instanceof TemplateParameterType) {
            // Is a template type. Change the return type into a bona fide type here
            final StaticScope objectScope = objectType.enclosedScope();
            final TemplateInstantiationInfo templateInstantiationInfo = objectScope.templateInstantiationInfo();
            type = templateInstantiationInfo.classSubstitionForTemplateTypeNamed(type.name());
        }

        assert type != null;
    }

    object.setResultIsConsumed(true);

    MethodInvocationEnvironmentClass originMethodClass = MethodInvocationEnvironmentClass.Unknown;
    if (null != currentScope_.associatedDeclaration()) {
        originMethodClass = currentScope_.methodInvocationEnvironmentClass();
    } else {
        final Type anotherType = object.enclosingMegaType();
        if (null != anotherType) {
            final StaticScope anotherScope = anotherType.enclosedScope();
            originMethodClass = anotherScope.methodInvocationEnvironmentClass();
        } else {
            originMethodClass = MethodInvocationEnvironmentClass.ClassEnvironment; // outermost scope
        }
    }
    final MethodInvocationEnvironmentClass targetMethodClass = null == message.enclosingMegaType()
            ? MethodInvocationEnvironmentClass.ClassEnvironment
            : message.enclosingMegaType().enclosedScope().methodInvocationEnvironmentClass();
    final boolean isStatic = (null != mdecl) && (null != mdecl.signature()) && mdecl.signature().isStatic();

    boolean isPolymorphic = true;
    if (amInConstructor()) {
        if (object instanceof IdentifierExpression) {
            // Don't dynamically dispatch methods from within a constructor
            if (((IdentifierExpression) object).name().equals("this")) {
                isPolymorphic = false;
            }
        }
    }

    if (null != type) {
        // Should probably never be true - here...
        final boolean isAConstructor = type.name().equals(message.selectorName());
        if (false == isAConstructor) {
            // Update the message type properly. Constructors are weird in
            // that the message type is void whereas the expression type is
            // in terms of the thing being constructed.
            message.setReturnType(type);
        }
    }

    final MessageExpression retval = new MessageExpression(object, message, type, ctxGetStart.getLine(),
            isStatic, originMethodClass, targetMethodClass, isPolymorphic);

    return retval;
}

From source file:info.fulloo.trygve.parser.Pass1Listener.java

License:Open Source License

protected Type processReturnType(final Token ctxGetStart, final Expression object, final Type objectType,
        final Message message) {
    final String objectTypeName = objectType.name();
    final ClassDeclaration classDecl = currentScope_.lookupClassDeclarationRecursive(objectTypeName);
    final RoleDeclaration roleDecl = currentScope_.lookupRoleOrStagePropDeclarationRecursive(objectTypeName);
    final ContextDeclaration contextDecl = currentScope_.lookupContextDeclarationRecursive(objectTypeName);
    final InterfaceDeclaration interfaceDecl = currentScope_
            .lookupInterfaceDeclarationRecursive(objectTypeName);

    final String methodSelectorName = message.selectorName();
    assert null != methodSelectorName;

    MethodDeclaration mdecl = null;//  w  w w  .  j  a v  a  2s.  c  o  m
    Type returnType = null;
    final ActualArgumentList actualArgumentList = message.argumentList();
    boolean roleHint = false;

    if (null != classDecl) {
        mdecl = processReturnTypeLookupMethodDeclarationUpInheritanceHierarchy(classDecl, methodSelectorName,
                actualArgumentList);
        if (null == mdecl) {
            final Type currentEnclosingType = Expression.nearestEnclosingMegaTypeOf(currentScope_);
            if (currentEnclosingType instanceof TemplateType) {
                // Ingore parameters as in Pass 1. We may not find a match with a template type...
                mdecl = classDecl.enclosedScope().lookupMethodDeclarationRecursive(methodSelectorName,
                        actualArgumentList, true);
                if (null == mdecl && actualArgumentList.isntError()) {
                    errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `",
                            methodSelectorName + actualArgumentList.selflessGetText(),
                            "' not declared in class `", classDecl.name(), "'.", "");
                }
            } else if (actualArgumentList.isntError()) {
                // Look at Object. Could be an assert or something
                final ClassDeclaration objectDecl = currentScope_.lookupClassDeclarationRecursive("Object");
                assert null != objectDecl;
                mdecl = processReturnTypeLookupMethodDeclarationIgnoringRoleStuffIn(objectDecl,
                        methodSelectorName, actualArgumentList);

                if (null == mdecl) {
                    errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `",
                            methodSelectorName + actualArgumentList.selflessGetText(),
                            "' not declared in class `", classDecl.name(), "'.", "");
                }
            }
        }

        final ClassDeclaration baseClassDeclaration = classDecl.baseClassDeclaration();
        if (null != baseClassDeclaration) {
            final String baseClassName = baseClassDeclaration.name();
            boolean noerrors = true;
            if (methodSelectorName.equals(baseClassName) && null != mdecl && mdecl.enclosingScope().pathName()
                    .equals(baseClassDeclaration.enclosedScope().pathName())) {
                // We are invoking a base class constructor. Cool.
                // Make sure it's the first thing in the class.
                if (parsingData_.currentExprAndDeclExists()) {
                    final ExprAndDeclList currentExprAndDecl = parsingData_.currentExprAndDecl();
                    if (currentExprAndDecl.bodyParts().isEmpty() == false) {
                        errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                                "Call of base class constructor `", baseClassName,
                                "' must be the first statement in the derived class constructor.", "");
                        noerrors = false;
                    }
                    if (mdecl.accessQualifier() != AccessQualifier.PublicAccess) {
                        errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                                "Call of base class constructor for class `", baseClassName,
                                "', which is not accessible to class `", classDecl.name() + "'.");
                        noerrors = false;
                    }
                }

                // Make sure the current method is a constructor!
                final MethodSignature currentMethod = parsingData_.currentMethodSignature();
                final ClassDeclaration currentClass = parsingData_.currentClassDeclaration();
                if (currentClass.name().equals(currentMethod.name()) == false) {
                    errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Base class constructor `",
                            baseClassName, "' can be explicitly invoked only from a derived class constructor.",
                            "");
                    noerrors = false;
                }

                if (noerrors) {
                    // There is code that automatically generates a
                    // base class constructor call (to a default constructor)
                    // if it can find one. If the programmer has taken over,
                    // cancel the automatic one.

                    // Get the calling method
                    final StaticScope callingScope = classDecl.enclosedScope();
                    FormalParameterList paramsToCurrentMethod = currentMethod.formalParameterList();
                    final String callingConstructorName = classDecl.name();
                    final MethodDeclaration callingMethod = callingScope
                            .lookupMethodDeclaration(callingConstructorName, paramsToCurrentMethod, false);
                    assert null != callingMethod;
                    callingMethod.hasManualBaseClassConstructorInvocations(true);
                }
            }
        }
    } else if (null != roleDecl) {
        // Calling a role method
        mdecl = processReturnTypeLookupMethodDeclarationIn(roleDecl, methodSelectorName, actualArgumentList);

        if (null == mdecl) {
            // First, check in requires list
            final Map<String, List<MethodSignature>> requiresSection = roleDecl.requiredSelfSignatures();
            final List<MethodSignature> possibleRequiredFunctions = requiresSection.get(methodSelectorName);
            if (null != possibleRequiredFunctions) {
                for (final MethodSignature aRequiredFunction : possibleRequiredFunctions) {
                    // We don't insist on parameter type matching in Pass 1. Pass 2 will catch that.
                    // But we'll try.
                    if (aRequiredFunction.formalParameterList().alignsWithUsingConversion(actualArgumentList)) {
                        mdecl = new MethodDeclaration(aRequiredFunction, roleDecl.enclosedScope(),
                                aRequiredFunction.lineNumber());
                        mdecl.addParameterList(aRequiredFunction.formalParameterList());
                        mdecl.setReturnType(mdecl.returnType());
                        break;
                    }
                }

                // Even if the signatures don't match, it may be because we have incomplete
                // type information. For now, give it a pass if the selector name is O.K.
                if (possibleRequiredFunctions.size() > 0) {
                    final MethodSignature aRequiredFunction = possibleRequiredFunctions.get(0);
                    mdecl = new MethodDeclaration(aRequiredFunction, roleDecl.enclosedScope(),
                            aRequiredFunction.lineNumber());
                    mdecl.addParameterList(aRequiredFunction.formalParameterList());
                    mdecl.setReturnType(mdecl.returnType());
                }
            }

            if (null == mdecl) {
                // If this is a Role variable, it's fair game to look for
                // methods in what will be a base class for every Role-player:
                // class object
                final ClassDeclaration objectDecl = currentScope_.lookupClassDeclarationRecursive("Object");
                assert null != objectDecl;

                mdecl = processReturnTypeLookupMethodDeclarationIn(objectDecl, methodSelectorName,
                        actualArgumentList);
                if (null == mdecl) {
                    mdecl = processReturnTypeLookupMethodDeclarationIgnoringRoleStuffIn(objectDecl,
                            methodSelectorName, actualArgumentList);
                    roleHint = true;
                }
            }
        }
        if (null == mdecl) {
            if (actualArgumentList.isntError()) {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `",
                        methodSelectorName + actualArgumentList.selflessGetText(), "' not declared in Role `",
                        roleDecl.name() + "'.");
            }
            if (message.lineNumber() < roleDecl.lineNumber()) {
                final MethodSignature enclosingMethod = parsingData_.currentMethodSignature();
                if (null != enclosingMethod) {
                    errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                            "\tTry moving the declaration of `", roleDecl.name(),
                            "' before the definition of method `", enclosingMethod.getText() + "'.");
                } else {
                    errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                            "\tTry moving the declaration of `", roleDecl.name(),
                            "' before the invocation of `", methodSelectorName + "'.");
                }
            }
        }
    } else if (null != contextDecl) {
        mdecl = processReturnTypeLookupMethodDeclarationUpInheritanceHierarchy(contextDecl, methodSelectorName,
                actualArgumentList);
        if (null == mdecl) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `",
                    methodSelectorName + actualArgumentList.selflessGetText(), "' not declared in Context `",
                    contextDecl.name() + "'.");
        }
    } else if (null != interfaceDecl) {
        final MethodSignature methodSignature = interfaceDecl
                .lookupMethodSignatureDeclaration(methodSelectorName, actualArgumentList);
        if (null == methodSignature) {
            if (actualArgumentList.isntError()) {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `",
                        methodSelectorName + actualArgumentList.selflessGetText(),
                        "' not declared in Interface `", interfaceDecl.name() + "'.");
            }
            returnType = new ErrorType();
        } else {
            returnType = methodSignature.returnType();
        }
    } else if (objectTypeName.equals("Class")) {
        final ClassDeclaration classDeclaration = currentScope_.lookupClassDeclarationRecursive(object.name());
        if (null == classDeclaration) {
            if (object.isntError()) {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                        "Cannot find class, Role, or interface `", object.name(), "'", "");
            }
        } else {
            mdecl = classDeclaration.enclosedScope().lookupMethodDeclaration(methodSelectorName,
                    actualArgumentList, false);
            if (null == mdecl) {
                mdecl = classDeclaration.enclosedScope().lookupMethodDeclarationWithConversionIgnoringParameter(
                        methodSelectorName, actualArgumentList, false, /*parameterToIgnore*/ null);
                if (null == mdecl) {
                    errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                            "Cannot find static script `" + methodSelectorName + actualArgumentList.getText(),
                            "' of class `", object.name(), "'.");
                }
            }
        }
    } else if (objectTypeName.endsWith("_$array")) {
        if (methodSelectorName.equals("size") && actualArgumentList.count() == 1) {
            returnType = StaticScope.globalScope().lookupTypeDeclaration("int"); // is O.K.
        } else if (methodSelectorName.equals("at") && actualArgumentList.count() == 2) {
            returnType = ((ArrayType) objectType).baseType(); // is O.K.
        } else if (methodSelectorName.equals("atPut") && actualArgumentList.count() == 3) {
            returnType = StaticScope.globalScope().lookupTypeDeclaration("void"); // is O.K.
        } else {
            if (object.name().length() > 0) {
                if (object.isntError()) {
                    errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                            "Cannot find class, Role, or interface for `", object.name(), "'.", "");
                }
            } else {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                        "Cannot find class, Role, or interface of this ", "type", "", "");
            }
            assert null == mdecl;
        }
    } else {
        if (object.name().length() > 0) {
            if (object.isntError() && objectType.isntError()) {
                errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                        "Cannot find class, Role, or interface for `", object.name(), "'.", "");
            }
        } else {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Cannot find class, Role, or interface of this ", "type", "", "");
        }
        assert null == mdecl;
    }

    if (null != mdecl) {
        final FormalParameterList formals = mdecl.formalParameterList();
        assert formals != null;
        final ActualArgumentList actuals = message.argumentList();
        assert actuals != null;

        final TypeDeclaration typeDecl = null != classDecl ? classDecl : contextDecl;

        // Type check is polymorphic in compiler passes
        this.typeCheckIgnoringParameter(formals, actuals, mdecl, typeDecl, "this", ctxGetStart, roleHint);

        returnType = mdecl.returnType();
    }

    returnType = null == returnType ? StaticScope.globalScope().lookupTypeDeclaration("void") : returnType;

    return returnType;
}

From source file:info.fulloo.trygve.parser.Pass1Listener.java

License:Open Source License

public Expression idExpr(final TerminalNode ctxJAVA_ID, final Token ctxGetStart) {
    // Pass 1 version
    final StaticScope globalScope = StaticScope.globalScope();
    Expression expression = null;
    Type type = null;//w  w w .jav a 2s . co  m
    StaticScope declaringScope = null;
    final String idName = ctxJAVA_ID.getText();
    ObjectDeclaration objdecl = currentScope_.lookupObjectDeclarationRecursive(idName);
    final RoleDeclaration roleDecl = currentScope_.lookupRoleOrStagePropDeclarationRecursive(idName);
    final StaticScope nearestEnclosingMethodScope = Expression.nearestEnclosingMethodScopeAround(currentScope_);
    ClassAndObjectDeclaration classAndObjectDeclaration = null;
    if (idName.equals("index") || idName.equals("lastIndex")) {
        // This is a legal identifier if invoked from within the
        // scope of a Role, where the Role is declared as a Role
        // vector type
        type = StaticScope.globalScope().lookupTypeDeclaration("void"); // default/error value
        expression = new NullExpression();
        if (null == currentRoleOrStageProp_) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Symbol `", idName,
                    "' may be used only within certain Role methods.", "");
            type = new ErrorType();
        } else {
            if (currentRoleOrStageProp_.isArray()) {
                expression = idName.equals("index")
                        ? new IndexExpression(currentRoleOrStageProp_, currentContext_)
                        : new LastIndexExpression(currentRoleOrStageProp_, currentContext_);
            } else {
                errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Symbol `", idName,
                        "' may be used only within a Role vector method. The Role ",
                        currentRoleOrStageProp_.name(), " is a not a vector.", "");
                type = new ErrorType();
            }
        }
    } else if (null != objdecl) {
        if (null != this.isRoleAssignmentWithinContext(idName)) {
            type = StaticScope.globalScope().lookupTypeDeclaration("void");
        } else {
            type = objdecl.type();
        }
        declaringScope = objdecl.enclosingScope();

        if (null == type) {
            type = StaticScope.globalScope().lookupTypeDeclaration("void");
        }

        // NOTE: This will also lump in references to Role identifiers
        // They are distinguished by its enclosing scope
        expression = new IdentifierExpression(idName, type, declaringScope, ctxGetStart.getLine());
    } else if (null != roleDecl) {
        // Someone is invoking a role. Cool.
        declaringScope = roleDecl.enclosingScope();
        final Type rawRoleType = declaringScope.lookupTypeDeclaration(idName); // Type$RoleType
        if (null != rawRoleType) { // stumbling check
            assert rawRoleType instanceof RoleType;
            final RoleType roleType = (RoleType) rawRoleType;
            if (this.isInsideMethodDeclaration(ctxJAVA_ID)) {
                final IdentifierExpression qualifier = new IdentifierExpression("this", roleType,
                        nearestEnclosingMethodScope, ctxGetStart.getLine());
                qualifier.setResultIsConsumed(true);
                expression = new QualifiedIdentifierExpression(qualifier, idName, roleType);
            } else {
                errorHook5p2(ErrorIncidenceType.Unimplemented, ctxGetStart.getLine(),
                        "Static initializers for Roles are unimplemented.", "", "", "");
                expression = new ErrorExpression(null);
            }
        } else {
            expression = new ErrorExpression(null);
        }
    } else if (null != (classAndObjectDeclaration = isMemberOfEnclosingObject(idName))) {
        objdecl = classAndObjectDeclaration.objectDecl();
        final Type classType = classAndObjectDeclaration.classType();
        final IdentifierExpression qualifier = new IdentifierExpression("this", classType,
                nearestEnclosingMethodScope, ctxGetStart.getLine());
        qualifier.setResultIsConsumed(true);
        expression = new QualifiedIdentifierExpression(qualifier, idName, objdecl.type());
    } else {
        final ClassDeclaration cdecl = currentScope_.lookupClassDeclarationRecursive(idName);
        if (null != cdecl) {
            type = globalScope.lookupTypeDeclaration("Class");
            declaringScope = globalScope;
        } else if (null == declaringScope) {
            // NOTE: This will also lump in references to Role identifiers
            // They are distinguished by their enclosing scope
            declaringScope = Expression.nearestEnclosingMethodScopeAround(currentScope_);
        }

        if (null == type) {
            type = StaticScope.globalScope().lookupTypeDeclaration("void");
        }

        expression = new IdentifierExpression(idName, type, declaringScope, ctxGetStart.getLine());
    }

    assert null != expression;
    return expression;
}

From source file:info.fulloo.trygve.parser.Pass1Listener.java

License:Open Source License

public <ContextArgType extends ParserRuleContext> Expression assignmentExpr(final Expression lhs,
        final String operator, final Expression rhs, final ContextArgType ctx) {
    // abelian_expr ASSIGN expr
    assert null != rhs;
    assert null != lhs;

    final Token ctxGetStart = ctx.getStart();
    final int lineNumber = ctxGetStart.getLine();

    final Type lhsType = lhs.type(), rhsType = rhs.type();

    boolean tf = lhsType instanceof RoleType;
    tf = null != rhsType;/* w w  w.ja  va  2  s .  co m*/
    if (lhsType instanceof RoleType && rhsType instanceof ArrayType) {
        if (((RoleType) lhsType).isArray()) {
            tf = lhsType.canBeConvertedFrom(((ArrayType) rhsType).baseType(), lineNumber, this);
        } else {
            // Maybe the Role just wants to be played by an array, building on
            // its at and atPut interface
            tf = lhsType.canBeConvertedFrom(rhsType, lineNumber, this);
            if (tf == false) {
                if (lhs.isntError() && rhs.isntError() && rhsType.isntError()) {
                    errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Type of `", lhs.getText(),
                            "' is incompatible with expression type `", rhsType.name(), "'.", "");
                }
            }
        }
    } else if (null != lhsType && null != rhsType) {
        tf = lhsType.canBeConvertedFrom(rhsType, lineNumber, this);
    } else {
        tf = false;
    }

    if (lhs.name().equals("this")) {
        errorHook5p2(ErrorIncidenceType.Noncompliant, lineNumber, "You're on your own here.", "", "", "");
    }

    if (lhs.name().equals("index") || lhs.name().equals("lastIndex")) {
        errorHook5p2(ErrorIncidenceType.Fatal, lineNumber,
                "`index' is a reserved word which is a read-only property of a Role vector element,",
                " and may not be assigned.", "", "");
    } else if (lhsType instanceof RoleType && null != rhsType && rhsType instanceof ArrayType) {
        final Type baseType = ((ArrayType) rhsType).baseType();
        if (lhsType.canBeConvertedFrom(baseType)) {
            this.checkRoleClassNameCollision((RoleType) lhsType, baseType, ctxGetStart.getLine());
        } else {
            // Maybe the Role is trying to be an array, using the at and atPut
            // facilities...
            if (lhsType.canBeConvertedFrom(rhsType)) {
                this.checkRoleClassNameCollision((RoleType) lhsType, rhsType, ctxGetStart.getLine());
            } else {
                errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Role vector elements of type `",
                        lhsType.name(), "' cannot be played by objects of type `",
                        ((ArrayType) rhsType).baseType().name(), "':", "");
            }
        }
    } else if (lhsType instanceof RoleType && null != rhsType) {
        final boolean isRoleArray = lhsType instanceof RoleType
                && ((RoleType) lhsType).associatedDeclaration() instanceof RoleArrayDeclaration;
        final boolean isStagePropArray = lhsType instanceof StagePropType
                && ((StagePropType) lhsType).associatedDeclaration() instanceof StagePropArrayDeclaration;
        if ((isRoleArray || isStagePropArray) && rhsType instanceof ClassType
                && rhsType.name().startsWith("List<")) {
            // includes stage props
            final String ofWhatThisIsAList = rhsType.name().substring(5, rhsType.name().length() - 1);
            final Type rhsBaseType = currentScope_.lookupTypeDeclarationRecursive(ofWhatThisIsAList);
            if (null != rhsBaseType && rhsBaseType.isntError()) { // error stumbling check
                tf = lhsType.canBeConvertedFrom(rhsBaseType, lineNumber, this);
                if (false == tf && lhs.isntError() && rhs.isntError()) {
                    errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Roles in `", lhsType.name(),
                            "' cannot be played by objects of type `", rhsBaseType.name(), "':", "");
                    this.reportMismatchesWith(lineNumber, (RoleType) lhsType, rhsBaseType);
                }
            }
        } else if (lhsType.canBeConvertedFrom(rhsType) == false && lhs.isntError() && rhs.isntError()
                && lhsType.isntError() && rhsType.isntError()) {
            errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Role `", lhsType.name(),
                    "' cannot be played by object of type `", rhsType.name(), "':", "");
            this.reportMismatchesWith(lineNumber, (RoleType) lhsType, rhsType);
        }
        this.checkRoleClassNameCollision((RoleType) lhsType, rhsType, ctxGetStart.getLine());
    } else if (null != lhsType && null != rhsType && lhsType.canBeConvertedFrom(rhsType) == false
            && lhs.isntError() && rhs.isntError() && rhsType.isntError()) {
        errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Type of `", lhsType.name(),
                "' is incompatible with expression type `", rhsType.name(), "'.", "");
    } else if (lhs instanceof ArrayIndexExpression) {
        final Type anotherLhsType = ((ArrayIndexExpression) lhs).baseType();
        if (null != anotherLhsType && null != rhsType && anotherLhsType.canBeConvertedFrom(rhsType) == false
                && lhs.isntError() && rhs.isntError() && rhsType.isntError()) {
            errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Type of `", lhs.getText(),
                    "' is incompatible with expression type `", rhsType.name(), "'.", "");
        }
    } else if (lhs instanceof RoleArrayIndexExpression) {
        if (lhsType.canBeConvertedFrom(rhsType) == false && lhs.isntError() && rhs.isntError()) {
            errorHook6p2(ErrorIncidenceType.Fatal, lineNumber, "Role `", lhsType.name(),
                    "' cannot be played by object of type `", rhsType.name(), "':", "");
            this.reportMismatchesWith(lineNumber, (RoleType) lhsType, rhsType);
        }
    } else if ((lhs instanceof IdentifierExpression) == false
            && (lhs instanceof QualifiedIdentifierExpression) == false && lhs.isntError() && rhs.isntError()) {
        errorHook5p2(ErrorIncidenceType.Fatal, lineNumber,
                "Can assign only to an identifier, qualified identifier, or vector element.", "", "", "");
    }

    rhs.setResultIsConsumed(true);

    final AssignmentExpression retval = new AssignmentExpression(lhs, operator, rhs, lineNumber, this);
    checkForAssignmentViolatingConstness(retval, ctx.getStart());

    return retval;
}

From source file:info.fulloo.trygve.parser.Pass2Listener.java

License:Open Source License

@Override
protected void checkExprDeclarationLevel(RuleContext ctxParent, Token ctxGetStart) {
    // Certified Pass 2 version :-)
    RuleContext executionContext = ctxParent;
    while ((executionContext instanceof ProgramContext) == false) {
        if (executionContext instanceof Method_declContext) {
            break;
        } else if (executionContext instanceof Stageprop_bodyContext) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Expression cannot just appear in stageprop scope: it must be in a method", "", "", "");
            break;
        } else if (executionContext instanceof Role_bodyContext) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Expression cannot just appear in Role scope: it must be in a method", "", "", "");
            break;
        } else if (executionContext instanceof Stageprop_declContext) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Expression cannot just appear in stageprop scope: it must be in a method", "", "", "");
            break;
        } else if (executionContext instanceof Role_declContext) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Expression cannot just appear in Role scope: it must be in a method", "", "", "");
            break;
        } else if (executionContext instanceof Class_bodyContext) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Expression cannot just appear in Class scope: it must be in a method", "", "", "");
            break;
        } else if (executionContext instanceof Type_declarationContext) {
            errorHook5p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(),
                    "Expression cannot just appear in a global program element scope: it must be in a method",
                    "", "", "");
            break;
        }/*from w  w w  .  ja v  a 2s .  c  o  m*/
        executionContext = executionContext.parent;
    }
}

From source file:info.fulloo.trygve.parser.Pass2Listener.java

License:Open Source License

@Override
public void binopTypeCheck(final Expression leftExpr, final String operationAsString,
        final Expression rightExpr, final Token ctxGetStart) {
    // Certified Pass 2 version ;-)
    final Type leftExprType = leftExpr.type(), rightExprType = rightExpr.type();
    final Type resultType = leftExprType;

    if (resultType.canBeConvertedFrom(rightExpr.type()) == false && leftExpr.isntError()
            && rightExpr.isntError() && leftExpr.type().isntError() && rightExpr.type().isntError()) {
        errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Invalid operands to `" + "",
                operationAsString, "' on type ", leftExpr.type().name(), " with operand of type ",
                rightExpr.type().name());
    }/*  w  w  w . j a va 2 s  . co m*/
    final ActualArgumentList argList = new ActualArgumentList();
    argList.addActualArgument(rightExpr);
    final Expression self = new IdentifierExpression("t$his", resultType, resultType.enclosedScope(),
            ctxGetStart.getLine());
    argList.addFirstActualParameter(self);
    final StaticScope enclosedScope = resultType.enclosedScope();

    MethodDeclaration mdecl = enclosedScope.lookupMethodDeclarationWithConversionIgnoringParameter(
            operationAsString, argList, false, /*parameterToIgnore*/ null);
    if (null == mdecl) {
        mdecl = enclosedScope.lookupMethodDeclarationRecursive(operationAsString, argList, false);
        if (null == mdecl) {
            mdecl = enclosedScope.lookupMethodDeclarationIgnoringRoleStuff(operationAsString, argList);
            if (null == mdecl && rightExpr.isntError() && rightExpr.type().isntError()
                    && resultType.isntError()) {
                errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "No such operation `",
                        operationAsString, "' on type `", resultType.name(),
                        "' for argument `" + rightExpr.type().name(), "'.");
            }
        }
    }

    // First, check "overloading"
    final ActualArgumentList argumentList = new ActualArgumentList();
    argumentList.addActualArgument(rightExpr);
    argumentList.addFirstActualParameter(leftExpr);
    final MethodDeclaration checkMethodOverload = leftExprType.enclosedScope()
            .lookupMethodDeclarationWithConversionIgnoringParameter(operationAsString, argumentList, false,
                    /*parameterToIgnore*/ null);

    if (null != checkMethodOverload) {
        ; // then the class overloads the operator. O.K.
    } else if (leftExprType.canBeLhsOfBinaryOperatorForRhsType(operationAsString, rightExprType)
            && rightExprType.canBeRhsOfBinaryOperator(operationAsString)) {
        ; // o.k.
    } else if (rightExpr.isntError() && resultType.isntError() && rightExpr.type().isntError()) {
        errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Operation `", operationAsString,
                "' cannot be applied to type `", resultType.name(), "' for argument `",
                rightExpr.type().name() + "'.");
    }
}

From source file:info.fulloo.trygve.parser.Pass2Listener.java

License:Open Source License

public ExpressionStackAPI exprFromExprDotJavaId(TerminalNode ctxJAVA_ID, Token ctxGetStart) {
    // : expr '.' JAVA_ID
    // Pop the expression for the indicated object and message
    // Certified Pass 2 version ;-)

    Type type = null;// ww  w.  ja  va2s. co  m
    final ExpressionStackAPI qualifier = parsingData_.popRawExpression();
    Expression expression = null;
    final String javaIdString = ctxJAVA_ID.getText();

    if (qualifier.type().name().equals("Class")) {
        // This is where we handle types like "System" for System.out.print*
        // Now we need to get the actual class of that name
        final Type rawClass = currentScope_.lookupTypeDeclarationRecursive(qualifier.name());
        assert rawClass instanceof ClassType;
        final ClassType theClass = (ClassType) rawClass;

        final ObjectDeclaration odecl = theClass.type().enclosedScope().lookupObjectDeclaration(javaIdString);
        if (odecl.type() != null)
            type = odecl.type();
        expression = new QualifiedClassMemberExpression(theClass, javaIdString, type);
    } else {
        final ObjectDeclaration odecl = qualifier.type().enclosedScope()
                .lookupObjectDeclarationRecursive(javaIdString);

        if (null == odecl) {
            final MethodDeclaration javaId2 = qualifier.type().enclosedScope()
                    .lookupMethodDeclarationRecursive(javaIdString, null, true);
            if (null == javaId2) {
                errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Identifier `", javaIdString,
                        "' not declared for object `", qualifier.name(), "'.", "");
                type = new ErrorType();
            } else {
                type = javaId2.returnType();
            }
        } else {
            type = odecl.type();
            assert type != null;
        }

        assert qualifier instanceof Expression;
        expression = new QualifiedIdentifierExpression((Expression) qualifier, javaIdString, type);
    }

    assert null != expression;

    return expression;
}

From source file:info.fulloo.trygve.parser.Pass2Listener.java

License:Open Source License

private void contextInvocationCheck(final Type nearestEnclosingMegaType, final Message message,
        final Type objectType, final Type wannabeContextType, final Token ctxGetStart) {
    // Don't allow Role methods directly to invoke
    // Context methods. Look up the method in the enclosing
    // context and make sure it's not there. But first we
    // can say it's O.K. if it's either another method
    // in the Role.
    MethodDeclaration testDecl = nearestEnclosingMegaType.enclosedScope()
            .lookupMethodDeclarationIgnoringParameter(message.selectorName(), message.argumentList(), "this",
                    true);//  www .jav a 2 s .  c  om
    if (null == testDecl) {
        // Check in the Requires list
        final RoleType objectTypeAsRoleType = (RoleType) objectType;
        final RoleDeclaration roleDecl = (RoleDeclaration) objectTypeAsRoleType.associatedDeclaration();
        final MethodSignature signatureInRequiresSection = declarationForMessageFromRequiresSectionOfRole(
                message, roleDecl);
        if (null == signatureInRequiresSection) {
            testDecl = wannabeContextType.enclosedScope().lookupMethodDeclarationIgnoringParameter(
                    message.selectorName(), message.argumentList(), "this", true);
            if (null != testDecl) {
                final StaticScope currentMethodScope = Expression
                        .nearestEnclosingMethodScopeAround(currentScope_);
                errorHook5p2(ErrorIncidenceType.Noncompliant, ctxGetStart.getLine(),
                        "NONCOMPLIANT: Enacting enclosed Context script `",
                        message.selectorName() + message.argumentList().selflessGetText(),
                        "' from within `" + nearestEnclosingMegaType.name() + "."
                                + currentMethodScope.associatedDeclaration().name(),
                        "'.");
            }
        }
    }
}

From source file:info.fulloo.trygve.parser.Pass2Listener.java

License:Open Source License

private void otherRolesRequiresInvocationCheck(final Type nearestEnclosingMegaType, final Message message,
        final Type objectType, final Type wannabeContextType, final Token ctxGetStart) {
    // Don't allow Role methods directly to invoke
    // the "requires" methods of other Roles in the same Context.
    // But first we can say it's O.K. if it's within the same Role.
    if (currentRoleOrStageProp_.type().pathName().equals(objectType.pathName())) {
        ; // is within the same Role; it's cool
    } else {//from w  w w.  j a v  a  2  s  . c o m
        final MethodDeclaration testDecl = nearestEnclosingMegaType.enclosedScope()
                .lookupMethodDeclarationIgnoringParameter(message.selectorName(), message.argumentList(),
                        "this", true);
        if (null != testDecl) {
            ; // is a regular Role method  is O.K.
        } else {
            // Check in the Requires list
            final RoleType objectTypeAsRoleType = (RoleType) objectType;
            final RoleDeclaration roleDecl = (RoleDeclaration) objectTypeAsRoleType.associatedDeclaration();
            final MethodSignature signatureInRequiresSection = declarationForMessageFromRequiresSectionOfRole(
                    message, roleDecl);
            if (null != signatureInRequiresSection) {
                // It's O.K. if the signature has been pulled into the Role interface

                final MethodSignature publishedSignature = roleDecl
                        .lookupPublishedSignatureDeclaration(signatureInRequiresSection);
                if (null != publishedSignature) {
                    // Is it public?
                    if (publishedSignature.accessQualifier() != AccessQualifier.PublicAccess) {
                        errorHook6p2(ErrorIncidenceType.Fatal, ctxGetStart.getLine(), "Script `",
                                message.selectorName(), "' is not public and so is not accessible to `",
                                nearestEnclosingMegaType.name(), "'.", "");
                    }
                } else {
                    errorHook5p2(ErrorIncidenceType.Noncompliant, ctxGetStart.getLine(),
                            "NONCOMPLIANT: Trying to enact object script `",
                            message.selectorName() + message.argumentList().selflessGetText(),
                            "' without using the interface of the Role it is playing: `" + roleDecl.name(),
                            "'.");
                }
            }
        }
    }
}