static bool TypeMatches(FunctionDeclaration decl, List <TypeSpec> ts, List <SwiftType> st, TypeMapper typeMap)
 {
     if (ts == null || st == null)
     {
         return(false);
     }
     if (ts.Count != st.Count)
     {
         return(false);
     }
     if (ts.Count == 1)
     {
         // Thanks swift, you're the best...
         if (IsVoid(ts [0]) && st [0].IsEmptyTuple)
         {
             return(true);
         }
     }
     for (int i = 0; i < ts.Count; i++)
     {
         if (!TypeMatches(decl, ts [i], st [i], typeMap))
         {
             return(false);
         }
     }
     return(true);
 }
        static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftBuiltInType st, TypeMapper typeMap)
        {
            if (st == null)
            {
                return(false);
            }
            if (ts.IsInOut != st.IsReference)
            {
                return(false);
            }
            switch (st.BuiltInType)
            {
            case CoreBuiltInType.Bool:
                return(ts.Name == "Swift.Bool");

            case CoreBuiltInType.Double:
                return(ts.Name == "Swift.Double");

            case CoreBuiltInType.Float:
                return(ts.Name == "Swift.Float");

            case CoreBuiltInType.Int:
                return(ts.Name == "Swift.Int");

            case CoreBuiltInType.UInt:
                return(ts.Name == "Swift.UInt");

            default:
                throw new ArgumentOutOfRangeException("st");
            }
        }
        static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftExistentialMetaType st, TypeMapper typeMap)
        {
            if (st == null)
            {
                return(false);
            }
            if (st.Protocol.Protocols.Count != 1)
            {
                return(false);
            }
            var protoClass = st.Protocol.Protocols [0];

            if (ts.Name == "Any.Type")
            {
                return(protoClass.ClassName.ToFullyQualifiedName() == "Swift.Any");
            }
            if (ts.Name == protoClass.ClassName.ToFullyQualifiedName())
            {
                return(true);
            }
            if (ts.Name.EndsWith(".Type", StringComparison.Ordinal))
            {
                var maybeClassName = ts.Name.Substring(0, ts.Name.Length - ".Type".Length);
                return(maybeClassName == protoClass.ClassName.ToFullyQualifiedName());
            }
            return(false);
        }
Exemple #4
0
        void FindsProperty(string code, Func <ClassDeclaration, bool> classFinder,
                           Func <PropertyDeclaration, bool> propFinder)
        {
            CustomSwiftCompiler compiler = Utils.CompileSwift(code, moduleName: "CanFind");

            var               errors = new ErrorHandling();
            ModuleInventory   mi     = ModuleInventory.FromFile(Path.Combine(compiler.DirectoryPath, "libCanFind.dylib"), errors);
            ModuleDeclaration mod    = compiler.ReflectToModules(new string [] { compiler.DirectoryPath },
                                                                 new string [] { compiler.DirectoryPath }, null, "CanFind") [0];

            ClassDeclaration classDecl = mod.AllClasses.FirstOrDefault(classFinder);

            Assert.IsNotNull(classDecl, "null class");

            PropertyDeclaration propDecl = classDecl.Members.OfType <PropertyDeclaration> ().FirstOrDefault(propFinder);

            Assert.IsNotNull(propDecl, "null property");

            FunctionDeclaration getter = propDecl.GetGetter();

            Assert.IsNotNull(getter, "null getter");

            FunctionDeclaration setter = propDecl.GetSetter();

            Assert.IsNotNull(setter, "null setter");

            TLFunction tlgetter = XmlToTLFunctionMapper.ToTLFunction(getter, mi);

            Assert.IsNotNull(tlgetter, "null tlgetter");

            TLFunction tlsetter = XmlToTLFunctionMapper.ToTLFunction(setter, mi);

            Assert.IsNotNull(tlsetter, "null tlsetter");
        }
Exemple #5
0
 public override Statement VisitFunctionDeclaration(FunctionDeclaration fdecl){
   if (fdecl == null) return null;
   Method method = fdecl.Method = new Method();
   method.Name = fdecl.Name;
   this.scope.Members.Add(method);
   return fdecl;
 }
Exemple #6
0
        private IodineMethod CompileMethod(FunctionDeclaration funcDecl)
        {
            symbolTable.NextScope();
            IodineMethod methodBuilder = new IodineMethod(module, funcDecl.Name, funcDecl.InstanceMethod,
                                                          funcDecl.Parameters.Count,
                                                          symbolTable.CurrentScope.SymbolCount);
            FunctionCompiler compiler = new FunctionCompiler(symbolTable,
                                                             methodBuilder);

            methodBuilder.Variadic           = funcDecl.Variadic;
            methodBuilder.AcceptsKeywordArgs = funcDecl.AcceptsKeywordArgs;
            for (int i = 0; i < funcDecl.Parameters.Count; i++)
            {
                methodBuilder.Parameters [funcDecl.Parameters [i]] = symbolTable.GetSymbol
                                                                         (funcDecl.Parameters [i]).Index;
            }
            funcDecl.Children [0].Visit(compiler);
            AstNode lastNode = funcDecl.Children [0].LastOrDefault();

            if (lastNode != null)
            {
                methodBuilder.EmitInstruction(lastNode.Location, Opcode.LoadNull);
            }
            else
            {
                methodBuilder.EmitInstruction(funcDecl.Location, Opcode.LoadNull);
            }
            methodBuilder.FinalizeLabels();
            symbolTable.LeaveScope();
            return(methodBuilder);
        }
        bool ClosureTypesMatch(FunctionDeclaration protoFunc, ClosureTypeSpec protoType, FunctionDeclaration classFunc, ClosureTypeSpec classType)
        {
            var argsMatch = TypesMatch(protoFunc, protoType.Arguments, classFunc, classType.Arguments);
            var retsMatch = TypesMatch(protoFunc, protoType.ReturnType, classFunc, classType.ReturnType);

            return(argsMatch && retsMatch);
        }
