예제 #1
0
 public ParserRuleContext([Nullable] Antlr4.Runtime.ParserRuleContext parent, int invokingStateNumber)
     : base(parent, invokingStateNumber)
 {
 }
예제 #2
0
 public override void ExitEveryRule(ParserRuleContext context)
 {
     Logger.writeLog("{end rule: " + this.parser.RuleNames[context.RuleIndex] + " : " + context.Start.Text + "}\n");
 }
예제 #3
0
 /// <inheritdoc/>
 /// <remarks>The default implementation does nothing.</remarks>
 public virtual void EnterEveryRule([NotNull] ParserRuleContext context) /*System.Console.WriteLine("enter EveryRule");*/ }
예제 #4
0
 public void AddFunctionDeclaration(string memberName, Antlr4.Runtime.ParserRuleContext functionDefinition)
 {
     FunctionDeclarations.Add(memberName, functionDefinition);
 }
예제 #5
0
 public SyneryInterpretationException(Antlr4.Runtime.ParserRuleContext tree, string message, Exception inner)
     : base(message, inner)
 {
     ParseTree = tree;
 }
예제 #6
0
 internal ParseException(Antlr4.Runtime.ParserRuleContext context, string message, string fileName = "(unknown)") : base(context, message, fileName)
 {
 }
예제 #7
0
 public TemporaryName(List <Part> parts, IDeclarativeRegion currentScore, VHDL_ANTLR4.vhdlVisitor visitor, Antlr4.Runtime.ParserRuleContext context)
 {
     this.parts        = parts;
     this.currentScore = currentScore;
     this.visitor      = visitor;
     this.context      = context;
 }
 /// <inheritdoc/>
 /// <remarks>The default implementation does nothing.</remarks>
 public virtual void ExitEveryRule([NotNull] ParserRuleContext context)
 {
 }
예제 #9
0
        public override void EnterEveryRule([Antlr4.Runtime.Misc.NotNull] Antlr4.Runtime.ParserRuleContext context)
        {
            string s = context.GetText();

            System.Console.WriteLine(s);
        }
예제 #10
0
 public TemporaryName(List <Part> parts, VHDL_ANTLR4.vhdlVisitor visitor, Antlr4.Runtime.ParserRuleContext context)
     : this(parts, visitor.currentScope, visitor, context)
 {
 }
예제 #11
0
 public virtual void ExitEveryRule(ParserRuleContext context)
 {
 }
예제 #12
0
        /// <summary>
        /// creates an exception that represents a runtime error with the interpretation of a RequestSelectItem
        /// </summary>
        /// <param name="context"></param>
        /// <param name="index">the row index of the current record</param>
        /// <param name="record">the current record</param>
        /// <param name="innerException">the original exception</param>
        /// <returns>an exception that contains all available details for the current context</returns>
        public static SyneryQueryInterpretationException CreateRequestSelectItemContextInterpretationException(Antlr4.Runtime.ParserRuleContext context, int index, object[] record, Exception innerException)
        {
            string values = "";

            foreach (var item in record)
            {
                values += item + ",";
            }

            values = values.TrimEnd(new char[] { ',' });

            return(new SyneryQueryInterpretationException(context, index, record, string.Format("Error starting on line {0} with record index {1} ({2}). The error message was: {3}", context.Start.Line, index, values, innerException.Message), innerException));
        }
