Esempio n. 1
0
        private void compilacion(ICharStream input, string pathSalida)
        {
            compilacionOK = false;

            //Plantillas
            //TextReader groupFileR = new StreamReader("C:\\Proyectos\\ProyectosVS\\FKVM\\FKVM\\src\\antlr\\FkvmIL.stg");
            TextReader groupFileR = new StreamReader(
                System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("FKVM.src.antlr.FkvmIL.stg"));
            StringTemplateGroup templates = new StringTemplateGroup(groupFileR);
            groupFileR.Close();

            //Análisis Léxico-Sintáctico
            Console.WriteLine("Análisis léxico-sintáctico...");
            //ANTLRFileStream input = new ANTLRFileStream(pathEntrada);
            FKVMLexer lexer = new FKVMLexer(input);

            CommonTokenStream tokens = new CommonTokenStream(lexer);
            FKVMParser parser = new FKVMParser(tokens);
            parser.TreeAdaptor = adaptor;
            parser.reportarError = re;
            FKVMParser.programa_return result = parser.programa();

            //Si no hay errores léxicos ni sintácticos ==> Análisis Semántico
            if (lexer.numErrors + parser.numErrors == 0)
            {
                //Analisis Semántico
                Console.WriteLine("Análisis semántico...");
                CommonTree t = ((CommonTree)result.Tree);
                //Console.WriteLine(t.ToStringTree() + "\n\n"); //
                CommonTreeNodeStream nodes2 = new CommonTreeNodeStream(t);
                nodes2.TokenStream = tokens;
                FKVMSem walker2 = new FKVMSem(nodes2);
                walker2.reportarError = re;
                walker2.programa(parser.symtable);

                //Si no hay errores en el análisis semántico ==> Generación de código
                if (walker2.numErrors == 0)
                {
                    //Generación de Código
                    Console.WriteLine("Generación de código...");
                    CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
                    nodes.TokenStream = tokens;
                    FKVMGen walker = new FKVMGen(nodes);
                    walker.TemplateLib = templates;
                    FKVMGen.programa_return r2 = walker.programa(parser.numVars);

                    //Presentación de resultados
                    StringTemplate output = (StringTemplate)r2.Template;
                    //Console.WriteLine(output.ToString());

                    StreamWriter pw = new StreamWriter(pathSalida);
                    pw.WriteLine(output.ToString());
                    pw.Flush();
                    pw.Close();

                    compilacionOK = true;
                }
            }
        }
 /// <summary>
 /// Creates a StringTemplateGroup instance that manages a set of
 /// templates defined in a "group file".
 /// </summary>
 /// <param name="reader">Input stream for group file data</param>
 /// <param name="lexer">Lexer to use for breaking up templates into chunks</param>
 /// <param name="errorListener">Error message sink</param>
 /// <param name="superGroup">Parent (or super/base) group</param>
 /// <returns>A StringTemplateGroup instance or null if no group is found</returns>
 public StringTemplateGroup CreateGroup(
     TextReader reader,
     Type lexer,
     IStringTemplateErrorListener errorListener,
     StringTemplateGroup superGroup)
 {
     return new StringTemplateGroup(reader, lexer, errorListener, superGroup);
 }
Esempio n. 3
0
        public string Process(string template, Dictionary<string, object> variables)
        {
            //This is a hack, but it removes the need for a step to separate html from tt
            //by treating it all as literals between tags
            Console.WriteLine("--------------------------------------------");
            Console.WriteLine(template);
            template = string.Concat("[%'", template.Replace("[%", "'^^][%").Replace("%]", "%][%'").Replace("'^^]", "'%]"), "'%]");
            template = template.Replace("[%''%]", "");
            Console.WriteLine("--------------------------------------------");
            Console.WriteLine(template);
            Console.WriteLine("--------------------------------------------");


            //CSharpTarget.stg contains string templates used for targeting C#
            //TextReader stgReader = new StreamReader(File.Open("CSharpGenerator.stg", FileMode.Open));
            TextReader stgReader = new StreamReader("CSharpGenerator.stg");
            StringTemplateGroup stg = new StringTemplateGroup(stgReader);

            //lex
            ICharStream input = new ANTLRStringStream(template);
            TemplateLexer lex = new TemplateLexer(input);

            //parse
            TemplateParser parse = new TemplateParser(new CommonTokenStream(lex));
            TemplateParser.document_return parseRet = parse.document();

            Console.WriteLine(( (CommonTree) parseRet.Tree).ToStringTree());

            //generate C#
            ITreeNodeStream nodeStream = new CommonTreeNodeStream(parseRet.Tree);
            CSharpGenerator gen = new CSharpGenerator(nodeStream);
            gen.TemplateLib = stg;
            CSharpGenerator.document_return ret = gen.document();

            //compile to executable and optionally run
            Console.WriteLine("--------------------------------------------");
            Console.WriteLine(ret.Template.ToString());
            Console.WriteLine("--------------------------------------------");


            // compile and run it
            var inMemory = true;
            Assembly assembly = Generate(ret.Template.ToString(), "", inMemory);
            if (inMemory)
            {
                //assembly.EntryPoint.Invoke(null, new object[] { new string[] { } });
                var o = assembly.CreateInstance("x");
                Object[] args = {this.Settings, variables};
                var result = o.GetType().InvokeMember("Render", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, o, args);

                return result.ToString();
            } 


            return "";
        }