Exemple #8
0
        internal FnPointer(Delegate d, CallingConvention convention)
        {
            var def  = d.Method.GetBaseDefinition();
            var pars = def.GetParameters();

            if (Constants.X64)
            {
                var dt  = DelegateCreator.NewDelegateType(def.ReturnType, pars.Select(p => p.ParameterType).ToArray());
                var fd  = Delegate.CreateDelegate(dt, d.Target, d.Method);
                var ptr = Marshal.GetFunctionPointerForDelegate(fd);
                Int64 = ptr.ToInt64();
            }
            else
            {
//				var ptr = Marshal.GetFunctionPointerForDelegate(d);
//				convention = CallingConvention.X86CDecl;
//				Int64 = ptr.ToInt64();

                // TODO: Need fixing!!!
                throw new NotImplementedException("Managed method cannot be called from machine code in X86 mode by now.");
            }

            var args = pars.Select(p => p.ParameterType.GetVariableType()).ToArray();
            var ret  = def.ReturnType.GetVariableType();

            FunctionDeclaration = new FunctionDeclaration(convention, args, ret);
        }
Exemple #9
0
        internal CallNode CreateCall(Operand op, FunctionDeclaration fn)
        {
            var node = new CallNode(op, fn);

            AddNode(node);
            return(node);
        }
Exemple #10
0
        private static void Process(this ExtendedId extendedId, bool isVariable = true)
        {
            var scope = extendedId.Scope;

            if (isVariable)
            {
                var declaration = scope.GlobalVariableSearch(extendedId.Name);
                if (declaration == null)
                {
                    throw new ScopeException($"Variable with name \"{extendedId.Name}\" does not exist");
                }
                extendedId.VariableDeclaration = declaration;
                if (!declaration.Initialized)
                {
                    throw new ScopeException(
                              $"Variable with name \"{extendedId.Name}\" was not initialized before accessing");
                }
                extendedId.ReturnType = declaration.ReturnType;
            }
            else
            {
                FunctionDeclaration declaration = scope.GlobalFunctionSearch(extendedId.Name);
                extendedId.ReturnType = declaration != null
                    ? declaration.ReturnType
                    : throw new ScopeException($"Variable with name \"{extendedId.Name}\" does not exist.");
            }
        }
Exemple #11
0
        internal FunctionSymbol(
            SourceFileSymbol declaringSourceFile,
            string name,
            FunctionDeclaration declaration)
            : base(declaringSourceFile, name, declaration)
        {
            var parameters = ImmutableArray <ParameterSymbol> .Empty;
            int paramCount = declaration.Parameters.Length;

            if (paramCount > 0)
            {
                var builder = ImmutableArray.CreateBuilder <ParameterSymbol>(paramCount);
                _parameterMap = new Dictionary <string, ParameterSymbol>();
                foreach (Parameter paramSyntax in declaration.Parameters)
                {
                    var parameter = new ParameterSymbol(this, paramSyntax.Name);
                    builder.Add(parameter);
                    _parameterMap.Add(parameter.Name, parameter);
                }

                parameters = builder.ToImmutable();
            }

            Parameters  = parameters;
            Declaration = declaration;
        }
        public override void VisitFunctionDeclaration(FunctionDeclaration node, AstPrinterContext context)
        {
            if (node.TypeSpecifier != null)
            {
                this.Visit(node.TypeSpecifier, context);
                context.Write(" ");
            }

            this.Visit(node.Name, context);
            context.Write("(");
            var i = 0;

            foreach (var p in node.Parameters)
            {
                this.Visit(p, context);
                i++;
                if (i < node.Parameters.Count)
                {
                    context.Write(", ");
                }
            }

            context.Write(")");
            if (node.Statement != null)
            {
                context.StartNewLine();
                this.Visit(node.Statement, context);
            }
            else
            {
                context.Write(";");
            }
        }
 public static void CheckName(this FunctionDeclaration functionDeclaration, Scope scopeToCheck)
 {
     if (scopeToCheck.ContainsFunction(functionDeclaration.Name))
     {
         throw new ScopeException($"Function with name: \"{functionDeclaration.Name}\" already exists");
     }
 }
 protected override void VisitFunctionDeclaration(FunctionDeclaration functionDeclaration)
 {
     // name, params skipped
     BeginNameScope(functionDeclaration.Params);
     Visit(functionDeclaration.Body);
     EndNameScope();
 }
 private void Check(CodeElement e, SymbolTable table, FunctionCall call, FunctionDeclaration definition)
 {
     var parameters = definition.Profile.Parameters;
     if (call.InputParameters.Count > parameters.Count) {
     var m = System.String.Format("Function {0} only takes {1} parameters", definition.Name, parameters.Count);
     DiagnosticUtils.AddError(e, m);
     }
     for (int c = 0; c < parameters.Count; c++) {
     var expected = parameters[c];
     if (c < call.InputParameters.Count) {
         var actual = call.InputParameters[c];
         if (actual.IsLiteral) continue;
         var found = table.GetVariable(new URI(actual.Value));
         if (found.Count < 1) DiagnosticUtils.AddError(e, "Parameter "+actual.Value+" is not referenced");
         if (found.Count > 1) DiagnosticUtils.AddError(e, "Ambiguous reference to parameter "+actual.Value);
         if (found.Count!= 1) continue;
         var type = found[0] as Typed;
         // type check. please note:
         // 1- if only one of [actual|expected] types is null, overriden DataType.!= operator will detect it
         // 2- if both are null, we WANT it to break: in TypeCobol EVERYTHING should be typed,
         //    and things we cannot know their type as typed as DataType.Unknown (which is a non-null valid type).
         if (type == null || type.DataType != expected.DataType) {
             var m = System.String.Format("Function {0} expected parameter {1} of type {2} (actual: {3})", definition.Name, c+1, expected.DataType, type.DataType);
             DiagnosticUtils.AddError(e, m);
         }
         if (type != null && type.Length > expected.Length) {
             var m = System.String.Format("Function {0} expected parameter {1} of max length {2} (actual: {3})", definition.Name, c+1, expected.Length, type.Length);
             DiagnosticUtils.AddError(e, m);
         }
     } else {
         var m = System.String.Format("Function {0} is missing parameter {1} of type {2}", definition.Name, c+1, expected.DataType);
         DiagnosticUtils.AddError(e, m);
     }
     }
 }
