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 Antlr.Runtime;
using System.Xml.Serialization; using System.Xml.Serialization;
using Antlr.StringTemplate;
using NDesk.Options; using NDesk.Options;
using RusticiSoftware.Translator.Utils; using RusticiSoftware.Translator.Utils;
@ -20,7 +22,8 @@ namespace RusticiSoftware.Translator.CSharp
private const string VERSION = "2009.1.1.x"; private const string VERSION = "2009.1.1.x";
private static DirectoryHT<TypeRepTemplate> AppEnv { get; set; } private static DirectoryHT<TypeRepTemplate> AppEnv { get; set; }
private static CS2JSettings cfg = new CS2JSettings(); private static CS2JSettings cfg = new CS2JSettings();
private static StringTemplateGroup templates = null;
public delegate void FileProcessor(string fName); public delegate void FileProcessor(string fName);
private static void showVersion() private static void showVersion()
@ -131,6 +134,16 @@ namespace RusticiSoftware.Translator.CSharp
w.Close(); 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 doFile(remArgs[0], ".cs", translateFile, cfg.Exclude); // parse it
if (cfg.DumpEnums) if (cfg.DumpEnums)
{ {
@ -260,6 +273,7 @@ namespace RusticiSoftware.Translator.CSharp
if (csTree != null) if (csTree != null)
{ {
// Make java compilation units from C# file
Dictionary<string, CommonTree> cus = new Dictionary<string, CommonTree>(); Dictionary<string, CommonTree> cus = new Dictionary<string, CommonTree>();
JavaMaker javaMaker = new JavaMaker(csTree); JavaMaker javaMaker = new JavaMaker(csTree);
javaMaker.Filename = fullName; javaMaker.Filename = fullName;
@ -267,7 +281,39 @@ namespace RusticiSoftware.Translator.CSharp
JavaMaker.compilation_unit_return java = javaMaker.compilation_unit(cfg, cus); JavaMaker.compilation_unit_return java = javaMaker.compilation_unit(cfg, cus);
foreach (KeyValuePair<string, CommonTree> package in 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); CommonTreeNodeStream javaSyntaxNodes = new CommonTreeNodeStream(package.Value);
javaSyntaxNodes.TokenStream = csTree.TokenStream; javaSyntaxNodes.TokenStream = csTree.TokenStream;
@ -280,11 +326,15 @@ namespace RusticiSoftware.Translator.CSharp
CommonTreeNodeStream javaCompilationUnitNodes = new CommonTreeNodeStream(javaCompilationUnit.Tree); CommonTreeNodeStream javaCompilationUnitNodes = new CommonTreeNodeStream(javaCompilationUnit.Tree);
javaCompilationUnitNodes.TokenStream = csTree.TokenStream; javaCompilationUnitNodes.TokenStream = csTree.TokenStream;
// Pretty print java parse tree as text
JavaPrettyPrint outputMaker = new JavaPrettyPrint(javaCompilationUnitNodes); JavaPrettyPrint outputMaker = new JavaPrettyPrint(javaCompilationUnitNodes);
outputMaker.Filename = fullName; outputMaker.Filename = fullName;
outputMaker.TraceDestination = Console.Error; 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; // ITreeNodeStream javaTree = java.Tree;
} }

View File

@ -15,6 +15,12 @@ options {
output=AST; 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 } @namespace { RusticiSoftware.Translator.CSharp }
@header @header
@ -26,6 +32,11 @@ options {
{ {
private IDictionary<string, CommonTree> CUs { get; set; } 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*/] compilation_unit[CS2JSettings inCfg, IDictionary<string, CommonTree> inCus /*, DirectoryHT<TypeRepTemplate> inAppEnv*/]
scope NSContext;
@init { @init {
CUs = inCus; CUs = inCus;
$NSContext::currentNS = "";
} }
: :
namespace_body; namespace_body;
namespace_declaration: namespace_declaration
'namespace' qualified_identifier namespace_block ';'? ; scope NSContext;
:
'namespace' qi=qualified_identifier
{
// extend parent namespace
$NSContext::currentNS = this.ParentNameSpace + $qi.thetext;
}
namespace_block ';'? ;
namespace_block: namespace_block:
'{' namespace_body '}' ; '{' namespace_body '}' ;
namespace_body: namespace_body:
@ -50,7 +70,7 @@ namespace_body:
extern_alias_directives: extern_alias_directives:
extern_alias_directive+ ; extern_alias_directive+ ;
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_directives:
using_directive+ ; using_directive+ ;
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 // 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) // here will become a Java compilation unit (and go to its own file)
type_declaration type_declaration
@init { string ns = $NSContext::currentNS; }
: :
('partial') => p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); } ('partial') => p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); }
(pc=class_declaration { CUs.Add($pc.name, $pc.tree); } (pc=class_declaration { CUs.Add(ns+"."+$pc.name, $pc.tree); }
| ps=struct_declaration { CUs.Add($ps.name, $ps.tree); } | ps=struct_declaration { CUs.Add(ns+"."+$ps.name, $ps.tree); }
| pi=interface_declaration { CUs.Add($pi.name, $pi.tree); }) | pi=interface_declaration { CUs.Add(ns+"."+$pi.name, $pi.tree); })
| c=class_declaration { CUs.Add($c.name, $c.tree); } | c=class_declaration { CUs.Add(ns+"."+$c.name, $c.tree); }
| s=struct_declaration { CUs.Add($s.name, $s.tree); } | s=struct_declaration { CUs.Add(ns+"."+$s.name, $s.tree); }
| i=interface_declaration { CUs.Add($i.name, $i.tree); } | i=interface_declaration { CUs.Add(ns+"."+$i.name, $i.tree); }
| e=enum_declaration { CUs.Add($e.name, $e.tree); } | e=enum_declaration { CUs.Add(ns+"."+$e.name, $e.tree); }
| d=delegate_declaration { CUs.Add($d.name, $d.tree); } ; | d=delegate_declaration { CUs.Add(ns+"."+$d.name, $d.tree); } ;
// Identifiers // Identifiers
qualified_identifier: qualified_identifier returns [string thetext]:
identifier ('.' identifier)*; i1=identifier { $thetext = $i1.text; } ('.' ip=identifier { $thetext += "." + $ip.text; } )*;
namespace_name namespace_name
: namespace_or_type_name ; : namespace_or_type_name ;
@ -92,10 +113,11 @@ modifier:
class_member_declaration: class_member_declaration:
attributes? attributes?
// TODO: Don't emit private
m=modifiers? m=modifiers?
( 'const' type constant_declarators ';' ( 'const' type constant_declarators ';'
| event_declaration // 'event' | event_declaration // 'event'
| 'partial' (method_declaration | p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); } (method_declaration
| interface_declaration | interface_declaration
| class_declaration | class_declaration
| struct_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; } (identifier generic_argument_list) => t=identifier ga=generic_argument_list { $generic_arguments = $ga.tyargs; }
| t=identifier ; | 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: qid_start returns [string name, List<String> tyargs]:
predefined_type predefined_type { $name = $predefined_type.thetext; }
| (identifier generic_argument_list) => identifier generic_argument_list | (identifier generic_argument_list) => identifier generic_argument_list { $name = $identifier.text; $tyargs = $generic_argument_list.tyargs; }
// | 'this' // | 'this'
// | 'base' // | 'base'
| identifier ('::' identifier)? | i1=identifier { $name = $i1.text; } ('::' inext=identifier { $name+="::" + $inext.text; })?
| literal | literal { $name = $literal.text; }
; // 0.ToString() is legal ; // 0.ToString() is legal
@ -362,7 +386,6 @@ type returns [string thetext]:
| (p3=predefined_type { $thetext = $p3.thetext; } | tn3=type_name { $thetext = $tn3.thetext; }) | (p3=predefined_type { $thetext = $p3.thetext; } | tn3=type_name { $thetext = $tn3.thetext; })
| 'void' { $thetext = "System.Void"; } ('*' { $thetext += "*"; })+ | 'void' { $thetext = "System.Void"; } ('*' { $thetext += "*"; })+
; ;
non_nullable_type: non_nullable_type:
(predefined_type | type_name) (predefined_type | type_name)
( rank_specifiers '*'* ( rank_specifiers '*'*
@ -621,8 +644,8 @@ method_header:
member_name '(' formal_parameter_list? ')' type_parameter_constraints_clauses? ; member_name '(' formal_parameter_list? ')' type_parameter_constraints_clauses? ;
method_body: method_body:
block ; block ;
member_name: member_name returns [string name, List<String> tyargs]:
qid ; // IInterface<int>.Method logic added. qid { $name = $qid.name; $tyargs = $qid.tyargs; } ; // IInterface<int>.Method logic added.
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
property_declaration: property_declaration:
@ -683,10 +706,13 @@ delegate_declaration returns [string name]:
delegate_modifiers: delegate_modifiers:
modifier+ ; modifier+ ;
// 4.0 // 4.0
variant_generic_parameter_list: variant_generic_parameter_list returns [List<string> tyargs]
'<' variant_type_parameters '>' ; @init {
variant_type_parameters: $tyargs = new List<string>();
variant_type_variable_name (',' variant_type_variable_name)* ; }:
'<' 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: variant_type_variable_name:
attributes? variance_annotation? type_variable_name ; attributes? variance_annotation? type_variable_name ;
variance_annotation: variance_annotation:
@ -794,7 +820,7 @@ struct_member_declaration:
attributes? m=modifiers? attributes? m=modifiers?
( 'const' type constant_declarators ';' ( 'const' type constant_declarators ';'
| event_declaration // 'event' | event_declaration // 'event'
| 'partial' (method_declaration | p='partial' { Warning($p.line, "[UNSUPPORTED] 'partial' definition"); } (method_declaration
| interface_declaration | interface_declaration
| class_declaration | class_declaration
| struct_declaration) | struct_declaration)

View File

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

View File

@ -13,8 +13,6 @@ options {
ASTLabelType=CommonTree; ASTLabelType=CommonTree;
language=CSharp2; language=CSharp2;
superClass='RusticiSoftware.Translator.CSharp.CommonWalker'; superClass='RusticiSoftware.Translator.CSharp.CommonWalker';
//output=AST;
//backtrack=true;
} }
// A scope to keep track of the namespaces available at any point in the program // 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\JavaMaker.cs" />
<Compile Include="CSharp\JavaPrettyPrint.cs" /> <Compile Include="CSharp\JavaPrettyPrint.cs" />
<Compile Include="CSharp\NetMaker.cs" /> <Compile Include="CSharp\NetMaker.cs" />
<Compile Include="CSharp\Templates.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="CSharp\csCrawl.g" /> <None Include="CSharp\csCrawl.g" />
@ -125,5 +126,13 @@
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <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> </ItemGroup>
</Project> </Project>