Esempio n. 4
0
File: Main.cs Progetto: dfneto/comdd
        public static void Main(string[] args)
        {
            // Use a try/catch block for parser exceptions
            try
            {
                string inputFileName;
                string templateFileName;

                if ((args.Length == 1) || (args.Length == 2))
                {
                    if (args.Length == 1)
                    {
                        templateFileName = "Java.stg";
                        inputFileName = args[0];
                    }
                    else
                    {
                        templateFileName = args[0];
                        inputFileName = args[1];
                    }

                    // Ensure full pathnames
                    if (!Path.IsPathRooted(templateFileName))
                    {
                        //templateFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templateFileName);
                        templateFileName = Path.Combine(Environment.CurrentDirectory, templateFileName);
                    }
                    if (!Path.IsPathRooted(inputFileName))
                    {
                        inputFileName = Path.Combine(Environment.CurrentDirectory, inputFileName);
                    }

                    templates = new StringTemplateGroup(new StreamReader(templateFileName),
                                        typeof(AngleBracketTemplateLexer));

                    ICharStream input = new ANTLRFileStream(inputFileName);
                    CMinusLexer lexer = new CMinusLexer(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    CMinusParser parser = new CMinusParser(tokens);
                    parser.TemplateLib = templates;
                    RuleReturnScope r = parser.program();
                    Console.Out.WriteLine(r.Template.ToString());
                }
                else
                    Console.Error.WriteLine("Usage: cminus [<output-template-file>] <input-file>");
            }
            catch (System.Exception e)
            {
                Console.Error.WriteLine("exception: " + e);
                Console.Error.WriteLine(e.StackTrace); // so we can get stack trace
            }
        }
    public StringTemplate LoadTemplate(string name)
    {
        if (_templateGroup == null) {
            _templateGroup = new StringTemplateGroup("MG", GLexConfig.TemplatePath, typeof(DefaultTemplateLexer));
            _templateGroup.RegisterAttributeRenderer(typeof(bool), TemplateRenderers.BoolRenderer.Instance);
            _templateGroup.RegisterAttributeRenderer(typeof(Color), TemplateRenderers.ColorRenderer.Instance);
            _templateGroup.RegisterAttributeRenderer(typeof(DateTime), TemplateRenderers.DateTimeRenderer.Instance);
            _templateGroup.RegisterAttributeRenderer(typeof(Vector3), TemplateRenderers.VectorRenderer.Instance);
            _templateGroup.RegisterAttributeRenderer(typeof(Vector2), TemplateRenderers.VectorRenderer.Instance);
            _templateGroup.RegisterAttributeRenderer(typeof(Matrix4x4), TemplateRenderers.MatrixRenderer.Instance);
        }

        Debug.Log (name);
        return _templateGroup.GetInstanceOf(GLexConfig.GetTemplate(name));
    }
 /// <summary>
 /// Creates a StringTemplateGroup instance that manages a set of 
 /// templates that are accessible via a specified 
 /// <seealso cref="StringTemplateLoader"/>.
 /// </summary>
 /// <param name="name">Input stream for group file data</param>
 /// <param name="templateLoader">Loader for retrieving this group's templates</param>
 /// <param name="lexer">Lexer to use for breaking up templates into chunks</param>
 /// <param name="errorListener">Error message sink</param>
 /// <param name="superGroup">Parent (or super/base) group</param>
 /// <returns>A StringTemplateGroup instance or null</returns>
 public StringTemplateGroup CreateGroup(
     string name,
     StringTemplateLoader templateLoader,
     Type lexer,
     IStringTemplateErrorListener errorListener,
     StringTemplateGroup superGroup)
 {
     return new StringTemplateGroup(name, templateLoader, lexer, errorListener, superGroup);
 }
        /**
         * Instantiates an instance of the CxxTestDriverGenerator for the
         * specified project and test suite collection.
         *
         * @param project the ICProject associated with this generator
         * @param path the path of the source file to be generated
         * @param suites the collection of test suites to be generated
         *
         * @throws IOException if an I/O error occurs during generation
         */
        public TestRunnerGenerator(string path, TestSuiteCollection suites,
			Dictionary<string, bool> testsToRun)
        {
            this.suites = suites;
            this.runnerPath = path;

            // Create a proxy object to manage the tests to run. Any tests
            // not in this map are assumed to be true (so that if tests
            // have been added, but not refreshed in the tool window, they
            // will be run until they are explicitly disabled).

            this.testsToRunProxy = new TestsToRunProxy(testsToRun);

            // Load the template from the embedded assembly resources.

            Stream stream =
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                RunnerTemplateResourcePath);

            StringTemplateGroup templateGroup = new StringTemplateGroup(
                new StreamReader(stream), typeof(AngleBracketTemplateLexer));

            templateGroup.RegisterAttributeRenderer(typeof(string),
                new TestRunnerStringRenderer(path));

            template = templateGroup.GetInstanceOf("runAllTestsFile");

            // Initialize the options that will be passed into the template.

            options = new Hashtable();
            options["platformIsMSVC"] = true;
            options["trapSignals"] = true;
            options["traceStack"] = true;
            options["noStaticInit"] = true;
            options["root"] = true;
            options["part"] = false;
            options["abortOnFail"] = true;
            options["longLongType"] = null;
            options["mainProvided"] = suites.MainFunctionExists;
            options["runner"] = "XmlStdioPrinter";
            options["xmlOutput"] = true;
            options["testResultsFilename"] = Constants.TestResultsFilename;
            options["testsToRun"] = testsToRunProxy;

            writer = File.CreateText(path);
        }
