1. 程式人生 > >程式碼翻譯嘗試-使用Roaster解析和生成Java原始碼 2018-09-13

程式碼翻譯嘗試-使用Roaster解析和生成Java原始碼 2018-09-13

此文是前文使用現有線上翻譯服務進行程式碼翻譯的體驗的程式語言方面第二點的一個嘗試. 參考Which framework to generate source code ? - Cleancode and Refactoring, 選了一個綜合代價看來最小的, forge/roaster, 因為它同時具備解析和生成兩方面功能.

初步漢化後代碼效果如下(尚未有語法高亮, 僅作演示用. 之後的線上翻譯結果也是同樣處理):

package com.company.example;

import java.io.Serializable;

public classimplements
Serializable { private static final long serialVersionUID = 1L; private final 整型 號; private 字串 全名; public 整型 get號() { return; } public 字串 get全名() { return 全名; } public void set全名(字串 全名) { this.全名 = 全名; } public(java.lang.Integer id) { this.id = id; } }

實現的原始碼在: https://github.com/program-in-chinese/java_code_translator/blob/8c038261bd797d9738de182f3e0f8ac111402704/src/main/java/com/codeinchinese/code_translator/翻譯Java程式碼.java

相關實現比較簡單. 因為側重程式碼解析生成, 翻譯部分最簡化(採用純對映表):

  static Map<String, String> 字典 = new HashMap<>();
  static {
    字典.put("id", "號");
    字典.put("fullName", "全名");
    字典.put("getId", "取號");

    字典.put("Integer", "整型");
    字典.put("String", "字串");

    字典.put("Person", "人");
  }

  public static
void main(String[] 引數) throws Exception { String 原始碼 = 檔案功用.取原始檔文字("測試.java"); JavaClassSource 分析結果 = Roaster.parse(JavaClassSource.class, 原始碼); // 漢化類名 分析結果.setName(查詞(分析結果.getName())); // 漢化Bean屬性名, 以及屬性的型別名 for (PropertySource<JavaClassSource> 某屬性 : 分析結果.getProperties()) { String 屬性名 = 某屬性.getName(); 某屬性.setName(查詞(屬性名)); String 屬性型別名 = 某屬性.getType().getName(); 某屬性.setType(查詞(屬性型別名)); } System.out.println(分析結果); } private static String 查詞(String 英文) { return 字典.containsKey(英文) ? 字典.get(英文) : 英文; }

Roaster一大缺陷是, 還不支援對方法內容的解析: ROASTER-1: Java Statement Fluent Model by sotty · Pull Request #27 · forge/roaster 貌似主創最近不很活躍, 很可能需要另闢蹊徑.

順便把原始碼用線上翻譯服務翻譯一下進行比較.

谷歌幾乎沒有翻譯:

package com.company.example;

import java.io.Serializable;

public class Person實現Serializable {

     private static final long serialVersionUID = 1L;
     private final Integer id;
     private String fullName;

     public Integer getId(){
         返回id;
    }

     public String getFullName(){
         return fullName;
    }

     public void setFullName(String fullName){
         this.fullName = fullName;
    }

     public Person(java.lang.Integer id){
         this.id = id;
    }
}

百度改變原始碼太大:

包裝公司。
匯入JavaIO.SerialCalab化;
公共類人謂詞可序列化{
私有靜態最終的長序列化版本UID=1L;
私有最終整數ID;
私有字串全名;
公共整數gTiID()
序列標識;
}
公共字串GETFuleNAMEL()
返回全名;
}
公共空隙設定FULL NULL(String FulnNeX){
全名=全名;
}
公共人(java.郎.整數ID){
這個ID=ID;
}
}

個人感覺即使是這樣初步的翻譯, 也是有優勢的. 至於程式語言關鍵詞不翻譯, 尚不是致命問題, 畢竟下面打算與英漢詞典API結合一下試試(這裡有一點初步嘗試, 對釋義的選取還需改進). 如效果還可以接受就上線做一下內測.