Exemple #16
0
        /// <summary>
        /// Alles ok met de functiedeclaratie?
        /// Nog niks op de stack...?
        /// Op de stack zetten
        /// </summary>
        /// <param name="l"></param>
        public void Visit(FunctionDeclaration l)
        {
            if (CheckGeneric(l))
            {
                return;
            }

            // We moeten een variabele hebben en een type, niet perse een initialisatie
            if (l.ResultType == String.Empty)
            {
                _errors.Add(new TypenameExpectedException(l.SourceCodeContext));
                return;
            }
            if (l.Name == String.Empty)
            {
                _errors.Add(new IdentifierExpectedException(l.SourceCodeContext));
                return;
            }
            if (l.ParListFound)
            {
                foreach (FunctionParameterDeclaration fpd in l.ParList)
                {
                    if (fpd.ParType == String.Empty)
                    {
                        _errors.Add(new TypenameExpectedException(l.SourceCodeContext));
                        continue;
                    }
                    if (fpd.ParName == String.Empty)
                    {
                        _errors.Add(new IdentifierExpectedException(l.SourceCodeContext));
                    }
                }
            }
            _tomatch.Add(l);
        }
Exemple #17
0
        public void TestFunctionRedeclaration()
        {
            var f = new FunctionDeclaration(
                new Range(new StringLocation(0), new StringLocation(1)),
                "f",
                UnitType.Instance,
                new List <VariableDeclaration>(),
                new InstructionBlock(new Range(new StringLocation(0), new StringLocation(1)), new List <Expression>()),
                false);

            var f2 = new FunctionDeclaration(
                new Range(new StringLocation(0), new StringLocation(1)),
                "f",
                UnitType.Instance,
                new List <VariableDeclaration>(),
                new InstructionBlock(new Range(new StringLocation(0), new StringLocation(1)), new List <Expression>()),
                false);

            var diagnosticsMock = new Moq.Mock <IDiagnostics>();
            var diagnostics     = diagnosticsMock.Object;

            var resolver  = new NameResolver();
            var functions = new List <FunctionDeclaration> {
                f, f2
            };
            var root = new Program(
                new Range(new StringLocation(0), new StringLocation(1)),
                new List <StructDeclaration>(),
                functions);

            Assert.ThrowsException <NameResolverException>(() => this.nameResolver.Run(root, diagnostics));
            MockDiagnostics.Verify(diagnosticsMock, NameResolver.MultipleDeclarationsDiagnostic);
        }
        public static TLFunction ToTLFunction(FunctionDeclaration decl, ModuleContents contents, TypeMapper typeMap)
        {
            string nameToSearch = GetNameToSearchOn(decl);
            var    funcs        = FuncsToSearch(contents, decl, nameToSearch);

            return(MatchFunctionDecl(decl, funcs, typeMap));
        }
Exemple #19
0
        public static void OnNode(FunctionDeclaration functionDeclaration)
        {
            var header = functionDeclaration?.CodeElement as FunctionDeclarationHeader;

            if (header == null)
            {
                return;                 //not my job
            }
            var filesection = functionDeclaration.Get <FileSection>("file");

            if (filesection != null) // TCRFUN_DECLARATION_NO_FILE_SECTION
            {
                DiagnosticUtils.AddError(filesection,
                                         "Illegal FILE SECTION in function \"" + header.Name + "\" declaration");
            }

            CheckNoGlobalOrExternal(functionDeclaration.Get <DataDivision>("data-division"));
            CheckNoLinkageItemIsAParameter(functionDeclaration.Get <LinkageSection>("linkage"), header.Profile);

            CheckParameters(header.Profile, functionDeclaration);
            CheckNoPerform(functionDeclaration.SymbolTable.EnclosingScope, functionDeclaration);

            var headerNameURI = new URI(header.Name);
            var functions     = functionDeclaration.SymbolTable.GetFunction(headerNameURI, functionDeclaration.Profile);

            if (functions.Count > 1)
            {
                DiagnosticUtils.AddError(functionDeclaration,
                                         "A function \"" + headerNameURI.Head + "\" with the same profile already exists in namespace \"" +
                                         headerNameURI.Tail + "\".");
            }
        }
        static bool TypeMatches(FunctionDeclaration decl, ClosureTypeSpec cs, SwiftType st, TypeMapper typeMap)
        {
            SwiftBaseFunctionType bft = st as SwiftBaseFunctionType;

            return(TypeMatches(decl, cs.Arguments, bft.Parameters, typeMap) &&
                   TypeMatches(decl, cs.ReturnType, bft.ReturnType, typeMap));
        }