Esempio n. 8
0
 //        private readonly StringTemplateGroup group = new StringTemplateGroup("myGroup", @"C:\shared.datastore\repository\personal\dev\projects\semantic-web\LinqToRdf.Prototypes\RdfMetal\template");
 public CodeGenerator()
 {
     templateLoader = new EmbeddedResourceTemplateLoader(GetType().Assembly, TemplateNamespace);
     stringTemplateGroup = new StringTemplateGroup("RdfMetal", templateLoader);
 }
Esempio n. 9
0
 static TemplateWrap()
 {
     log = log4net.LogManager.GetLogger(typeof(TemplateWrap));
     Group = new StringTemplateGroup("CodeNote", TemplateDir, typeof(Antlr.StringTemplate.Language.DefaultTemplateLexer));
 }
 /// <summary>
 /// Creates a group manager for some templates, all of which are
 /// loaded via a <see cref="StringTemplateLoader"/>.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="templateLoader"></param>
 /// <param name="lexer"></param>
 /// <param name="errorListener"></param>
 public StringTemplateGroup(
     string name,
     StringTemplateLoader templateLoader,
     Type lexer,
     IStringTemplateErrorListener errorListener,
     StringTemplateGroup superGroup)
 {
     this.name = name;
     nameToGroupMap[name] = this;
     if (templateLoader == null)
         this.templateLoader = new NullTemplateLoader();
     else
         this.templateLoader = templateLoader;
     this.templateLexerClass = lexer;
     if (errorListener == null)
         this.errorListener = DEFAULT_ERROR_LISTENER;
     else
         this.errorListener = errorListener;
     this.superGroup = superGroup;
 }
 /// <summary>
 /// Loads the named StringTemplateGroup instance with the specified super 
 /// group from somewhere. Configure to use specified lexer.
 /// </summary>
 /// <remarks>
 /// Groups with region definitions must know their supergroup to find 
 /// templates during parsing.
 /// </remarks>
 /// <param name="groupName">Name of the StringTemplateGroup to load</param>
 /// <param name="superGroup">Super group</param>
 /// <param name="lexer">Type of lexer to use to break up templates into chunks</param>
 /// <returns>A StringTemplateGroup instance or null if no group is found</returns>
 public StringTemplateGroup LoadGroup(string groupName, StringTemplateGroup superGroup, Type lexer)
 {
     StringTemplateGroup group = null;
     try
     {
         Stream groupStream = assembly.GetManifestResourceStream(namespaceRoot + "." + groupName + ".stg");
         group = factory.CreateGroup(new StreamReader(groupStream), lexer, errorListener, superGroup);
     }
     catch (Exception ex)
     {
         Error("Resource Error: can't load group '" + namespaceRoot + "." + groupName + ".stg' from assembly '" + assembly.FullName + "'", ex);
     }
     return group;
 }
Esempio n. 12
0
 public TreeElements()
 {
     group = new StringTemplateGroup(new StringReader(BASE));
     templateGroup = new StringTemplateGroup("interface");
         templateGroup.SuperGroup = group;
     templateGroup.DefineTemplate("interface", INTERFACE_DECLARATION);
     templateGroup.DefineTemplate("impl", IMPL_DECLARATION);
     templateGroup.DefineTemplate("elementTypes", ELEMENT_TYPES_DECLARATION);
     templateGroup.DefineTemplate("elementTypeInstances", ELEMENT_TYPE_INSTANCES_DECLARATION);
     templateGroup.DefineTemplate("elementsFactory", ELEMENTS_FACTORY);
 }