예제 #13
0
        private (IExprTerm, List <IPStmt>) SimplifyExpression(IPExpr expr)
        {
            Antlr4.Runtime.ParserRuleContext location = expr.SourceLocation;
            List <IPStmt> deps = new List <IPStmt>();

#pragma warning disable CCN0002 // Non exhaustive patterns in switch block
            switch (expr)
            {
            case IExprTerm term:
                return(term, deps);

            case BinOpExpr binOpExpr:
                (IExprTerm lhsTemp, List <IPStmt> lhsDeps) = SimplifyExpression(binOpExpr.Lhs);
                (IExprTerm rhsTemp, List <IPStmt> rhsDeps) = SimplifyExpression(binOpExpr.Rhs);

                if (binOpExpr.Operation == BinOpType.And)
                {
                    // And is short-circuiting, so we need to treat it differently from other binary operators
                    deps.AddRange(lhsDeps);
                    (VariableAccessExpr andTemp, IPStmt andInitialStore) = SaveInTemporary(new CloneExpr(lhsTemp));
                    deps.Add(andInitialStore);
                    CompoundStmt reassignFromRhs = new CompoundStmt(location, rhsDeps.Append(new AssignStmt(location, andTemp, new CloneExpr(rhsTemp))));
                    deps.Add(new IfStmt(location, andTemp, reassignFromRhs, null));
                    return(andTemp, deps);
                }
                else if (binOpExpr.Operation == BinOpType.Or)
                {
                    // Or is short-circuiting, so we need to treat it differently from other binary operators
                    deps.AddRange(lhsDeps);
                    (VariableAccessExpr orTemp, IPStmt orInitialStore) = SaveInTemporary(new CloneExpr(lhsTemp));
                    deps.Add(orInitialStore);
                    CompoundStmt reassignFromRhs = new CompoundStmt(location, rhsDeps.Append(new AssignStmt(location, orTemp, new CloneExpr(rhsTemp))));
                    deps.Add(new IfStmt(location, orTemp, new NoStmt(location), reassignFromRhs));
                    return(orTemp, deps);
                }
                else
                {
                    (VariableAccessExpr binOpTemp, IPStmt binOpStore) =
                        SaveInTemporary(new BinOpExpr(location, binOpExpr.Operation, lhsTemp, rhsTemp));
                    deps.AddRange(lhsDeps.Concat(rhsDeps));
                    deps.Add(binOpStore);
                    return(binOpTemp, deps);
                }

            case CastExpr castExpr:
                (IExprTerm castSubExpr, List <IPStmt> castDeps) = SimplifyExpression(castExpr.SubExpr);
                (VariableAccessExpr castTemp, IPStmt castStore) = SaveInTemporary(new CastExpr(location, new CloneExpr(castSubExpr), castExpr.Type));
                deps.AddRange(castDeps);
                deps.Add(castStore);
                return(castTemp, deps);

            case ChooseExpr chooseExpr:
                if (chooseExpr.SubExpr != null)
                {
                    (IExprTerm chooseSubExpr, List <IPStmt> chooseDeps) = SimplifyExpression(chooseExpr.SubExpr);
                    (VariableAccessExpr chooseTemp, IPStmt chooseStore) = SaveInTemporary(new ChooseExpr(location, chooseSubExpr, chooseExpr.Type));
                    deps.AddRange(chooseDeps);
                    deps.Add(chooseStore);
                    return(chooseTemp, deps);
                }
                else
                {
                    (VariableAccessExpr chooseTemp, IPStmt chooseStore) = SaveInTemporary(chooseExpr);
                    deps.Add(chooseStore);
                    return(chooseTemp, deps);
                }

            case CoerceExpr coerceExpr:
                (IExprTerm coerceSubExpr, List <IPStmt> coerceDeps) = SimplifyExpression(coerceExpr.SubExpr);
                (VariableAccessExpr coerceTemp, IPStmt coerceStore) =
                    SaveInTemporary(new CoerceExpr(location, coerceSubExpr, coerceExpr.NewType));
                deps.AddRange(coerceDeps);
                deps.Add(coerceStore);
                return(coerceTemp, deps);

            case ContainsExpr containsKeyExpr:
                (IExprTerm contKeyExpr, List <IPStmt> contKeyDeps) = SimplifyExpression(containsKeyExpr.Item);
                (IExprTerm contMapExpr, List <IPStmt> contMapDeps) = SimplifyExpression(containsKeyExpr.Collection);
                (VariableAccessExpr contTemp, IPStmt contStore)    =
                    SaveInTemporary(new ContainsExpr(location, contKeyExpr, contMapExpr));
                deps.AddRange(contKeyDeps.Concat(contMapDeps));
                deps.Add(contStore);
                return(contTemp, deps);

            case CtorExpr ctorExpr:
                (IReadOnlyList <IVariableRef> ctorArgs, List <IPStmt> ctorArgDeps) = SimplifyArgPack(ctorExpr.Arguments);
                deps.AddRange(ctorArgDeps);
                (VariableAccessExpr ctorTemp, IPStmt ctorStore) = SaveInTemporary(new CtorExpr(location, ctorExpr.Interface, ctorArgs));
                deps.Add(ctorStore);
                return(ctorTemp, deps);

            case DefaultExpr defaultExpr:
                (VariableAccessExpr defTemp, IPStmt defStore) = SaveInTemporary(defaultExpr);
                deps.Add(defStore);
                return(defTemp, deps);

            case FairNondetExpr fairNondetExpr:
                (VariableAccessExpr fndTemp, IPStmt fndStore) = SaveInTemporary(fairNondetExpr);
                deps.Add(fndStore);
                return(fndTemp, deps);

            case FunCallExpr funCallExpr:
                (ILinearRef[] funArgs, List <IPStmt> funArgsDeps) = SimplifyFunArgs(funCallExpr.Arguments);
                deps.AddRange(funArgsDeps);
                (VariableAccessExpr funTemp, IPStmt funStore) = SaveInTemporary(new FunCallExpr(location, funCallExpr.Function, funArgs));
                deps.Add(funStore);
                return(funTemp, deps);

            case KeysExpr keysExpr:
                (IExprTerm keysColl, List <IPStmt> keysDeps)    = SimplifyExpression(keysExpr.Expr);
                (VariableAccessExpr keysTemp, IPStmt keysStore) = SaveInTemporary(new KeysExpr(location, keysColl, keysExpr.Type));
                deps.AddRange(keysDeps);
                deps.Add(keysStore);
                return(keysTemp, deps);

            case MapAccessExpr mapAccessExpr:
                (IExprTerm mapExpr, List <IPStmt> mapDeps)            = SimplifyExpression(mapAccessExpr.MapExpr);
                (IExprTerm mapIdxExpr, List <IPStmt> mapIdxDeps)      = SimplifyExpression(mapAccessExpr.IndexExpr);
                (VariableAccessExpr mapItemTemp, IPStmt mapItemStore) =
                    SaveInTemporary(new MapAccessExpr(location, mapExpr, mapIdxExpr, mapAccessExpr.Type));
                deps.AddRange(mapDeps.Concat(mapIdxDeps));
                deps.Add(mapItemStore);
                return(mapItemTemp, deps);

            case SetAccessExpr setAccessExpr:
                (IExprTerm setExpr, List <IPStmt> setDeps)            = SimplifyExpression(setAccessExpr.SetExpr);
                (IExprTerm setIdxExpr, List <IPStmt> setIdxDeps)      = SimplifyExpression(setAccessExpr.IndexExpr);
                (VariableAccessExpr setItemTemp, IPStmt setItemStore) =
                    SaveInTemporary(new SetAccessExpr(location, setExpr, setIdxExpr, setAccessExpr.Type));
                deps.AddRange(setDeps.Concat(setIdxDeps));
                deps.Add(setItemStore);
                return(setItemTemp, deps);

            case NamedTupleAccessExpr namedTupleAccessExpr:
                (IExprTerm ntSubExpr, List <IPStmt> ntSubDeps) = SimplifyExpression(namedTupleAccessExpr.SubExpr);
                (VariableAccessExpr ntTemp, IPStmt ntStore)    =
                    SaveInTemporary(new NamedTupleAccessExpr(location, ntSubExpr, namedTupleAccessExpr.Entry));
                deps.AddRange(ntSubDeps);
                deps.Add(ntStore);
                return(ntTemp, deps);

            case NamedTupleExpr namedTupleExpr:
                (IReadOnlyList <IVariableRef> args, List <IPStmt> argDeps) = SimplifyArgPack(namedTupleExpr.TupleFields);
                deps.AddRange(argDeps);

                (VariableAccessExpr ntVal, IPStmt ntValStore) =
                    SaveInTemporary(new NamedTupleExpr(location, args, namedTupleExpr.Type));
                deps.Add(ntValStore);
                return(ntVal, deps);

            case NondetExpr nondetExpr:
                (VariableAccessExpr ndTemp, IPStmt ndStore) = SaveInTemporary(nondetExpr);
                deps.Add(ndStore);
                return(ndTemp, deps);

            case SeqAccessExpr seqAccessExpr:
                (IExprTerm seqExpr, List <IPStmt> seqDeps)        = SimplifyExpression(seqAccessExpr.SeqExpr);
                (IExprTerm seqIdx, List <IPStmt> seqIdxDeps)      = SimplifyExpression(seqAccessExpr.IndexExpr);
                (VariableAccessExpr seqElem, IPStmt seqElemStore) =
                    SaveInTemporary(new SeqAccessExpr(location, seqExpr, seqIdx, seqAccessExpr.Type));
                deps.AddRange(seqDeps.Concat(seqIdxDeps));
                deps.Add(seqElemStore);
                return(seqElem, deps);

            case SizeofExpr sizeofExpr:
                (IExprTerm sizeExpr, List <IPStmt> sizeDeps)    = SimplifyExpression(sizeofExpr.Expr);
                (VariableAccessExpr sizeTemp, IPStmt sizeStore) = SaveInTemporary(new SizeofExpr(location, sizeExpr));
                deps.AddRange(sizeDeps);
                deps.Add(sizeStore);
                return(sizeTemp, deps);

            case TupleAccessExpr tupleAccessExpr:
                (IExprTerm tupItemExpr, List <IPStmt> tupAccessDeps)  = SimplifyExpression(tupleAccessExpr.SubExpr);
                (VariableAccessExpr tupItemTemp, IPStmt tupItemStore) =
                    SaveInTemporary(new TupleAccessExpr(location,
                                                        tupItemExpr,
                                                        tupleAccessExpr.FieldNo,
                                                        tupleAccessExpr.Type));
                deps.AddRange(tupAccessDeps);
                deps.Add(tupItemStore);
                return(tupItemTemp, deps);

            case UnaryOpExpr unaryOpExpr:
                (IExprTerm unExpr, List <IPStmt> unDeps)    = SimplifyExpression(unaryOpExpr.SubExpr);
                (VariableAccessExpr unTemp, IPStmt unStore) = SaveInTemporary(new UnaryOpExpr(location, unaryOpExpr.Operation, unExpr));
                deps.AddRange(unDeps);
                deps.Add(unStore);
                return(unTemp, deps);

            case UnnamedTupleExpr unnamedTupleExpr:
                (IReadOnlyList <IVariableRef> tupFields, List <IPStmt> tupFieldDeps) = SimplifyArgPack(unnamedTupleExpr.TupleFields);
                deps.AddRange(tupFieldDeps);
                (VariableAccessExpr tupVal, IPStmt tupStore) = SaveInTemporary(new UnnamedTupleExpr(location, tupFields));
                deps.Add(tupStore);
                return(tupVal, deps);

            case ValuesExpr valuesExpr:
                (IExprTerm valuesColl, List <IPStmt> valuesDeps)    = SimplifyExpression(valuesExpr.Expr);
                (VariableAccessExpr valuesTemp, IPStmt valuesStore) =
                    SaveInTemporary(new ValuesExpr(location, valuesColl, valuesExpr.Type));
                deps.AddRange(valuesDeps);
                deps.Add(valuesStore);
                return(valuesTemp, deps);

            case StringExpr stringExpr:
                (IPExpr[] stringArgs, List <IPStmt> stringArgsDeps) = SimplifyFunArgs(stringExpr.Args);
                (VariableAccessExpr stringTemp, IPStmt stringStore) = SaveInTemporary(new StringExpr(location, stringExpr.BaseString, stringArgs.ToList()));
                deps.AddRange(stringArgsDeps);
                deps.Add(stringStore);
                return(stringTemp, deps);

            default:
                throw new ArgumentOutOfRangeException(nameof(expr));
            }
#pragma warning restore CCN0002 // Non exhaustive patterns in switch block
        }