Exemple #21
0
        public void FindsPropertyGetterAndSetterFuncs()
        {
            string code = "public class Bar { public var x:Int = 0; }";

            CustomSwiftCompiler compiler = Utils.CompileSwift(code, moduleName: "CanFind");

            ModuleDeclaration mod = compiler.ReflectToModules(new string [] { compiler.DirectoryPath },
                                                              new string [] { compiler.DirectoryPath }, null, "CanFind") [0];

            ClassDeclaration classDecl = mod.AllClasses.FirstOrDefault(cl => cl.Name == "Bar");

            Assert.IsNotNull(classDecl);

            PropertyDeclaration propDecl = classDecl.Members.OfType <PropertyDeclaration> ().FirstOrDefault(p => p.Name == "x");

            Assert.IsNotNull(propDecl);

            FunctionDeclaration getter = propDecl.GetGetter();

            Assert.IsNotNull(getter);

            FunctionDeclaration setter = propDecl.GetSetter();

            Assert.IsNotNull(setter);
        }
        static bool TypeMatches(FunctionDeclaration decl, NamedTypeSpec ts, SwiftType st, TypeMapper typeMap)
        {
            switch (st.Type)
            {
            case CoreCompoundType.Scalar:
                return(TypeMatches(decl, ts, st as SwiftBuiltInType, typeMap));

            case CoreCompoundType.Class:
                return(TypeMatches(decl, ts, st as SwiftClassType, typeMap));

            case CoreCompoundType.MetaClass:
                if (st is SwiftExistentialMetaType exist)
                {
                    return(TypeMatches(decl, ts, exist, typeMap));
                }
                else
                {
                    return(TypeMatches(decl, ts, st as SwiftMetaClassType, typeMap));
                }

            case CoreCompoundType.BoundGeneric:
                return(TypeMatches(decl, ts, st as SwiftBoundGenericType, typeMap));

            case CoreCompoundType.ProtocolList:
                return(TypeMatches(decl, ts, st as SwiftProtocolListType, typeMap));

            case CoreCompoundType.GenericReference:
                return(TypeMatches(decl, ts, st as SwiftGenericArgReferenceType, typeMap));

            case CoreCompoundType.Struct:
            default:
                return(false);
            }
        }
Exemple #23
0
 public void visit(FunctionDeclaration that)
 {
     that.Type.visit(this);
     Console.Write(" {0}(", that.Name);
     foreach (ParameterDeclaration parameter in that.Parameters)
     {
         parameter.visit(this);
         if (parameter != that.Parameters[that.Parameters.Length - 1])
         {
             Console.Write(", ");
         }
     }
     Console.WriteLine(")");
     Console.WriteLine("{");
     Console.Write("return ");
     if (that.Body != null)
     {
         that.Body.visit(this);
     }
     else
     {
         Console.Write("null");
     }
     Console.WriteLine(";");
     Console.WriteLine("}");
 }
        bool TypesMatch(FunctionDeclaration protoFunc, TypeSpec protoType, FunctionDeclaration classFunc, TypeSpec classType)
        {
            if (protoType.Kind != classType.Kind)
            {
                return(false);
            }
            if (protoType.Equals(classType))
            {
                return(true);
            }

            switch (protoType.Kind)
            {
            case TypeSpecKind.Closure:
                return(ClosureTypesMatch(protoFunc, protoType as ClosureTypeSpec, classFunc, classType as ClosureTypeSpec));

            case TypeSpecKind.Named:
                return(NamedTypesMatch(protoFunc, protoType as NamedTypeSpec, classFunc, classType as NamedTypeSpec));

            case TypeSpecKind.ProtocolList:
                return(ProtoListTypesMatch(protoFunc, protoType as ProtocolListTypeSpec, classFunc, classType as ProtocolListTypeSpec));

            case TypeSpecKind.Tuple:
                return(TupleTypesMatch(protoFunc, protoType as TupleTypeSpec, classFunc, classType as TupleTypeSpec));

            default:
                throw new NotImplementedException($"Unknown TypeSpec kind {protoType.Kind}");
            }
        }
Exemple #25
0
        private string GetFunction(FunctionDeclaration func, string[] splitScripts)
        {
            var stringBuilder = new StringBuilder();

            if (func.LineStart == func.LineEnd)
            {
                stringBuilder
                .Append($"{splitScripts[func.LineStart - 1].Substring(func.ColumnStart, (func.ColumnEnd - func.ColumnStart))}\r\n");
            }
            else
            {
                for (int i = func.LineStart - 1; i < func.LineEnd; i++)
                {
                    if (func.LineStart - 1 == i)
                    {
                        stringBuilder
                        .Append($"{splitScripts[i].Substring(func.ColumnStart, splitScripts[i].Length - func.ColumnStart)}\r\n");
                    }
                    else if (func.LineEnd - 1 == i)
                    {
                        stringBuilder.Append($"{splitScripts[i].Substring(0, func.ColumnEnd)}\r\n");
                    }
                    else
                    {
                        stringBuilder.Append($"{splitScripts[i]}\r\n");
                    }
                }
            }
            return(stringBuilder.ToString());
        }