Esempio n. 13
0
        public void GenerateFile(string outputFilePath, string templateString, string templateName, string rootName, object root)
        {
            if (_mostRecentSourceFile < File.GetLastWriteTimeUtc(outputFilePath)) return;

            StringTemplateGroup group;

            using (StringReader reader = new StringReader(templateString))
            {
                group = new StringTemplateGroup(reader, typeof(AngleBracketTemplateLexer));
            }

            StringTemplate template = group.GetInstanceOf(templateName);

            template.SetAttribute(rootName, root);

            using (StreamWriter writer = new StreamWriter(outputFilePath, false))
            {
                template.Write(new AutoIndentWriter(writer));
            }
        }
 /// <summary>
 /// Return a list of all template sigs that are present in the group, but
 /// that have wrong formal argument lists.  Return null if all is well.
 /// </summary>
 /// <param name="group">Group to check</param>
 /// <returns>
 /// List of templates with mismatched signatures from specified group or null
 /// </returns>
 public IList GetMismatchedTemplates(StringTemplateGroup group)
 {
     ArrayList mismatched = null;
     foreach (string name in templates.Keys)
     {
         TemplateDefinition tdef = (TemplateDefinition) templates[name];
         if ( group.IsDefined(tdef.name) )
         {
             StringTemplate defST = group.GetTemplateDefinition(tdef.name);
             IDictionary formalArgs = defST.FormalArguments;
             bool ack = false;
             if ( (tdef.formalArgs!=null && formalArgs==null) ||
                 (tdef.formalArgs==null && formalArgs!=null) ||
                 (tdef.formalArgs.Count != formalArgs.Count) )
             {
                 ack = true;
             }
             if ( !ack )
             {
                 foreach (string argName in formalArgs.Keys)
                 {
                     if ( tdef.formalArgs[argName] == null )
                     {
                         ack=true;
                         break;
                     }
                 }
             }
             if ( ack )
             {
                 // Console.Out.WriteLine(CollectionUtils.DictionaryToString(tdef.formalArgs)
                 //	+ "!=" + CollectionUtils.DictionaryToString(formalArgs));
                 if (mismatched == null)
                 {
                     mismatched = new ArrayList();
                 }
                 mismatched.Add(GetTemplateSignature(tdef));
             }
         }
     }
     return mismatched;
 }
 /// <summary>
 /// Return a list of all template names missing from group that are defined
 /// in this interface. Return null if all is well.
 /// </summary>
 /// <param name="group">Group to check</param>
 /// <returns>List of templates missing from specified group or null</returns>
 public IList GetMissingTemplates(StringTemplateGroup group)
 {
     ArrayList missing = null;
     foreach (string name in templates.Keys)
     {
         TemplateDefinition tdef = (TemplateDefinition) templates[name];
         if ( !tdef.optional && !group.IsDefined(tdef.name) )
         {
             if (missing == null)
             {
                 missing = new ArrayList();
             }
             missing.Add(tdef.name);
         }
     }
     return missing;
 }
 public static StringTemplateGroup LoadGroup(string name, StringTemplateGroup superGroup)
 {
     if (groupLoader != null)
     {
         return groupLoader.LoadGroup(name, superGroup);
     }
     return null;
 }
 /// <summary>
 /// Create a group from the input stream, but use a nondefault lexer
 /// to break the templates up into chunks.  This is usefor changing
 /// the delimiter from the default $...$ to <...>, for example.
 /// </summary>
 public StringTemplateGroup(
     TextReader r,
     Type lexer,
     IStringTemplateErrorListener errorListener,
     StringTemplateGroup superGroup)
 {
     this.templatesDefinedInGroupFile = true;
     this.templateLexerClass = (lexer == null) ? typeof(AngleBracketTemplateLexer) : lexer;
     this.errorListener = (errorListener == null) ? DEFAULT_ERROR_LISTENER : errorListener;
     this.superGroup = superGroup;
     this.templateLoader = new NullTemplateLoader();
     ParseGroup(r);
     VerifyInterfaceImplementations();
 }
 public StringTemplateGroup(TextReader r, IStringTemplateErrorListener errorListener, StringTemplateGroup superGroup)
     : this(r, null, errorListener, superGroup)
 {
 }
 /// <summary>
 /// Loads the named StringTemplateGroup instance with the specified super 
 /// group from somewhere. 
 /// </summary>
 /// <remarks>
 /// Groups with region definitions must know their supergroup to find 
 /// templates during parsing.
 /// </remarks>
 /// <param name="groupName">Name of the StringTemplateGroup to load</param>
 /// <param name="superGroup">Super group</param>
 /// <returns>A StringTemplateGroup instance or null if no group is found</returns>
 public StringTemplateGroup LoadGroup(string groupName, StringTemplateGroup superGroup)
 {
     return LoadGroup(groupName, superGroup, null);
 }
 /// <summary>
 /// Loads the named StringTemplateGroup instance with the specified super 
 /// group from somewhere. Configure to use specified lexer.
 /// </summary>
 /// <remarks>
 /// Groups with region definitions must know their supergroup to find 
 /// templates during parsing.
 /// </remarks>
 /// <param name="groupName">Name of the StringTemplateGroup to load</param>
 /// <param name="superGroup">Super group</param>
 /// <param name="lexer">Type of lexer to use to break up templates into chunks</param>
 /// <returns>A StringTemplateGroup instance or null if no group is found</returns>
 public StringTemplateGroup LoadGroup(string groupName, StringTemplateGroup superGroup, Type lexer)
 {
     foreach (IStringTemplateGroupLoader loader in loaders)
     {
         StringTemplateGroup group = loader.LoadGroup(groupName, superGroup, lexer);
         if (group != null)
             return group;
     }
     return null;
 }
 /// <summary>
 /// Loads the named StringTemplateGroup instance with the specified super 
 /// group from somewhere. Configure to use specified lexer.
 /// </summary>
 /// <remarks>
 /// Groups with region definitions must know their supergroup to find 
 /// templates during parsing.
 /// </remarks>
 /// <param name="groupName">Name of the StringTemplateGroup to load</param>
 /// <param name="superGroup">Super group</param>
 /// <param name="lexer">Type of lexer to use to break up templates into chunks</param>
 /// <returns>A StringTemplateGroup instance or null if no group is found</returns>
 public StringTemplateGroup LoadGroup(string groupName, StringTemplateGroup superGroup, Type lexer)
 {
     StringTemplateGroup group = null;
     string fileName = LocateFile(groupName + ".stg");
     if (fileName == null)
     {
         Error("no such group file '" + groupName + ".stg'");
     }
     else
     {
         using (StreamReader reader = new StreamReader(fileName, encoding))
         {
             try
             {
                 group = factory.CreateGroup(reader, lexer, errorListener, superGroup);
             }
             catch (ArgumentException argx)
             {
                 Error("Path Error: can't load group '" + groupName + "'", argx);
             }
             catch (IOException iox)
             {
                 Error("IO Error: can't load group '" + groupName + "'", iox);
             }
         }
     }
     return group;
 }
        private void WriteHeaderFileContent(TextWriter writer, string suitePath)
        {
            Stream stream =
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                NewTestSuiteTemplateResourcePath);

            StringTemplateGroup templateGroup = new StringTemplateGroup(
                new StreamReader(stream), typeof(AngleBracketTemplateLexer));

            templateGroup.RegisterAttributeRenderer(typeof(string),
                new NewTestSuiteStringRenderer(suitePath));

            StringTemplate template =
                templateGroup.GetInstanceOf("newSuiteFile");

            // Initialize the options that will be passed into the template.

            Hashtable options = new Hashtable();
            options["suiteName"] = suiteName;
            options["superclass"] = superclass;
            options["headerUnderTest"] = headerUnderTest.CanonicalName;
            options["createSetUp"] = createSetUp;
            options["createTearDown"] = createTearDown;

            template.SetAttribute("options", options);
            template.SetAttribute("testCases", new List<string>(stubNames));

            template.Write(new AutoIndentWriter(writer));
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            try
            {
                string inputFileName;
                string templateFileName;

                if ((args.Length == 1) || (args.Length == 2))
                {
                    if (args.Length == 1)
                    {
                        templateFileName = "CUDAC.stg";
                        inputFileName = args[0];
                    }
                    else
                    {
                        templateFileName = args[0];
                        inputFileName = args[1];
                    }

                    if (!Path.IsPathRooted(templateFileName))
                    {
                        //templateFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templateFileName);
                        templateFileName = Path.Combine(Environment.CurrentDirectory, templateFileName);
                    }
                    if (!Path.IsPathRooted(inputFileName))
                    {
                        inputFileName = Path.Combine(Environment.CurrentDirectory, inputFileName);
                    }

                    templates = new StringTemplateGroup(new StreamReader(templateFileName),
                                        typeof(AngleBracketTemplateLexer));
                    templates2 = new StringTemplateGroup(new StreamReader("CUDAPattern.stg"),
                                        typeof(AngleBracketTemplateLexer));
                    templates3 = new StringTemplateGroup(new StreamReader("CUDACkernel.stg"),
                                       typeof(AngleBracketTemplateLexer));

                    //ArrayList one=new ArrayList();
                    //one.Add("i");
                    ////one.Add("+");
                    ////one.Add("1");

                    //ArrayList two = new ArrayList();
                    //two.Add("i");

                    Analysis analysis = new Analysis();
                    //if (analysis.BenergyTest(one, two))
                    //{
                    //    Console.Out.WriteLine("Iterative Dependecy");
                    //}
                    //else
                    //{
                    //    Console.Out.WriteLine("No Dependecy");
                    //}
                    //return;

                    ICharStream input = new ANTLRFileStream(inputFileName);
                    C2CUDATranslatorLexer lexer = new C2CUDATranslatorLexer(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    C2CUDATranslatorParser parser = new C2CUDATranslatorParser(tokens);
                    parser.TemplateLib = templates;
                    RuleReturnScope r = parser.program();
                    Console.Out.WriteLine(r.Template.ToString().Replace(@"\/", "/").ToString());
                    // Part 2
                    // Console.Error.WriteLine("Getting Pattern");
                    ICharStream input3 = new ANTLRFileStream(inputFileName);
                    C2CUDATranslatorLexer lexer3 = new C2CUDATranslatorLexer(input3);
                    CommonTokenStream tokens3 = new CommonTokenStream(lexer3);
                    C2CUDATranslatorParser parser3 = new C2CUDATranslatorParser(tokens3);
                    parser3.TemplateLib = templates3;
                    RuleReturnScope r3 = parser3.program();

                    ICharStream input2 = new ANTLRStringStream(r3.Template.ToString().Replace("((", "( (").Replace(@"\/", "/").ToString().ToString().Replace("))", ") )").ToString().Replace("){", ") {").ToString().Replace("**", "*").ToString());
                    PatternGeneratorLexer lexer2 = new PatternGeneratorLexer(input2);
                    CommonTokenStream tokens2 = new CommonTokenStream(lexer2);
                    PatternGeneratorParser parser2 = new PatternGeneratorParser(tokens2);
                    parser2.TemplateLib = templates2;
                    RuleReturnScope r2 = parser2.pattern();
                    Console.Error.WriteLine("// Pattern : ");
                    string pattern= r2.Template.ToString();
                    Console.Out.WriteLine("//" + r2.Template.ToString().Replace("\r\n","\r\n//"));

                    //Console.Out.WriteLine("Checking in Database");

                    //string connecstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
                    //SqlConnection con = new SqlConnection(connecstr);
                    //con.Close();
                    //con.Open();
                    //String sql = "Select * from PatternDatabase";
                    //DataTable dt = new DataTable();
                    //SqlDataAdapter adp = new SqlDataAdapter(sql,con);
                    //adp.Fill(dt);
                    //bool flag=false ;
                    //for(int i=0;i<dt.Rows.Count -1 ;i++)
                    //{
                    //    if(pattern==dt.Rows[i][1].ToString())
                    //    {
                    //        Console.Out.WriteLine("Found in Database");
                    //        flag =true ;
                    //    }
                    //    else
                    //    {
                    //    }
                    //}
                    //if (flag == true)
                    //{
                    //}
                    //else
                    //{
                    //    sql = "Insert into PatternDatabase values('"+pattern.ToString()+"','"+pattern.ToString()+"')";
                    //    SqlCommand cmd = new SqlCommand(sql, con);
                    //    cmd.ExecuteNonQuery();
                    //    con.Close();
                    //    Console.Out.WriteLine("Not Found in Database But added in database");
                    //}
                    //con.Close();
                    string lines = "group CUDA;\r\n pattern(type,name,args,";

                     string[] p = pattern.ToString().Replace("{", " ").ToString().Replace("}", " ").ToString().Replace("\n", ",").Replace(@"\/", "/").ToString().Substring(34, pattern.Length - 34).ToString().Split(',');
                    for (int i = 0;i< p.Length  -1; i++)
                    {
                        if (p[i].ToString().Trim() != "")
                        {
                            lines = lines + p[i].ToString().Trim() + ",\r\n";
                        }
                    }
                    lines = lines + ") ::= << " + "\r\n" + "<type> <name>(<args; separator=\"\\n\">) {" + "\r\n";

                    for (int i = 0;i< p.Length  -1; i++)
                    {
                        if (p[i].ToString().Trim() != "")
                        {
                            lines = lines + " <" + p[i].ToString().Trim() + ">" + "\r\n";
                        }
                    }
                    lines = lines + ">>";
                    System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.stg");
                    file.WriteLine(lines);

                    file.Close();

                    Console.ReadLine();

                }
                else
                    Console.Error.WriteLine("Usage: C2CUDATranslator [<output-template-file>] <input-file>");
            }
            catch (System.Exception e)
            {
                Console.Error.WriteLine("exception: " + e);
                Console.Error.WriteLine(e.StackTrace);
                Console.ReadLine();
            }
        }