예제 #14
0
        public StringTemplateParseResultEventArgs(ITextSnapshot snapshot, IList <ParseErrorEventArgs> errors, TimeSpan elapsedTime, IList <IToken> tokens, IRuleReturnScope result, IList <Antlr4.Runtime.IToken> tokens4, Antlr4.Runtime.ParserRuleContext result4)
            : base(snapshot, errors, elapsedTime, tokens, result)
        {
            Tokens4 = tokens as ReadOnlyCollection <Antlr4.Runtime.IToken>;
            if (Tokens == null)
            {
                Tokens4 = new ReadOnlyCollection <Antlr4.Runtime.IToken>(tokens4 ?? new Antlr4.Runtime.IToken[0]);
            }

            Result4 = result4;
        }
        public void HandleParensExpression(
            Antlr4.Runtime.ParserRuleContext context,
            bool isCallStatement,
            SBExpressionData left,
            Stack <SBExpressionData> argumentStack,
            SBExpressionData assignmentTarget,
            PropertyBlock propertyBlock)
        {
            var leftType = left.DataType?.Type;
            List <SBExpressionData> arguments = new List <SBExpressionData>();

            if (argumentStack.Count > 0)
            {
                while (argumentStack.Count > 0)
                {
                    arguments.Insert(0, this.ResolveIfIdentifier(argumentStack.Pop(), true));                             // First pushed first in list.
                }
            }

            var           matchingMethods = new List <Tuple <MethodInfo, int> >();
            var           suggestedAssignmentsForMatchingMethods = new List <List <SBExpressionData> >();
            Expression    instance       = null;
            var           callType       = ParansExpressionType.MethodCall;
            var           firstParIsThis = false; // Whether the first parameter of procedure (or method?) is a 'this' reference.
            TypeReference returnType     = null;

            #region Identify call type and list methods with matching name

            IEnumerable <MethodInfo> methods = null;
            // Find the list of methods matching the given arguments.
            switch (left.ReferencedType)
            {
            case SBExpressionType.Namespace:
            case SBExpressionType.Constant:
            case SBExpressionType.GlobalVariableReference:
            case SBExpressionType.TypeReference:
                m_errors.SymanticError(context.Start.Line, -1, false, $"\"{left.ToString()}\" is not a method, procedure or delegate.");
                return;

            case SBExpressionType.Identifier:
                m_errors.SymanticError(left.Token.Line, left.Token.Column, false, $"\"{left.ToString()}\" is unresolved.");
                return;

            case SBExpressionType.Expression:
            case SBExpressionType.PropertyReference:
            case SBExpressionType.LocalVariableReference:
                if (left.DataType.Type.IsDelegate())
                {
                    methods = new MethodInfo[] { leftType.GetMethod("Invoke") };
                }
                else if (typeof(IProcedureReference).IsAssignableFrom(leftType))
                {
                    if (leftType.IsGenericType && leftType.GetGenericTypeDefinition() == typeof(IProcedureReference <>))
                    {
                        var m = leftType.GetGenericArguments()[0].GetMethod("Invoke");
                        System.Diagnostics.Debug.Assert(m != null);
                        methods  = new MethodInfo[] { m };
                        callType = isCallStatement ? ParansExpressionType.ProcedureCall : ParansExpressionType.FunctionCall;
                        if (left.DataType.HaveProcedureReference)
                        {
                            var proc = left.DataType.DynamicType as FileProcedure;
                            firstParIsThis = proc.IsFirstParameterThisReference;
                            instance       = left.InstanceCode;
                        }
                    }
                    else
                    {
                        // Make rest of this method treat this as a method call rather than a procedure call.
                        instance = left.ExpressionCode;
                        callType = isCallStatement ? ParansExpressionType.DynamicProcedureCall : ParansExpressionType.DynamicFunctionCall;
                    }
                }
                else
                {
                    m_errors.SymanticError(context.Start.Line, -1, false, $"\"{left.ToString()}\" is not a procedure reference or a delegate.");
                    return;
                }
                break;

            case SBExpressionType.MethodReference:
                instance = left.ExpressionCode;
                methods  = (IEnumerable <MethodInfo>)left.Value;
                break;

            case SBExpressionType.ProcedureReference:
            {
                callType = isCallStatement ? ParansExpressionType.ProcedureCall : ParansExpressionType.FunctionCall;
                // Note: never anonymous procedure here.
                var procedure = (left.Value as IProcedureReference).ProcedureData;
                if (!isCallStatement && (procedure.Flags & ProcedureFlags.IsFunction) == ProcedureFlags.None)
                {
                    m_errors.SymanticError(context.Start.Line, -1, false, "Only procedures marked as 'function' can be called from expressions.");
                }
                if (procedure.DataType != null && procedure.DataType.Type != typeof(UnresolvedProcedureType))
                {
                    var m = procedure.DataType.Type.GetGenericArguments()[0].GetMethod("Invoke");
                    System.Diagnostics.Debug.Assert(m != null);
                    methods = new MethodInfo[] { m };
                }
                else
                {
                    m_errors.SymanticError(context.Start.Line, -1, false, "Unresolved signature for procedure.");
                }
            }
            break;

            //case SBExpressionType.DynamicObjectProperty:
            //case SBExpressionType.DynamicObjectPropertyReadonly:
            //    m_errors.SymanticError(context.Start.Line, context.Start.Column, false, "Left side is a dynamic property, not a dynamic procedure.");
            //    return;

            //case SBExpressionType.DynamicObjectProcedure:
            //    {
            //        callType = ParansExpressionType.DynamicObjectMethodCall;
            //    }
            //    break;

            case SBExpressionType.DynamicObjectMember:
            case SBExpressionType.DynamicAsyncObjectMember:
            {
                instance = left.InstanceCode;
                var name = left.Value as string;
                SBExpressionData sequencialFirstArguments = null, namedArguments = null, sequencialLastArguments = null;
                if (this.CreateArgumentsForDynamicCall(
                        arguments,
                        ref sequencialFirstArguments,
                        ref namedArguments,
                        ref sequencialLastArguments))
                {
                    MethodInfo dynamicExecutor = (left.ReferencedType == SBExpressionType.DynamicObjectMember) ? s_ExecuteDynamicObjectMethod : s_ExecuteDynamicAsyncObjectMethod;
                    Expression dynamicCall     = Expression.Call(
                        dynamicExecutor,
                        m_currentProcedure?.ContextReferenceInternal,
                        Expression.Convert(instance, (left.ReferencedType == SBExpressionType.DynamicObjectMember) ? typeof(IDynamicStepBroObject) : typeof(IDynamicAsyncStepBroObject)),
                        Expression.Constant(name),
                        sequencialFirstArguments.ExpressionCode);

                    returnType = (left.ReferencedType == SBExpressionType.DynamicObjectMember) ? TypeReference.TypeObject : TypeReference.TypeAsyncObject;
                    if (m_callAssignmentAwait)
                    {
                        dynamicCall           = this.MakeAwaitOperation(dynamicCall, context, true, m_callAssignmentTarget?.DataType.Type);
                        returnType            = (TypeReference)dynamicCall.Type; //new TypeReference(dynamicCall.Type);
                        m_callAssignmentAwait = false;
                    }

                    if (isCallStatement)
                    {
                        m_scopeStack.Peek().AddStatementCode(dynamicCall);
                    }
                    else
                    {
                        m_expressionData.Push(
                            new SBExpressionData(
                                HomeType.Immediate,
                                SBExpressionType.Expression,
                                returnType,
                                dynamicCall,
                                automaticTypeConvert: true));
                    }
                }
                else
                {
                    throw new NotImplementedException();
                }
                return;             // All done for now.
            }

            case SBExpressionType.OperationError:
            case SBExpressionType.UnsupportedOperation:
            case SBExpressionType.UnknownIdentifier:
                return;

            default:
                m_errors.InternalError(context.Start.Line, -1, $"Unhandled expression type: \"{left.ReferencedType}\".");
                break;
            }

            #endregion

            MethodInfo selectedMethod = null;
            List <SBExpressionData> methodArguments = null;

            #region Dynamic Procedure Call

            if (callType == ParansExpressionType.DynamicProcedureCall)
            {
                selectedMethod = s_DynamicProcedureCall;

                SBExpressionData sequencialFirstArguments = null, namedArguments = null, sequencialLastArguments = null;
                if (this.CreateArgumentsForDynamicCall(
                        arguments,
                        ref sequencialFirstArguments,
                        ref namedArguments,
                        ref sequencialLastArguments))
                {
                    //this IProcedureReference procedure,
                    //IScriptCallContext context,
                    //PropertyBlock propertyBlock,
                    //object[] sequencialFirstArguments,
                    //ArgumentList namedArguments,
                    //object[] sequencialLastArguments

                    m_scopeStack.Peek().AddStatementCode(
                        Expression.Call(
                            s_DynamicProcedureCall,
                            instance,
                            m_currentProcedure?.ContextReferenceInternal,
                            Expression.Constant(null, typeof(PropertyBlock)),
                            sequencialFirstArguments.ExpressionCode,
                            namedArguments.ExpressionCode,
                            sequencialLastArguments.ExpressionCode));
                }
                return;     // All done.
            }
            else if (callType == ParansExpressionType.DynamicFunctionCall)
            {
                selectedMethod = s_DynamicFunctionCall;
                throw new NotImplementedException("DYNAMIC FUNCTION CALL");
            }

            #endregion

            // Fall through: Not a dynamic call

            if (methods == null)
            {
                throw new Exception("No methods identified; should be handled and reported earlier.");
            }

            #region Find matching method and setup arguments

            foreach (var m in methods)
            {
                var constructedMethod = m;
                var extensionInstance = m.IsExtension() ? instance : null;
                List <SBExpressionData> suggestedAssignments = new List <SBExpressionData>();
                int score = this.CheckMethodArguments(
                    ref constructedMethod,
                    callType == ParansExpressionType.ProcedureCall || callType == ParansExpressionType.FunctionCall,
                    firstParIsThis,
                    instance,
                    m_currentProcedure?.ContextReferenceInternal,
                    extensionInstance,
                    arguments,
                    suggestedAssignments);
                if (score > 0)
                {
                    matchingMethods.Add(new Tuple <MethodInfo, int>(constructedMethod, score));
                    suggestedAssignmentsForMatchingMethods.Add(suggestedAssignments);
                }
            }

            int bestMatch = -1;
            if (matchingMethods.Count == 1)
            {
                bestMatch = 0;
            }
            else if (matchingMethods.Count > 1)
            {
                int max      = matchingMethods[0].Item2;
                int maxAt    = 0;
                int numAtMax = 1;
                for (var i = 1; i < matchingMethods.Count; i++)
                {
                    if (matchingMethods[i].Item2 > max)
                    {
                        max      = matchingMethods[i].Item2;
                        maxAt    = i;
                        numAtMax = 1;
                    }
                    else if (matchingMethods[i].Item2 == max)
                    {
                        numAtMax++;
                    }
                }
                if (numAtMax == 1)
                {
                    bestMatch = maxAt;
                }
            }

            if (bestMatch >= 0)
            {
                selectedMethod = matchingMethods[bestMatch].Item1;
                var suggestedAssignments = suggestedAssignmentsForMatchingMethods[bestMatch];

                returnType = new TypeReference(selectedMethod.ReturnType);
                if (selectedMethod.IsExtension())
                {
                    instance = null;
                }
                methodArguments = new List <SBExpressionData>();
                int i = 0;
                foreach (var p in selectedMethod.GetParameters())
                {
                    SBExpressionData argument = suggestedAssignments[i];
                    if (argument == null || argument.ExpressionCode == null)
                    {
                        throw new NotImplementedException();    // Implicit argument must be found and added.
                    }
                    else
                    {
                        methodArguments.Add(argument);
                    }
                    i++;
                }
            }
            else
            {
                // Handle none or more than one alternative
                throw new NotImplementedException();
            }

            #endregion

            #region Call the target procedure or method

            if (callType == ParansExpressionType.ProcedureCall || callType == ParansExpressionType.FunctionCall)
            {
                Expression procedureReferenceExp  = null;
                Type       delegateType           = null;
                Type       procedureReferenceType = null;
                Expression theDelegate            = null;

                switch (left.ReferencedType)
                {
                case SBExpressionType.Expression:
                case SBExpressionType.PropertyReference:
                case SBExpressionType.LocalVariableReference:
                {
                    procedureReferenceExp = left.ExpressionCode;

                    if (leftType.IsGenericType && leftType.GetGenericTypeDefinition() == typeof(IProcedureReference <>))
                    {
                        delegateType           = leftType.GetGenericArguments()[0];
                        procedureReferenceType = leftType;         //typeof(IProcedureReference<>).MakeGenericType(delegateType);
                    }
                    else
                    {
                        if (leftType == typeof(IProcedureReference))
                        {
                            // Anonymous procedure type; do a dynamic call !!!
                            throw new NotImplementedException("Dynamic call needs to be implemented.");
                        }
                        else
                        {
                            throw new ArgumentException("Not a procedure reference");
                        }
                    }
                }
                break;

                case SBExpressionType.ProcedureReference:
                {
                    var procRef   = left.Value as IProcedureReference;
                    var procedure = procRef.ProcedureData as FileProcedure;
                    returnType             = procedure.ReturnType;
                    delegateType           = procedure.DelegateType;
                    procedureReferenceType = procedure.ProcedureReferenceType;

                    if (delegateType != null)
                    {
                        var getStaticProcedureReferenceTyped = s_GetProcedureTyped.MakeGenericMethod(delegateType);
                        int fileID = Object.ReferenceEquals(procedure.ParentFile, m_file) ? -1 : ((ScriptFile)procedure.ParentFile).UniqueID;

                        procedureReferenceExp = Expression.Call(
                            getStaticProcedureReferenceTyped,
                            m_currentProcedure.ContextReferenceInternal,
                            Expression.Constant(fileID),
                            Expression.Constant(procedure.UniqueID));
                    }
                    else
                    {
                        int fileID = Object.ReferenceEquals(procedure.ParentFile, m_file) ? -1 : ((ScriptFile)procedure.ParentFile).UniqueID;

                        procedureReferenceExp = Expression.Call(
                            s_GetProcedure,
                            m_currentProcedure.ContextReferenceInternal,
                            Expression.Constant(fileID),
                            Expression.Constant(procedure.UniqueID));
                    }
                }
                break;

                default:
                    break;
                }

                theDelegate = Expression.Property(procedureReferenceExp, "RuntimeProcedure");

                if (isCallStatement)
                {
                    // C# version of the generated code:
                    // var callcontext = context.EnterNewScriptContext(MySecond, ContextLogOption.Normal).Disposer())
                    // try { MySecondProcedure(callcontext.Value, v1, v2); }
                    // finally { callcontext.Dispose(); }

                    var procRefVar = Expression.Variable(procedureReferenceType, "procRef");
                    var subCallContextContainer = Expression.Variable(typeof(InternalDisposer <IScriptCallContext>), "subCallContextContainer");
                    var subCallContext          = Expression.Property(subCallContextContainer, "Value");
                    // Replace the callContext argument with new context reference.
                    methodArguments[0] = new SBExpressionData(subCallContext);
                    var assignProcRefVar = Expression.Assign(procRefVar, procedureReferenceExp);

                    var createSubContext = Expression.New(
                        typeof(InternalDisposer <IScriptCallContext>).GetConstructor(new Type[] { typeof(IScriptCallContext) }),
                        Expression.Call(
                            m_currentProcedure.ContextReferenceInternal,
                            typeof(IScriptCallContext).GetMethod(nameof(IScriptCallContext.EnterNewScriptContext), new Type[] { typeof(IProcedureReference), typeof(ContextLogOption), typeof(bool) }),
                            procRefVar,
                            Expression.Constant(ContextLogOption.Normal),
                            Expression.Constant(false)));

                    var invokeMethod = delegateType.GetMethod("Invoke");

                    Expression callProcedure = Expression.Call(
                        Expression.Property(
                            procRefVar,
                            "RuntimeProcedure"),
                        invokeMethod,
                        methodArguments.Select(a => a.ExpressionCode).ToArray());
                    if (m_callAssignmentAwait)
                    {
                        callProcedure = this.MakeAwaitOperation(callProcedure, context, true, m_callAssignmentTarget?.DataType.Type);
                        returnType    = new TypeReference(callProcedure.Type);
                    }
                    if (m_callAssignmentTarget != null)
                    {
                        callProcedure = Expression.Assign(m_callAssignmentTarget.ExpressionCode, callProcedure);
                    }

                    var disposeSubContext = Expression.Call(
                        subCallContextContainer,
                        typeof(InternalDisposer <IScriptCallContext>).GetMethod("Dispose"));

                    var completeProcedureCall = Expression.Block(
                        new ParameterExpression[] { procRefVar, subCallContextContainer },
                        Expression.TryCatchFinally(
                            Expression.Block(
                                assignProcRefVar,
                                Expression.Assign(subCallContextContainer, createSubContext),
                                callProcedure,
                                Expression.Condition(
                                    Expression.Call(s_PostProcedureCallResultHandling, m_currentProcedure.ContextReferenceInternal, subCallContext),
                                    Expression.Return(m_currentProcedure.ReturnLabel, Expression.Default(m_currentProcedure.ReturnType.Type)),  // When told to exit the procedure now.
                                    Expression.Empty())
                                ),
                            disposeSubContext,
                            Expression.Catch(
                                typeof(Exception),
                                Expression.Rethrow())
                            ));

                    m_scopeStack.Peek().AddStatementCode(completeProcedureCall);
                }
                else
                {
                    var subCallContext = Expression.New(
                        typeof(FunctionCallContextWrapper).GetConstructor(
                            new Type[] { typeof(IScriptCallContext),
                                         typeof(int),
                                         typeof(int) }),
                        m_currentProcedure.ContextReferenceInternal,
                        Expression.Constant(context.Start.Line),
                        Expression.Constant(-1) /* TODO: get line and column from the 'left' parameter */);

                    methodArguments[0] = new SBExpressionData(subCallContext);

                    m_expressionData.Push(
                        new SBExpressionData(
                            HomeType.Immediate,
                            SBExpressionType.Expression,
                            returnType,
                            Expression.Call(
                                theDelegate,
                                delegateType.GetMethod("Invoke"),
                                methodArguments.Select(a => a.ExpressionCode).ToArray()),
                            null));
                }
            }
            else    // Not a procedure or function; a method.
            {
                switch (left.ReferencedType)
                {
                case SBExpressionType.Expression:
                case SBExpressionType.PropertyReference:
                case SBExpressionType.LocalVariableReference:
                    if (leftType.IsDelegate())
                    {
                        m_expressionData.Push(
                            new SBExpressionData(
                                HomeType.Immediate,
                                SBExpressionType.Expression,
                                (TypeReference)(leftType.GetMethod("Invoke").ReturnType),
                                Expression.Invoke(left.ExpressionCode, methodArguments.Select(a => a.ExpressionCode).ToArray()),
                                null));
                    }
                    else
                    {
                        throw new NotImplementedException("Can we end up here?");
                    }
                    break;

                case SBExpressionType.MethodReference:
                {
                    Expression callMethod = Expression.Call(
                        instance,
                        selectedMethod,
                        methodArguments.Select(a => a.ExpressionCode).ToArray());
                    if (isCallStatement)
                    {
                        if (m_callAssignmentAwait)
                        {
                            callMethod = this.MakeAwaitOperation(callMethod, context, true, m_callAssignmentTarget?.DataType.Type);
                            returnType = new TypeReference(callMethod.Type);
                        }
                        if (m_callAssignmentTarget != null)
                        {
                            callMethod = Expression.Assign(m_callAssignmentTarget.ExpressionCode, callMethod);
                        }
                        m_scopeStack.Peek().AddStatementCode(callMethod);
                    }
                    else
                    {
                        m_expressionData.Push(
                            new SBExpressionData(
                                HomeType.Immediate,
                                SBExpressionType.Expression,
                                returnType,
                                callMethod,
                                null));
                    }
                }
                break;

                default:
                    break;
                }
            }

            #endregion
        }
예제 #16
0
 public VariableNotFountException(string variable, Antlr4.Runtime.ParserRuleContext context)
 {
     this._context   = context;
     this._variable  = variable;
     this._errorInfo = new ErrorInfo(context.Start.Line, context.Start.Column, "列变量" + _variable + " 没有定义");
 }
예제 #17
0
 internal TypeException(Antlr4.Runtime.ParserRuleContext context, string message, string fileName) : base(context, message, fileName)
 {
 }
 public virtual void ExitEveryRule(ParserRuleContext context)
 {
 }
예제 #19
0
 public void ExitEveryRule(Antlr4.Runtime.ParserRuleContext ctx)
 {
 }