Exemple #26
0
        public object VisitFunctionDeclaration(FunctionDeclaration functionDeclaration, object o)
        {
            functionDeclaration.ParameterList.Visit(this);
            functionDeclaration.Statements.Visit(this, functionDeclaration);

            return(null);
        }
Exemple #27
0
        private SyntaxTree(int entryPoint, params Parser.Program[] program)
        {
            // a syntax tree contains all declarative statements in a pack of files. it ignores other
            // executive statements and the sequence of them.

            int index = 0;

            foreach (var selected in program)
            {
                FunctionDeclaration entryFunction = new FunctionDeclaration(new Literal("___entry"));
                prog?.Result.Diagnostics.AddRange(selected.Result.Diagnostics);
                foreach (var stmt in selected.Body)
                {
                    this.Diagnostics.File = selected.Result.File;
                    if (stmt is DeclarationBlock decl)
                    {
                        VisitBlock(decl);
                        prog?.Body.Add(decl);
                    }
                    else if (index == entryPoint)
                    {
                        entryFunction.Statements.Add(stmt);
                    }
                }

                if (index == entryPoint)
                {
                    VisitBlock(entryFunction);
                    prog?.Body.Add(entryFunction);
                }

                index++;
            }
        }
 /// <summary>
 /// Creates the lua code function.
 /// </summary>
 /// <param name="dte">The DTE.</param>
 /// <param name="parent">The parent.</param>
 /// <param name="name">The name.</param>
 /// <param name="returnType">Type of the return.</param>
 /// <param name="access">The access.</param>
 /// <param name="function">The function.</param>
 /// <returns></returns>
 public static LuaCodeFunction CreateLuaCodeFunction(
     DTE dte, CodeElement parent, string name, LuaType returnType, vsCMAccess access,
     FunctionDeclaration function)
 {
     return(CreateLuaCodeFunction(dte, parent, name, returnType, access, vsCMFunction.vsCMFunctionFunction,
                                  function));
 }
 private void InferType(FunctionDeclaration node)
 {
     if (node.Type == null)
     {
         node.SetType(NodeHelper.CreateNode(NodeKind.VoidKeyword));
     }
 }
Exemple #30
0
        /// <summary>
        /// This method will format the label of the SignatureInformation with procedure's name and all the expected arguments
        /// </summary>
        /// <param name="procedure">The selected procedure</param>
        /// <returns></returns>
        public static SignatureInformation SignatureHelperSignatureFormatter(FunctionDeclaration procedure)
        {
            var parametersInfo = new ParameterInformation[procedure.Profile.Parameters.Count];
            int i = 0; bool firstPass = true;

            foreach (var parameter in procedure.Profile.InputParameters)
            {
                var label = string.Format("{0}{1}({2})", firstPass ? "INPUT " : null, parameter.DataName, parameter.DataType.Name);
                parametersInfo[i] = new ParameterInformation(label, null); //Replace null with commented documentation linked to parameter

                i++; firstPass = false;
            }
            firstPass = true;
            foreach (var parameter in procedure.Profile.InoutParameters)
            {
                var label = string.Format("{0}{1}({2})", firstPass ? "IN-OUT " : null, parameter.DataName, parameter.DataType.Name);
                parametersInfo[i] = new ParameterInformation(label, null);

                i++; firstPass = false;
            }
            firstPass = true;
            foreach (var parameter in procedure.Profile.OutputParameters)
            {
                var label = string.Format("{0}{1}({2})", firstPass ? "OUTPUT " : null, parameter.DataName, parameter.DataType.Name);
                parametersInfo[i] = new ParameterInformation(label, null);

                i++; firstPass = false;
            }

            return(new SignatureInformation(procedure.Name, null, parametersInfo)); //Replace null with commented documentation linked to procedure declaration
        }
        public void Void_OneArg()
        {
            var test = new FunctionDeclaration("DoSomething", Primitive.Void, AccessLevel.Public, false,
                new VariableDeclaration("myInt", Primitive.Int));

            Assert.AreEqual("void DoSomething(int myInt)", test.CreateSource());
        }
            public override bool Accept(Ast.FunctionDeclaration element, int data)
            {
                var method = parent.functions[element.name];

                if (il != null)
                {
                    throw new NotSupportedException("Nested fucntions are not supported");
                }
                currentFunction = element;
                il = method.GetILGenerator();
                foreach (var i in element.locals)
                {
                    il.DeclareLocal(typeof(long));
                }
                element.block.Accept(this, data);

                if (!element.hasReturn && !(element.block.statements.Last() is ReturnStatement))
                {
                    il.Emit(OpCodes.Ret);
                }

                if (element.hasReturn && !(element.block.statements.Last() is Ast.ReturnStatement))
                {
                    il.Emit(OpCodes.Ldc_I8, 0L);
                    il.Emit(OpCodes.Ret);
                }

                il = null;
                currentFunction = null;
                return(false);
            }