Esempio n. 24
0
        public static void CS2JMain(string[] args)
        {
            long startTime = DateTime.Now.Ticks;
            bool doHelp = false;

            // Use a try/catch block for parser exceptions
            try
            {
                // if we have at least one command-line argument
                if (args.Length > 0)
                {
			
                    if (cfg.Verbosity >= 2) Console.Error.WriteLine("Parsing Command Line Arguments...");

                    OptionSet p = new OptionSet ()
                        .Add ("config=", f => updateFromConfigFile(f, cfg))
                        .Add ("v", v => cfg.Verbosity = cfg.OptVerbosity.IsDefault ? 1 : cfg.Verbosity + 1)
                        .Add ("debug=", v => cfg.DebugLevel = Int32.Parse(v))
                        .Add ("debug-template-extraction:", v => cfg.DebugTemplateExtraction = parseBoolOption(v))
                        .Add ("warnings:", v => cfg.Warnings = parseBoolOption(v))
                        .Add ("warnings-resolve-failures:", v => cfg.WarningsFailedResolves = parseBoolOption(v))
                        .Add ("version:", v => { if (parseBoolOption(v)) showVersion(); })
                        .Add ("help|h|?", v => {doHelp = true; doEarlyExit = true; })
                        .Add ("show-csharp:", v => cfg.DumpCSharp = parseBoolOption(v))
                        .Add ("show-java:", v => cfg.DumpJava = parseBoolOption(v))
                        .Add ("show-javasyntax:", v => cfg.DumpJavaSyntax = parseBoolOption(v))
                        .Add ("show-tokens:", v => cfg.DisplayTokens = parseBoolOption(v))
                        .Add ("D=", def => cfg.OptMacroDefines.Add(mkStrings(def))) 							
                        .Add ("dump-enums:", v => cfg.DumpEnums = parseBoolOption(v))
                        .Add ("out-enums-file=", dir => cfg.EnumDir = Path.Combine(Directory.GetCurrentDirectory(), dir))							
                        .Add ("dump-xmls:", v => cfg.DumpXmls = parseBoolOption(v))
                        .Add ("out-xml-dir=", dir => cfg.XmlDir = Path.Combine(Directory.GetCurrentDirectory(), dir))
                        .Add ("out-java-dir=", dir => cfg.OutDir = dir)
                        .Add ("cheat-dir=", dir => cfg.CheatDir = dir)
                        .Add ("net-templates-dir=", dirs => cfg.OptNetRoot.Add(mkDirectories(dirs)))
                        .Add ("ex-net-templates-dir=", dirs => cfg.OptExNetRoot.Add(mkDirectories(dirs)))
                        .Add ("net-schema-dir=", dirs => cfg.OptNetSchemaDir.Add(mkDirectories(dirs)))
                        .Add ("app-dir=", dirs => cfg.OptAppRoot.Add(mkDirectories(dirs)))
                        .Add ("ex-app-dir=", dirs => cfg.OptExAppRoot.Add(mkDirectories(dirs)))
                        .Add ("cs-dir=", dirs => cfg.OptCsDir.Add(mkDirectories(dirs)))
                        .Add ("ex-cs-dir=", dirs => cfg.OptExCsDir.Add(mkDirectories(dirs)))
                        .Add ("alt-translations=", alts => cfg.OptAltTranslations.Add(mkStrings(alts)))
                        .Add ("keep-parens:", v => cfg.TranslatorKeepParens = parseBoolOption(v))
                        .Add ("timestamp-files:", v => cfg.TranslatorAddTimeStamp = parseBoolOption(v))
                        .Add ("blanket-throw:", v => cfg.TranslatorBlanketThrow = parseBoolOption(v))
                        .Add ("exception-is-throwable:", v => cfg.TranslatorExceptionIsThrowable = parseBoolOption(v))
                        .Add ("make-javadoc-comments:", v => cfg.TranslatorMakeJavadocComments = parseBoolOption(v))
                        .Add ("make-java-naming-conventions:", v => cfg.TranslatorMakeJavaNamingConventions = parseBoolOption(v))
                        .Add ("experimental-enums-to-numeric-consts:", v => cfg.EnumsAsNumericConsts = parseBoolOption(v))
                        .Add ("experimental-unsigned-to-signed:", v => cfg.UnsignedNumbersToSigned = parseBoolOption(v))
                        .Add ("experimental-unsigned-to-bigger-signed:", v => cfg.UnsignedNumbersToBiggerSignedNumbers = parseBoolOption(v))
                        .Add ("experimental-transforms:", v => cfg.ExperimentalTransforms = parseBoolOption(v))
                        .Add ("internal-isjavaish:", v => cfg.InternalIsJavaish = parseBoolOption(v))
                        ;
					
                    // Final argument is translation target
                    foreach (string s in p.Parse (args))
                    {
                       if (s.StartsWith("-") || s.StartsWith("/"))
                       {
                          Console.WriteLine("ERROR: Unrecognized Option: " + s);
                          doEarlyExit = true;
                       }
                       else
                       {
                          cfg.OptCsDir.Add(mkDirectories(s));
                       }
                    }

                    if (cfg.Verbosity > 0) showVersion();

                    if (doHelp) showUsage();
                    if (!doEarlyExit && (cfg.CsDir == null || cfg.CsDir.Count == 0)) {
                        // No work
                       Console.WriteLine("Please specify files to translate with -cs-dir option");
                       doEarlyExit = true;
                    }

                    if (doEarlyExit)
                    {
                        Environment.Exit(0);
                    }

                    AppEnv = new DirectoryHT<TypeRepTemplate>();
                    if (cfg.TranslatorMakeJavaNamingConventions)
                    {
                       // Search lowerCamelCase
                       AppEnv.Alts.Add("LCC");                       
                    }
                    foreach (string alt in cfg.AltTranslations)
                    {
                       AppEnv.Alts.Add(alt);                       
                    }

                    // Load .Net templates
                    // Do we have schemas for the templates?
                    if (cfg.NetSchemaDir.Count == 0)
                    {
                       // By default look for schemas in net dirs
                       cfg.NetSchemaDir = new List<string>(cfg.NetRoot);
                    }

                    // Comment out for now.  I don't see how to wrie an xsd file that will allow elements to appear in any order
                    // foreach (string schemadir in cfg.NetSchemaDir)
                    //   doFile(schemadir, ".xsd", addNetSchema, null);

                    foreach (string r in cfg.NetRoot)
                        doFile(r, ".xml", addNetTranslation, cfg.ExNetRoot);

                    // Load Application Class Signatures (i.e. generate templates)
                    if (cfg.AppRoot.Count == 0)
                    {
                        // By default translation target is application root
                       foreach (string s in cfg.CsDir)
                       {
                          cfg.AppRoot.Add(s);
                       }
                    }
                    foreach (string r in cfg.AppRoot)
                        doFile(r, ".cs", addAppSigTranslation, cfg.ExAppRoot); // parse it
                    if (cfg.DumpEnums) {
                        enumXmlWriter = new XmlTextWriter(cfg.EnumDir, System.Text.Encoding.UTF8);
                        enumXmlWriter.WriteStartElement("enums");
                    }
                    if (cfg.DumpXmls)
                    {
                        // Get package name and convert to directory name
                        foreach (KeyValuePair<string,TypeRepTemplate> de in AppEnv)
                        {
                            String xmlFName = Path.Combine(cfg.XmlDir,
                                                           ((string)de.Key).Replace('.', Path.DirectorySeparatorChar) + ".xml");
                            String xmlFDir = Path.GetDirectoryName(xmlFName);
                            if (!Directory.Exists(xmlFDir))
                            {
                                Directory.CreateDirectory(xmlFDir);
                            }
                            XmlSerializer s = new XmlSerializer(de.Value.GetType(), CS2JConstants.TranslationTemplateNamespace);
                            TextWriter w = new StreamWriter(xmlFName);
                            s.Serialize(w, de.Value);
                            w.Close();
                        }
                    }

                    // load in T.stg template group, put in templates variable
                    string templateLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("templates", "java.stg"));
                    if (File.Exists(templateLocation)) {
                       TextReader groupFileR = new StreamReader(templateLocation);
                       templates = new StringTemplateGroup(groupFileR);
                       groupFileR.Close();
                    }
                    else {
                        templates = new StringTemplateGroup(new StringReader(Templates.JavaTemplateGroup));
                    }

                    foreach (string r in cfg.CsDir)
                        doFile(r, ".cs", translateFile, cfg.ExCsDir); // translate it

                    if (cfg.DebugLevel >= 1 && partialTypes.Count > 0) Console.Out.WriteLine("Writing out collected partial types");
                    foreach (KeyValuePair<string, ClassDescriptorSerialized> entry in partialTypes)
                       emitPartialType(entry.Key, entry.Value);

                    if (cfg.DumpEnums)
                    {
                        enumXmlWriter.WriteEndElement();
                        enumXmlWriter.Close();
                    }
                }
                else
                {
                    showUsage();
                }
            }
            catch (System.Exception e)
            {
                Console.Error.WriteLine("exception: " + e);
                Console.Error.WriteLine(e.StackTrace); // so we can get stack trace
            }
            double elapsedTime = ((DateTime.Now.Ticks - startTime) / TimeSpan.TicksPerMillisecond) / 1000.0;
            if (cfg.Verbosity >= 1)
            {
                System.Console.Out.WriteLine("Total run time was {0} seconds.", elapsedTime);
            }
        }
