1
0
mirror of https://github.com/twiglet/cs2j.git synced 2025-01-18 13:15:17 +01:00

Add template file to control Java pretty printing

This commit is contained in:
Kevin Glynn 2010-11-10 19:03:09 +01:00
parent e914af9031
commit 16babbd494
8 changed files with 165 additions and 43 deletions

Binary file not shown.

View File

@ -7,6 +7,8 @@ using Antlr.Runtime.Tree;
using Antlr.Runtime;
using System.Xml.Serialization;
using Antlr.StringTemplate;
using NDesk.Options;
using RusticiSoftware.Translator.Utils;
@ -20,7 +22,8 @@ namespace RusticiSoftware.Translator.CSharp
private const string VERSION = "2009.1.1.x";
private static DirectoryHT<TypeRepTemplate> AppEnv { get; set; }
private static CS2JSettings cfg = new CS2JSettings();
private static StringTemplateGroup templates = null;
public delegate void FileProcessor(string fName);
private static void showVersion()
@ -131,6 +134,16 @@ namespace RusticiSoftware.Translator.CSharp
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));
}
doFile(remArgs[0], ".cs", translateFile, cfg.Exclude); // parse it
if (cfg.DumpEnums)
{
@ -260,6 +273,7 @@ namespace RusticiSoftware.Translator.CSharp
if (csTree != null)
{
// Make java compilation units from C# file
Dictionary<string, CommonTree> cus = new Dictionary<string, CommonTree>();
JavaMaker javaMaker = new JavaMaker(csTree);
javaMaker.Filename = fullName;
@ -267,7 +281,39 @@ namespace RusticiSoftware.Translator.CSharp
JavaMaker.compilation_unit_return java = javaMaker.compilation_unit(cfg, cus);
foreach (KeyValuePair<string, CommonTree> package in cus) {
Console.WriteLine (package.Key);
string claName = package.Key.Substring(package.Key.LastIndexOf('.')+1);
string nsDir = package.Key.Substring(0,package.Key.LastIndexOf('.')).Replace('.', Path.DirectorySeparatorChar);
if (cfg.CheatDir != "")
{
String ignoreMarker = Path.Combine(cfg.CheatDir, Path.Combine(nsDir, claName + ".none"));
if (File.Exists(ignoreMarker))
{
// Don't generate this class
continue;
}
}
// Make sure parent directory exists
String javaFDir = Path.Combine(cfg.OutDir, nsDir);
String javaFName = Path.Combine(javaFDir, claName + ".java");
if (!Directory.Exists(javaFDir))
{
Directory.CreateDirectory(javaFDir);
}
if (cfg.CheatDir != "")
{
String cheatFile = Path.Combine(cfg.CheatDir, Path.Combine(nsDir, claName + ".java"));
if (File.Exists(cheatFile))
{
// the old switcheroo
File.Copy(cheatFile, javaFName,true);
continue;
}
}
// Translate calls to .Net to calls to Java libraries
CommonTreeNodeStream javaSyntaxNodes = new CommonTreeNodeStream(package.Value);
javaSyntaxNodes.TokenStream = csTree.TokenStream;
@ -280,11 +326,15 @@ namespace RusticiSoftware.Translator.CSharp
CommonTreeNodeStream javaCompilationUnitNodes = new CommonTreeNodeStream(javaCompilationUnit.Tree);
javaCompilationUnitNodes.TokenStream = csTree.TokenStream;
// Pretty print java parse tree as text
JavaPrettyPrint outputMaker = new JavaPrettyPrint(javaCompilationUnitNodes);
outputMaker.Filename = fullName;
outputMaker.TraceDestination = Console.Error;
outputMaker.TemplateLib = templates;
outputMaker.type_declaration();
StreamWriter javaW = new StreamWriter(javaFName);
javaW.Write(outputMaker.type_declaration().ToString());
javaW.Close();
}
// ITreeNodeStream javaTree = java.Tree;
}

View File

@ -15,6 +15,12 @@ options {
output=AST;
}
// A scope to keep track of the namespaces available at any point in the program
scope NSContext {
int filler;
string currentNS;
}
@namespace { RusticiSoftware.Translator.CSharp }
@header
@ -26,6 +32,11 @@ options {
{
private IDictionary<string, CommonTree> CUs { get; set; }
protected string ParentNameSpace {
get {
return ((NSContext_scope)$NSContext.ToArray()[$NSContext.Count-2]).currentNS;
}
}
}
/********************************************************************************************
@ -35,14 +46,23 @@ options {
///////////////////////////////////////////////////////
compilation_unit[CS2JSettings inCfg, IDictionary<string, CommonTree> inCus /*, DirectoryHT<TypeRepTemplate> inAppEnv*/]
scope NSContext;
@init {
CUs = inCus;
$NSContext::currentNS = "";
}
:
namespace_body;
namespace_declaration:
'namespace' qualified_identifier namespace_block ';'? ;
namespace_declaration
scope NSContext;
:
'namespace' qi=qualified_identifier
{
// extend parent namespace
$NSContext::currentNS = this.ParentNameSpace + $qi.thetext;
}
namespace_block ';'? ;
namespace_block:
'{' namespace_body '}' ;
namespace_body:
@ -50,7 +70,7 @@ namespace_body:
extern_alias_directives:
extern_alias_directive+ ;
extern_alias_directive:
'extern' 'alias' identifier ';' ;
e='extern' 'alias' i=identifier ';' { Warning($e.line, "[UNSUPPORTED] External Alias " + $i.text); } ;
using_directives:
using_directive+ ;
using_directive:
@ -68,19 +88,20 @@ namespace_member_declaration:
// type_declaration is only called at the top level, so each of the types declared
// here will become a Java compilation unit (and go to its own file)
type_declaration
@init { string ns = $NSContext::currentNS; }
:
('partial') => p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); }
(pc=class_declaration { CUs.Add($pc.name, $pc.tree); }
| ps=struct_declaration { CUs.Add($ps.name, $ps.tree); }
| pi=interface_declaration { CUs.Add($pi.name, $pi.tree); })
| c=class_declaration { CUs.Add($c.name, $c.tree); }
| s=struct_declaration { CUs.Add($s.name, $s.tree); }
| i=interface_declaration { CUs.Add($i.name, $i.tree); }
| e=enum_declaration { CUs.Add($e.name, $e.tree); }
| d=delegate_declaration { CUs.Add($d.name, $d.tree); } ;
(pc=class_declaration { CUs.Add(ns+"."+$pc.name, $pc.tree); }
| ps=struct_declaration { CUs.Add(ns+"."+$ps.name, $ps.tree); }
| pi=interface_declaration { CUs.Add(ns+"."+$pi.name, $pi.tree); })
| c=class_declaration { CUs.Add(ns+"."+$c.name, $c.tree); }
| s=struct_declaration { CUs.Add(ns+"."+$s.name, $s.tree); }
| i=interface_declaration { CUs.Add(ns+"."+$i.name, $i.tree); }
| e=enum_declaration { CUs.Add(ns+"."+$e.name, $e.tree); }
| d=delegate_declaration { CUs.Add(ns+"."+$d.name, $d.tree); } ;
// Identifiers
qualified_identifier:
identifier ('.' identifier)*;
qualified_identifier returns [string thetext]:
i1=identifier { $thetext = $i1.text; } ('.' ip=identifier { $thetext += "." + $ip.text; } )*;
namespace_name
: namespace_or_type_name ;
@ -92,10 +113,11 @@ modifier:
class_member_declaration:
attributes?
// TODO: Don't emit private
m=modifiers?
( 'const' type constant_declarators ';'
| event_declaration // 'event'
| 'partial' (method_declaration
| p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); } (method_declaration
| interface_declaration
| class_declaration
| struct_declaration)
@ -327,16 +349,18 @@ type_or_generic returns [string type, List<string> generic_arguments]
}:
(identifier generic_argument_list) => t=identifier ga=generic_argument_list { $generic_arguments = $ga.tyargs; }
| t=identifier ;
qid: // qualified_identifier v2
qid_start qid_part*
// keving: as far as I can see this is (<interfacename>.)?identifier (<tyargs>)? at lease for C# 3.0 and less.
qid returns [string name, List<String> tyargs]: // qualified_identifier v2
qid_start qid_part* { $name=$qid_start.name; $tyargs = $qid_start.tyargs; }
;
qid_start:
predefined_type
| (identifier generic_argument_list) => identifier generic_argument_list
qid_start returns [string name, List<String> tyargs]:
predefined_type { $name = $predefined_type.thetext; }
| (identifier generic_argument_list) => identifier generic_argument_list { $name = $identifier.text; $tyargs = $generic_argument_list.tyargs; }
// | 'this'
// | 'base'
| identifier ('::' identifier)?
| literal
| i1=identifier { $name = $i1.text; } ('::' inext=identifier { $name+="::" + $inext.text; })?
| literal { $name = $literal.text; }
; // 0.ToString() is legal
@ -362,7 +386,6 @@ type returns [string thetext]:
| (p3=predefined_type { $thetext = $p3.thetext; } | tn3=type_name { $thetext = $tn3.thetext; })
| 'void' { $thetext = "System.Void"; } ('*' { $thetext += "*"; })+
;
non_nullable_type:
(predefined_type | type_name)
( rank_specifiers '*'*
@ -621,8 +644,8 @@ method_header:
member_name '(' formal_parameter_list? ')' type_parameter_constraints_clauses? ;
method_body:
block ;
member_name:
qid ; // IInterface<int>.Method logic added.
member_name returns [string name, List<String> tyargs]:
qid { $name = $qid.name; $tyargs = $qid.tyargs; } ; // IInterface<int>.Method logic added.
///////////////////////////////////////////////////////
property_declaration:
@ -683,10 +706,13 @@ delegate_declaration returns [string name]:
delegate_modifiers:
modifier+ ;
// 4.0
variant_generic_parameter_list:
'<' variant_type_parameters '>' ;
variant_type_parameters:
variant_type_variable_name (',' variant_type_variable_name)* ;
variant_generic_parameter_list returns [List<string> tyargs]
@init {
$tyargs = new List<string>();
}:
'<' variant_type_parameters[$tyargs] '>' ;
variant_type_parameters [List<String> tyargs]:
v1=variant_type_variable_name { tyargs.Add($v1.text); } (',' vn=variant_type_variable_name { tyargs.Add($vn.text); })* ;
variant_type_variable_name:
attributes? variance_annotation? type_variable_name ;
variance_annotation:
@ -794,7 +820,7 @@ struct_member_declaration:
attributes? m=modifiers?
( 'const' type constant_declarators ';'
| event_declaration // 'event'
| 'partial' (method_declaration
| p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); } (method_declaration
| interface_declaration
| class_declaration
| struct_declaration)

View File

@ -5,7 +5,7 @@ options {
ASTLabelType=CommonTree;
language=CSharp2;
superClass='RusticiSoftware.Translator.CSharp.CommonWalker';
//output=template;
output=template;
}
@namespace { RusticiSoftware.Translator.CSharp }
@ -17,20 +17,19 @@ options {
@members
{
protected bool is_class_modifier()
{
return false;
}
}
compilation_unit:
namespace_body[true];
package;
package:
(PACKAGE string type_declaration) ->
package(now = {DateTime.Now}, includeDate = {true}, packageName = {$string}, type = {$type_declaration});
namespace_declaration:
'namespace' qualified_identifier namespace_block ';'? ;
namespace_block:
'{' namespace_body[false] '}' ;
namespace_body[bool bGlobal]:
'{' namespace_body '}' ;
namespace_body:
extern_alias_directives? using_directives? global_attributes? namespace_member_declarations? ;
extern_alias_directives:
extern_alias_directive+ ;
@ -51,7 +50,7 @@ namespace_member_declaration:
namespace_declaration
| attributes? modifiers? type_declaration ;
type_declaration:
('partial') => 'partial' (class_declaration
('partial') => 'partial' (class_declaration
| struct_declaration
| interface_declaration)
| class_declaration

View File

@ -13,8 +13,6 @@ options {
ASTLabelType=CommonTree;
language=CSharp2;
superClass='RusticiSoftware.Translator.CSharp.CommonWalker';
//output=AST;
//backtrack=true;
}
// A scope to keep track of the namespaces available at any point in the program

View File

@ -0,0 +1,16 @@
using System;
namespace RusticiSoftware.Translator.CSharp
{
public class Templates
{
private static string _javaTemplateGroup = @"
Nothing to see here
";
public static string JavaTemplateGroup { get
{ return _javaTemplateGroup; }
}
}
}

View File

@ -0,0 +1,24 @@
group JavaPrettyPrintTemplates;
itsmine(now, includeDate) ::= <<
//
//
// This file was translated from C# to Java by CS2J (http://www.cs2j.com).
//
// This code is to be used for evaluation of the CS2J tool ONLY.
//
// For more information about CS2J please contact cs2jcontact@scorm.com
<if(includeDate)>
//
// Translated: <now><\n>
<endif>
//
>>
package(now, includeDate, packageName, type) ::= <<
<itsmine(now=now,includeDate=includeDate)>
package <packageName>;
<type>
>>

View File

@ -69,6 +69,7 @@
<Compile Include="CSharp\JavaMaker.cs" />
<Compile Include="CSharp\JavaPrettyPrint.cs" />
<Compile Include="CSharp\NetMaker.cs" />
<Compile Include="CSharp\Templates.cs" />
</ItemGroup>
<ItemGroup>
<None Include="CSharp\csCrawl.g" />
@ -125,5 +126,13 @@
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="antlr.runtime, Version=2.7.7.3, Culture=neutral, PublicKeyToken=d7701e059243744f">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\antlr.runtime.dll</HintPath>
</Reference>
<Reference Include="StringTemplate, Version=3.0.1.6846, Culture=neutral, PublicKeyToken=beee492b52c41e85">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\StringTemplate.dll</HintPath>
</Reference>
</ItemGroup>
</Project>