Exemple #33
0
        /// <summary>
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="codeGenerator"></param>
        /// <param name="functionDeclaration"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ExpressionSyntax Generate(IStandardFunctionMetadata metadata,
                                         MsilBinGenerator codeGenerator,
                                         FunctionDeclaration functionDeclaration,
                                         IReadOnlyList <Expression> parameters)
        {
            var reference = (VariableReferenceExpression)parameters[0];

            // generates {reference} = System.{type}.Parse(Console.ReadLine())
            return(SyntaxFactory.AssignmentExpression(
                       SyntaxKind.SimpleAssignmentExpression,
                       codeGenerator.CompileExpression(reference),
                       SyntaxFactory.InvocationExpression(
                           SyntaxFactory.MemberAccessExpression(
                               SyntaxKind.SimpleMemberAccessExpression,
                               SyntaxFactory.MemberAccessExpression(
                                   SyntaxKind.SimpleMemberAccessExpression,
                                   MsilBinGenerator.MapIdentifierName("System"),
                                   MsilBinGenerator.MapIdentifierName(MapTypeNames[functionDeclaration.Name])),
                               MsilBinGenerator.MapIdentifierName("Parse")))
                       .WithArgumentList(
                           SyntaxFactory.ArgumentList(
                               SyntaxFactory.SingletonSeparatedList(
                                   SyntaxFactory.Argument(
                                       SyntaxFactory.InvocationExpression(
                                           SyntaxFactory.MemberAccessExpression(
                                               SyntaxKind.SimpleMemberAccessExpression,
                                               MsilBinGenerator.MapIdentifierName("Console"),
                                               MsilBinGenerator.MapIdentifierName("ReadLine")))))))));
        }
        public void Void_TwoArgs()
        {
            var test = new FunctionDeclaration("DoSomething", Primitive.Void, AccessLevel.Public, false,
                new VariableDeclaration("myInt", Primitive.Int),
                new VariableDeclaration("someText", Primitive.Char.MakePointer().MakeConst()));

            Assert.AreEqual("void DoSomething(int myInt, const char *someText)", test.CreateSource());
        }
 public FunctionDeclaration(Position pos, Symbol name, FieldList param, NameType result, Expression body, FunctionDeclaration next)
 {
     Pos = pos;
     Name = name;
     Param = param;
     Result = result;
     Body = body;
     Next = next;
 }
Exemple #36
0
 public virtual object Walk(FunctionDeclaration node)
 {
     if (Enter(node))
     {
         node.Identifier.Accept(this);
         foreach (var parameter in node.FormalParameters)
         {
             parameter.Accept(this);
         }
         node.Body.Accept(this);
     }
     Exit(node);
     return null;
 }
        private void GenerateFunction(FunctionDeclaration function, StringBuilder programBuilder)
        {
            string parameterFormat = "ByVal {0} As {1}";
            string functionFormat = "Public Function {0}({1}){2}{3}";
            string blockFormat ="{0} End Function";
            var type = function.Type;
            var name = function.Id;

            string typeString = GetTypeString(type);
            if (!(type is VoidType))
            {
                typeString = "As " + typeString;
            }
            string parameters = string.Join(",",function.Parameters.Select(p => string.Format(parameterFormat,p.Id, GetTypeString(p.Type) )));
            string blockString = Environment.NewLine + string.Join(Environment.NewLine, function.Block.StatementList.Select(b => GetStatement(b)));
            blockString = string.Format(blockFormat, blockString);
            programBuilder.Append(string.Format(functionFormat, name, parameters, typeString, blockString));
        }
Exemple #38
0
 public override object Walk(FunctionDeclaration node)
 {
     var funcDec = new BikeFunction(node, node.Identifier, node.FormalParameters, node.Body,
         Context.CurrentFrame);
     Context.CurrentFrame.Define(node.Identifier.Value, funcDec);
     return funcDec;
 }
Exemple #39
0
 public override Statement VisitFunctionDeclaration(FunctionDeclaration fDecl) {
   if (fDecl == null) return fDecl;
   fDecl.Method = this.VisitMethod(fDecl.Method);
   return fDecl;
 }
Exemple #40
0
 public override Statement VisitFunctionDeclaration(FunctionDeclaration functionDeclaration){
   if (functionDeclaration == null) return null;
   this.VisitResolvedTypeReference(functionDeclaration.ReturnType, functionDeclaration.ReturnTypeExpression);
   return base.VisitFunctionDeclaration(functionDeclaration);
 }
Exemple #41
0
 public void VisitFunctionDeclaration(FunctionDeclaration functionDeclaration)
 {
     VisitFunctionExpression(functionDeclaration.Function);
 }
 private static FunctionCall Create(FunctionCall call, FunctionDeclaration declaration)
 {
     var result = new FunctionCall(call.QualifiedName, declaration.Library, declaration.Copy);
     if (declaration.Profile == null) return result;
     int count = declaration.Profile.InputParameters.Count + declaration.Profile.InoutParameters.Count + declaration.Profile.OutputParameters.Count;
     // declaration.Profile.ReturningParameter is not used because
     // the same data is always used by (and hardcoded in) function call codegen: <function.Name>-RESULT
     for(int i=0; i < count; i++) {
     var pAsDefined = GetParameter(i, declaration);
     var pAsUsed    = GetParameter(i, call);
     result.InputParameters.Add(Create(pAsDefined, pAsUsed));
     }
     return result;
 }
 public virtual bool Enter(FunctionDeclaration node)
 {
     return true;
 }