Esempio n. 25
0
 public static StringTemplate LoadTemplate(string name)
 {
     StringTemplateGroup templateGroup = new StringTemplateGroup ("MG", templatePath, typeof(DefaultTemplateLexer));
     return templateGroup.GetInstanceOf (name);
 }
        /// <summary>
        /// Constructs a new Domain renderer object.
        /// </summary>
        private DomainRenderer()
        {
            log = LogManager.GetLogger(typeof(DomainRenderer));

            CommonGroupLoader loader = null;

            string location = null;

            if (ConfigurationManager.AppSettings[RELATIVE_CONFIG].Equals("true"))
            {
                location = Path.GetDirectoryName(Assembly.GetAssembly(GetType()).CodeBase);
                if (location.IndexOf("file:") == 0)
                {
                    location = location.Substring(6);
                }
                log.InfoFormat("Obtaining Templates from the Relative location: {0}", location);
            }
            else
            {
                location = ConfigurationManager.AppSettings[TEMPLATE_LOCATION_CONFIG];
                log.InfoFormat("Obtaining Templates from this location: {0}", location);
            }

            loader = new CommonGroupLoader(new ConsoleErrorListener(), location);

            StringTemplateGroup.RegisterGroupLoader(loader);

            baseTemplateGroup = StringTemplateGroup.LoadGroup(BASE_TEMPLATES_GROUP);

            templateGroups = new Dictionary<string, StringTemplateGroup>();

            dateRenderer = new DateRenderer();
        }