Exemple #44
0
 public virtual Statement VisitFunctionDeclaration(FunctionDeclaration functionDeclaration){
   if (functionDeclaration == null) return null;
   functionDeclaration.Parameters = this.VisitParameterList(functionDeclaration.Parameters);
   functionDeclaration.ReturnType = this.VisitTypeReference(functionDeclaration.ReturnType);
   functionDeclaration.Body = this.VisitBlock(functionDeclaration.Body);
   return functionDeclaration;
 }
 /// <summary>Parent node: PROCEDURE DIVISION</summary>
 /// <param name="context">DECLARE FUNCTION</param>
 public override void EnterFunctionDeclaration(ProgramClassParser.FunctionDeclarationContext context)
 {
     var terminal = context.FunctionDeclarationHeader();
     var header = terminal != null? (FunctionDeclarationHeader)terminal.Symbol : null;
     if (header != null) header.SetLibrary(CurrentProgram.Identification.ProgramName.Name);
     var node = new FunctionDeclaration(header);
     node.Label = "F"+(++functionsCounter).ToString("0000000");
     node.Library = CurrentProgram.Identification.ProgramName.Name;
     CurrentProgram.CurrentTable.AddFunction(node);
     Enter(node, context, new SymbolTable(CurrentProgram.CurrentTable, SymbolTable.Scope.Function));
 }
Exemple #46
0
 public override bool Enter(FunctionDeclaration node)
 {
     Print("FunctionDeclaration");
     level++;
     return true;
 }
Exemple #47
0
 public virtual Statement VisitFunctionDeclaration(FunctionDeclaration functionDeclaration, FunctionDeclaration changes, FunctionDeclaration deletions, FunctionDeclaration insertions){
   this.UpdateSourceContext(functionDeclaration, changes);
   if (functionDeclaration == null) return changes;
   return functionDeclaration;
 }
 public void VisitFunctionDeclaration(FunctionDeclaration funcDecl)
 {
     /*if(funcDecl == scope){
         // the function body is being analyzed, go deep:
         foreach(ParameterDeclaration p in funcDecl.Parameters)
             Define(p.Name);
     }else{*/
         // analyze the function definition itself (it is visited while analyzing parent scope):
         Define(funcDecl.Name);
         foreach(ParameterDeclaration p in funcDecl.Parameters){
             if(p.Option != null)
                 p.Option.AcceptWalker(this);
         }
     //}
 }
Exemple #49
0
 public virtual void VisitFunctionDeclaration(FunctionDeclaration functionDeclaration)
 {
   if (functionDeclaration == null) return;
   this.VisitParameterList(functionDeclaration.Parameters);
   this.VisitTypeReference(functionDeclaration.ReturnType);
   this.VisitBlock(functionDeclaration.Body);
 }
 public override Statement VisitFunctionDeclaration(FunctionDeclaration fDecl){
   if (fDecl == null) return fDecl;
   this.ConstructMethodForNestedFunction(fDecl, fDecl.Method, fDecl.ReturnType, fDecl.Parameters, fDecl.Body);
   return fDecl;
 }
        private void WriteFunction(FunctionDeclaration function, StringBuilder programBuilder)
        {
            mainName = GenerateLabel(function);
            if (function.Parameters.Count() > 0)
            {
                foreach (var param in function.Parameters)
                {
                    registerFile.stackx86.idValue = null;
                    var pos = registerFile.stack.Last().Value.positioninStack;
                    registerFile.stackx86.positioninStack = Convert.ToString(Convert.ToInt32(pos) + 4);
                    registerFile.stack.Add(param.Id, registerFile.stackx86);
                }
            }

            WriteGlobalVariables(programBuilder, mainName);
            programBuilder.AppendLine();
            programBuilder.AppendFormat("{0}:", mainName);
            programBuilder.AppendLine();
            programBuilder.Append("\t push ebp");
            programBuilder.Append("\t\t# Reserva el espacio de memoria en pila. ");
            programBuilder.AppendLine();
            programBuilder.Append("\t mov ebp, esp");
            programBuilder.Append("\t\t# Guarda el espacio de memoria en pila. ");
            programBuilder.AppendLine();
            programBuilder.Append("\t sub ebp, -64");
            programBuilder.AppendLine("\t\t# Reserva el espacio para variables a usar. ");

            WriteBlock(function.Block, programBuilder);

            programBuilder.Append("\t mov DWORD PTR [ebp-16], eax");
            programBuilder.Append("\t# Guarda eax en la pila para retorno");
            programBuilder.AppendLine();
            programBuilder.AppendLine("\t leave");
            programBuilder.Append("\t ret");
            programBuilder.Append("\t\t# Restablece la pila.");
            programBuilder.AppendLine();
        }
 void PrintDeclaration(FunctionDeclaration d, int i)
 {
     Say("FunctionDeclaration(");
     if (d != null)
     {
         SayLn(d.Name.ToString());
         PrintFieldlist(d.Param, i+1); SayLn(",");
         if (d.Result!=null) {
         Indent(i+1); SayLn(d.Result.Name.ToString());
     }
     PrintExpression(d.Body, i+1); SayLn(",");
     Indent(i+1); PrintDeclaration(d.Next, i+1);
     }
     Say(")");
 }
    public virtual Differences VisitFunctionDeclaration(FunctionDeclaration functionDeclaration1, FunctionDeclaration functionDeclaration2){
      Differences differences = new Differences(functionDeclaration1, functionDeclaration2);
      if (functionDeclaration1 == null || functionDeclaration2 == null){
        if (functionDeclaration1 != functionDeclaration2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      FunctionDeclaration changes = (FunctionDeclaration)functionDeclaration2.Clone();
      FunctionDeclaration deletions = (FunctionDeclaration)functionDeclaration2.Clone();
      FunctionDeclaration insertions = (FunctionDeclaration)functionDeclaration2.Clone();

      Differences diff = this.VisitBlock(functionDeclaration1.Body, functionDeclaration2.Body);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Body = diff.Changes as Block;
      deletions.Body = diff.Deletions as Block;
      insertions.Body = diff.Insertions as Block;
      Debug.Assert(diff.Changes == changes.Body && diff.Deletions == deletions.Body && diff.Insertions == insertions.Body);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitIdentifier(functionDeclaration1.Name, functionDeclaration2.Name);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Name = diff.Changes as Identifier;
      deletions.Name = diff.Deletions as Identifier;
      insertions.Name = diff.Insertions as Identifier;
      Debug.Assert(diff.Changes == changes.Name && diff.Deletions == deletions.Name && diff.Insertions == insertions.Name);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      ParameterList parChanges, parDeletions, parInsertions;
      diff = this.VisitParameterList(functionDeclaration1.Parameters, functionDeclaration2.Parameters, out parChanges, out parDeletions, out parInsertions);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Parameters = parChanges;
      deletions.Parameters = parDeletions;
      insertions.Parameters = parInsertions;
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitTypeNode(functionDeclaration1.ReturnType, functionDeclaration2.ReturnType);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.ReturnType = diff.Changes as TypeNode;
      deletions.ReturnType = diff.Deletions as TypeNode;
      insertions.ReturnType = diff.Insertions as TypeNode;
      //Debug.Assert(diff.Changes == changes.ReturnType && diff.Deletions == deletions.ReturnType && diff.Insertions == insertions.ReturnType);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
Exemple #54
0
 public override Statement VisitFunctionDeclaration(FunctionDeclaration func){
   if (func == null || func.Method == null) return null;
   TypeNode closure = func.Method.DeclaringType;
   this.VisitMethod(func.Method);
   if (closure != null && closure.Members != null)
     closure.Members.Add(func.Method);
   return null;
 }
 public virtual void Exit(FunctionDeclaration node)
 {
 }
 private static ParameterDescription GetParameter(int index, FunctionDeclaration function)
 {
     int offset = 0;
     if (index - offset < function.Profile.InputParameters.Count) return function.Profile.InputParameters[index-offset];
     offset += function.Profile.InputParameters.Count;
     if (index - offset < function.Profile.InoutParameters.Count) return function.Profile.InoutParameters[index-offset];
     offset += function.Profile.InoutParameters.Count;
     if (index - offset < function.Profile.OutputParameters.Count) return function.Profile.OutputParameters[index-offset];
     offset += function.Profile.OutputParameters.Count;
     if (index - offset < 1) return function.Profile.ReturningParameter;
     throw new System.ArgumentOutOfRangeException("Expected: "+index+" < "+function.Profile.InputParameters.Count
                                                                  +'+'+function.Profile.InoutParameters.Count
                                                                  +'+'+function.Profile.OutputParameters.Count
                                                                  +'+'+(function.Profile.ReturningParameter!=null?1:0));
 }
Exemple #57
0
 public override void Exit(FunctionDeclaration node)
 {
     level--;
 }
 public virtual Statement VisitFunctionDeclaration(FunctionDeclaration functionDeclaration1, FunctionDeclaration functionDeclaration2)
 {
     if (functionDeclaration1 == null) return null;
     if (functionDeclaration2 == null)
     {
         functionDeclaration1.Parameters = this.VisitParameterList(functionDeclaration1.Parameters, null);
         functionDeclaration1.ReturnType = this.VisitTypeReference(functionDeclaration1.ReturnType, null);
         functionDeclaration1.Body = this.VisitBlock(functionDeclaration1.Body, null);
     }
     else
     {
         functionDeclaration1.Parameters = this.VisitParameterList(functionDeclaration1.Parameters, functionDeclaration2.Parameters);
         functionDeclaration1.ReturnType = this.VisitTypeReference(functionDeclaration1.ReturnType, functionDeclaration2.ReturnType);
         functionDeclaration1.Body = this.VisitBlock(functionDeclaration1.Body, functionDeclaration2.Body);
     }
     return functionDeclaration1;
 }
        public void VisitFunctionDeclaration(FunctionDeclaration funcDecl)
        {
            UniqueIdGenerator.DefineNewId(funcDecl.NameToken);
            int tmp_counter = scope_counter;
            DecendScope();
            scope_counter = 0;

            funcDecl.Parameters.AcceptWalker(this);
            funcDecl.Body.AcceptWalker(this);

            AscendScope();
            scope_counter = tmp_counter + 1;
        }
Exemple #60
0
 public override Statement VisitFunctionDeclaration(FunctionDeclaration functionDeclaration)
 {
     if (functionDeclaration == null) return null;
     return base.VisitFunctionDeclaration((FunctionDeclaration)functionDeclaration.Clone());
 }