Coding Style

Phase 1
Eclipse Format
Comment for MigrationTool.java

git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@1869 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
alfred
2006-10-31 02:27:39 +00:00
parent 8aaf5a0d13
commit 71f30e5184
16 changed files with 3272 additions and 2736 deletions

View File

@ -12,219 +12,244 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.io.*; import java.io.BufferedReader;
import java.util.regex.*; import java.io.BufferedWriter;
import java.util.*; import java.io.File;
import java.lang.reflect.*; import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Common { public final class Common {
public static final int BOTH = 0; public static final int BOTH = 0;
public static final int FILE = 1;
public static final int DIR = 2;
public static final String STRSEPARATER = "(.*)\\\\([^\\\\]*)"; public static final int FILE = 1;
public static final Pattern PTNSEPARATER = Pattern.compile("(.*)\\\\([^\\\\]*)");
//-------------------------------------regex------------------------------------------// public static final int DIR = 2;
public static final String replaceAll(String line, Pattern ptn, String des) { public static final String STRSEPARATER = "(.*)\\\\([^\\\\]*)";
Matcher mtr = ptn.matcher(line);
if (mtr.find()) { public static final Pattern PTNSEPARATER = Pattern
return mtr.replaceAll(des); .compile("(.*)\\\\([^\\\\]*)");
}
return line; // -------------------------------------regex------------------------------------------//
}
public static final boolean find (String line, String regex) { public static final String replaceAll(String line, Pattern ptn, String des) {
Pattern ptn = Pattern.compile(regex); Matcher mtr = ptn.matcher(line);
return ptn.matcher (line).find (); if (mtr.find()) {
} return mtr.replaceAll(des);
//-------------------------------------regex------------------------------------------// }
//-----------------------------------file&string---------------------------------------// return line;
}
public static final String file2string(String filename) throws Exception { public static final boolean find(String line, String regex) {
BufferedReader rd = new BufferedReader(new FileReader(filename)); Pattern ptn = Pattern.compile(regex);
StringBuffer wholefile = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
wholefile.append(line + "\n");
}
rd.close();
return wholefile.toString();
}
public static final void string2file(String content, String filename) throws Exception { return ptn.matcher(line).find();
ensureDir(filename); }
PrintWriter outfile = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
outfile.append(content);
outfile.flush();
outfile.close();
}
public static final void fileCopy(String src, String des) throws Exception { // -------------------------------------regex------------------------------------------//
string2file(file2string(src), des);
}
//-----------------------------------file&string---------------------------------------// // -----------------------------------file&string---------------------------------------//
//--------------------------------------dir--------------------------------------------// public static final String file2string(String filename) throws Exception {
/* BufferedReader rd = new BufferedReader(new FileReader(filename));
public static final HashSet<String> walkDir(String path, int mode) throws Exception { StringBuffer wholefile = new StringBuffer();
HashSet<String> pathlist = new HashSet<String>(); String line;
Common.toDoAll(path, Common.class.getMethod("walkDir", String.class), null, null, mode); while ((line = rd.readLine()) != null) {
return pathlist; wholefile.append(line + "\n");
} }
*/ rd.close();
public static final void ensureDir(String objFileWhole) { return wholefile.toString();
File tempdir; }
Matcher mtrseparate = PTNSEPARATER.matcher(objFileWhole);
if (mtrseparate.find()) {
tempdir = new File(mtrseparate.group(1));
if (!tempdir.exists()) tempdir.mkdirs();
}
}
public static final void deleteDir(String objFileWhole) { public static final void string2file(String content, String filename)
String[] list = new File(objFileWhole).list(); throws Exception {
File temp; ensureDir(filename);
for (int i = 0 ; i < list.length ; i++) { PrintWriter outfile = new PrintWriter(new BufferedWriter(
temp = new File(objFileWhole + File.separator + list[i]); new FileWriter(filename)));
if (temp.isDirectory()) { outfile.append(content);
deleteDir(objFileWhole + File.separator + list[i]); outfile.flush();
} else { outfile.close();
temp.delete(); }
}
}
new File(objFileWhole).delete();
}
public static final String dirCopy_(String src) throws Exception { public static final void fileCopy(String src, String des) throws Exception {
Matcher mtrseparate = Common.PTNSEPARATER.matcher(src); string2file(file2string(src), des);
if (mtrseparate.find()) { }
dirCopy(src, mtrseparate.group(1) + File.separator + "_" + mtrseparate.group(2));
}
return mtrseparate.group(1) + File.separator + "_" + mtrseparate.group(2);
}
public static final void dirCopy(String src, String des) throws Exception { // -----------------------------------file&string---------------------------------------//
String[] list = new File(src).list();
File test;
ensureDir(des); // --------------------------------------dir--------------------------------------------//
for (int i = 0 ; i < list.length ; i++) { /*
test = new File(src + File.separator + list[i]); * public static final HashSet<String> walkDir(String path, int mode)
if (test.isDirectory()) { * throws Exception { HashSet<String> pathlist = new HashSet<String>();
dirCopy(src + File.separator + list[i], des + File.separator + list[i]); * Common.toDoAll(path, Common.class.getMethod("walkDir", String.class),
} else { * null, null, mode); return pathlist; }
//ensureDir(des + File.separator + list[i]); */
string2file(file2string(src + File.separator + list[i]), des + File.separator + list[i]); public static final void ensureDir(String objFileWhole) {
} File tempdir;
} Matcher mtrseparate = PTNSEPARATER.matcher(objFileWhole);
} if (mtrseparate.find()) {
tempdir = new File(mtrseparate.group(1));
if (!tempdir.exists())
tempdir.mkdirs();
}
}
public static final void oneLevelDirCopy(String src, String des, String type) throws Exception { public static final void deleteDir(String objFileWhole) {
String[] list = new File(src).list(); String[] list = new File(objFileWhole).list();
File temp;
for (int i = 0; i < list.length; i++) {
temp = new File(objFileWhole + File.separator + list[i]);
if (temp.isDirectory()) {
deleteDir(objFileWhole + File.separator + list[i]);
} else {
temp.delete();
}
}
new File(objFileWhole).delete();
}
ensureDir(des); public static final String dirCopy_(String src) throws Exception {
for (int i = 0; i < list.length; i++) { Matcher mtrseparate = Common.PTNSEPARATER.matcher(src);
if (list[i].contains(type)) { if (mtrseparate.find()) {
string2file(file2string(src + File.separator + list[i]), des + File.separator + list[i]); dirCopy(src, mtrseparate.group(1) + File.separator + "_"
} + mtrseparate.group(2));
} }
} return mtrseparate.group(1) + File.separator + "_"
+ mtrseparate.group(2);
}
//--------------------------------------dir--------------------------------------------// public static final void dirCopy(String src, String des) throws Exception {
String[] list = new File(src).list();
File test;
//-------------------------------like python walk-----------------------------------------// ensureDir(des);
for (int i = 0; i < list.length; i++) {
test = new File(src + File.separator + list[i]);
if (test.isDirectory()) {
dirCopy(src + File.separator + list[i], des + File.separator
+ list[i]);
} else {
// ensureDir(des + File.separator + list[i]);
string2file(file2string(src + File.separator + list[i]), des
+ File.separator + list[i]);
}
}
}
public static final void toDoAll(String path, Method md, Object obj, Object[] args, int type) throws Exception { public static final void oneLevelDirCopy(String src, String des, String type)
String[] list = new File(path).list(); throws Exception {
ArrayList<Object> _args = new ArrayList<Object>(); String[] list = new File(src).list();
_args.add(path); ensureDir(des);
if (args != null) { for (int i = 0; i < list.length; i++) {
for (int i = 0; i < args.length; i++) { if (list[i].contains(type)) {
_args.add(args[i]); string2file(file2string(src + File.separator + list[i]), des
} + File.separator + list[i]);
} }
}
}
if (type == DIR || type == BOTH) { // --------------------------------------dir--------------------------------------------//
md.invoke(obj, _args.toArray());
}
for (int i = 0 ; i < list.length ; i++) {
if (new File(path + File.separator + list[i]).isDirectory()) {
toDoAll(path + File.separator + list[i], md, obj, args, type);
} else {
if (type == FILE || type == BOTH) {
_args.set(0, path + File.separator + list[i]);
md.invoke(obj, _args.toArray());
}
}
}
}
public static final void toDoAll(Set<String> set, ForDoAll fda) throws Exception { // -------------------------------like python
Iterator<String> di = set.iterator(); // walk-----------------------------------------//
while (di.hasNext()) {
fda.run(di.next());
}
}
public static final void toDoAll(String path, ForDoAll fda, int type) throws Exception { // filter of file type can be done in toDo public static final void toDoAll(String path, Method md, Object obj,
String[] list = new File(path).list(); Object[] args, int type) throws Exception {
File test; String[] list = new File(path).list();
ArrayList<Object> _args = new ArrayList<Object>();
if (type == DIR || type == BOTH) { _args.add(path);
fda.run(path); if (args != null) {
} for (int i = 0; i < args.length; i++) {
for (int i = 0 ; i < list.length ; i++) { _args.add(args[i]);
test = new File(path + File.separator + list[i]); }
if (test.isDirectory()) { }
if (fda.filter(test)) {
toDoAll(path + File.separator + list[i], fda, type);
}
} else {
if (type == FILE || type == BOTH) {
fda.run(path + File.separator + list[i]);
}
}
}
}
public static interface ForDoAll { if (type == DIR || type == BOTH) {
public void run(String filepath) throws Exception; md.invoke(obj, _args.toArray());
}
for (int i = 0; i < list.length; i++) {
if (new File(path + File.separator + list[i]).isDirectory()) {
toDoAll(path + File.separator + list[i], md, obj, args, type);
} else {
if (type == FILE || type == BOTH) {
_args.set(0, path + File.separator + list[i]);
md.invoke(obj, _args.toArray());
}
}
}
}
public boolean filter(File dir); public static final void toDoAll(Set<String> set, ForDoAll fda)
} throws Exception {
Iterator<String> di = set.iterator();
while (di.hasNext()) {
fda.run(di.next());
}
}
public static abstract class Laplace { public static final void toDoAll(String path, ForDoAll fda, int type)
public void transform(String src, String des) throws Exception { throws Exception { // filter of file type can be done in toDo
Common.string2file(operation(Common.file2string(src)), des); String[] list = new File(path).list();
} File test;
public abstract String operation(String wholeline); if (type == DIR || type == BOTH) {
fda.run(path);
}
for (int i = 0; i < list.length; i++) {
test = new File(path + File.separator + list[i]);
if (test.isDirectory()) {
if (fda.filter(test)) {
toDoAll(path + File.separator + list[i], fda, type);
}
} else {
if (type == FILE || type == BOTH) {
fda.run(path + File.separator + list[i]);
}
}
}
}
public abstract boolean recognize(String filename); public static interface ForDoAll {
public void run(String filepath) throws Exception;
public abstract String namechange(String oldname); public boolean filter(File dir);
} }
public static interface Element { public static abstract class Laplace {
public void transform(String src, String des) throws Exception {
Common.string2file(operation(Common.file2string(src)), des);
}
// public int replace = 0; public abstract String operation(String wholeline);
// public int type = 1;
public String getReplace(String key); public abstract boolean recognize(String filename);
// public void getType(String key); public abstract String namechange(String oldname);
// }
// public void setReplace(int num);
//
// public void setType(int num);
} public static interface Element {
// public int replace = 0;
// public int type = 1;
public String getReplace(String key);
// public void getType(String key);
//
// public void setReplace(int num);
//
// public void setType(int num);
}
} }

View File

@ -12,196 +12,228 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.util.regex.*; import java.io.BufferedReader;
import java.io.*; import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Critic { public final class Critic {
public static final Pattern PTN_NEW_HEAD_COMMENT = Pattern.compile("^\\/\\*\\*.*?\\*\\*\\/",Pattern.DOTALL); public static final Pattern PTN_NEW_HEAD_COMMENT = Pattern.compile(
private static final Pattern ptnheadcomment = Pattern.compile("^\\/\\*\\+\\+(.*?)\\-\\-\\*\\/",Pattern.DOTALL); "^\\/\\*\\*.*?\\*\\*\\/", Pattern.DOTALL);
private static final Pattern ptnfunccomment = Pattern.compile("([\\};\\/\">]\\s*)([\\w\\s\\*]*?[_\\w][_\\w\\d]*\\s*\\([^\\)\\(]*\\)\\s*)\\/\\*\\+\\+(.*?)\\-\\-\\*\\/\\s*(.*?)(?=[\\{;])",Pattern.DOTALL); // find function with {;">/ , may be unsafe
//private static Pattern ptncommentstructure = Pattern.compile("\\/\\*\\+\\+\\s*Routine Description:\\s*(.*?)\\s*Arguments:\\s*(.*?)\\s*Returns:\\s*(.*?)\\s*\\-\\-\\*\\/",Pattern.DOTALL);
private static final Pattern ptncommentequation = Pattern.compile("([^\\s]*)\\s+-\\s+(.*)\\s*");
private static Matcher mtrcommentequation;
private static final Pattern ptnnewcomment = Pattern.compile("(\\s*@(param|retval)\\s+[^\\s]+)\\s+(.*)");
private static Matcher mtrnewcomment;
private static final int totallinelength = 82; private static final Pattern ptnheadcomment = Pattern.compile(
"^\\/\\*\\+\\+(.*?)\\-\\-\\*\\/", Pattern.DOTALL);
public static final void run(String filepath) throws Exception { private static final Pattern ptnfunccomment = Pattern
if (MigrationTool.doCritic) { // this is left here to set an example for future structure .compile(
critic(filepath); "([\\};\\/\">]\\s*)([\\w\\s\\*]*?[_\\w][_\\w\\d]*\\s*\\([^\\)\\(]*\\)\\s*)\\/\\*\\+\\+(.*?)\\-\\-\\*\\/\\s*(.*?)(?=[\\{;])",
} Pattern.DOTALL); // find function with {;">/ , may be
} // unsafe
private static final void critic(String filepath) throws Exception { // private static Pattern ptncommentstructure =
if (filepath.contains(".c") || filepath.contains(".h")) { // Pattern.compile("\\/\\*\\+\\+\\s*Routine
BufferedReader rd = null; // Description:\\s*(.*?)\\s*Arguments:\\s*(.*?)\\s*Returns:\\s*(.*?)\\s*\\-\\-\\*\\/",Pattern.DOTALL);
String line = null; private static final Pattern ptncommentequation = Pattern
StringBuffer templine = new StringBuffer(); .compile("([^\\s]*)\\s+-\\s+(.*)\\s*");
boolean incomment = false;
System.out.println("Criticing " + filepath); private static Matcher mtrcommentequation;
String wholeline = Common.file2string(filepath);
wholeline = wholeline.replaceAll("\t", " "); private static final Pattern ptnnewcomment = Pattern
wholeline = Common.replaceAll(wholeline, ptnheadcomment, "/** @file$1**/"); .compile("(\\s*@(param|retval)\\s+[^\\s]+)\\s+(.*)");
wholeline = Common.replaceAll(wholeline, ptnfunccomment, "$1\n/**$3\n**/\n$4$2");
//wholeline = Common.replaceAll(wholeline, ptncommentstructure, "/**\n#%\n$1\n%#\n#%%\n$2\n%%#\n#%%%\n$3\n%%%#\n**/");
// first scan private static Matcher mtrnewcomment;
boolean description = false;
boolean arguments = false;
boolean returns = false;
boolean inequation = false;
rd = new BufferedReader(new StringReader(wholeline));
while ((line = rd.readLine()) != null) {
if (line.matches("\\/\\*\\*")) {
incomment = true;
description = false;
arguments = false;
returns = false;
templine.append(line + "\n");
} else if (line.matches("\\*\\*\\/")) {
incomment = false;
templine.append("\n" + line + "\n");
} else if (incomment) {
if (line.contains("Routine Description:")) {
description = true;
arguments = false;
returns = false;
} else if (line.contains("Arguments:")) {
description = false;
arguments = true;
returns = false;
templine.append("\n");
} else if (line.contains("Returns:")) {
description = false;
arguments = false;
returns = true;
templine.append("\n");
} else if (description) {
if (line.trim().length() != 0) {
templine.append(" " + line.trim() + "\n");
}
} else if (arguments) {
mtrcommentequation = ptncommentequation.matcher(line);
if (mtrcommentequation.find()) {
inequation = true;
templine.append(" @param " + mtrcommentequation.group(1) + " " + mtrcommentequation.group(2) + "\n");
} else if (inequation && line.trim().length() == 0) {
inequation = false;
} else if (inequation && line.trim().length() != 0) {
templine.append("#%#%" + line + "\n");
} else {
if (line.trim().length() != 0) {
templine.append(" " + line.trim() + "\n");
}
}
} else if (returns) {
mtrcommentequation = ptncommentequation.matcher(line);
if (mtrcommentequation.find()) {
inequation = true;
templine.append(" @retval " + mtrcommentequation.group(1) + " " + mtrcommentequation.group(2) + "\n");
} else if (inequation && line.trim().length() == 0) {
inequation = false;
} else if (inequation && line.trim().length() != 0) {
templine.append("#%#%" + line + "\n");
} else {
if (line.trim().length() != 0) {
templine.append(" @return " + line.trim() + "\n");
}
}
}
} else {
templine.append(line + "\n");
}
}
wholeline = templine.toString();
wholeline = wholeline.replaceAll("\n#%#%\\s*", " ");
//
// secend scan private static final int totallinelength = 82;
int startmax = 0;
rd = new BufferedReader(new StringReader(wholeline));
while ((line = rd.readLine()) != null) {
if (line.matches("\\/\\*\\*")) {
incomment = true;
templine.append(line + "\n");
} else if (line.matches("\\*\\*\\/")) {
incomment = false;
templine.append(line + "\n");
} else if (incomment) {
mtrnewcomment = ptnnewcomment.matcher(line);
if (mtrnewcomment.find()) {
startmax = mtrnewcomment.group(1).length() > startmax ? mtrnewcomment.group(1).length() : startmax;
}
}
}
startmax++;
//
// third scan public static final void run(String filepath) throws Exception {
int n = 0; if (MigrationTool.doCritic) { // this is left here to set an example
String temp = null; // for future structure
String[] tempcont = null; critic(filepath);
int count = 0; }
templine = new StringBuffer(); }
rd = new BufferedReader(new StringReader(wholeline));
while ((line = rd.readLine()) != null) {
if (line.matches("\\/\\*\\*")) {
incomment = true;
templine.append(line + "\n");
} else if (line.matches("\\*\\*\\/")) {
incomment = false;
templine.append(line + "\n");
} else if (incomment) {
mtrnewcomment = ptnnewcomment.matcher(line);
if (mtrnewcomment.find()) {
n = startmax - mtrnewcomment.group(1).length();
templine.append(mtrnewcomment.group(1));
while (n-- >= 0) {
templine.append(" ");
}
temp = mtrnewcomment.group(3);
tempcont = temp.split(" "); // use \\s+ ?
count = 0; private static final void critic(String filepath) throws Exception {
for (int i = 0; i < tempcont.length; i++) { if (filepath.contains(".c") || filepath.contains(".h")) {
count += tempcont[i].length(); BufferedReader rd = null;
if (count <= (totallinelength - startmax)) { String line = null;
templine.append(tempcont[i] + " "); StringBuffer templine = new StringBuffer();
count += 1; boolean incomment = false;
} else {
templine.append("\n");
n = startmax;
while (n-- >= 0) {
templine.append(" ");
}
templine.append(tempcont[i] + " ");
count = tempcont[i].length() + 1;
}
}
templine.append("\n");
} else {
templine.append(line + "\n");
}
} else {
templine.append(line + "\n");
}
}
wholeline = templine.toString();
//
// Remove trailing blanks.
//
wholeline = wholeline.replaceAll (" +\n", "\n");
Common.string2file(wholeline, filepath);
}
}
public static final void fireAt(String path) throws Exception { System.out.println("Criticing " + filepath);
//Common.toDoAll(Common.dirCopy_(path), Critic.class.getMethod("critic", String.class), null, null, Common.FILE); String wholeline = Common.file2string(filepath);
Common.toDoAll(path, Critic.class.getMethod("run", String.class), null, null, Common.FILE);
//Common.toDoAll(Common.dirCopy_(path), critic, Common.FILE); wholeline = wholeline.replaceAll("\t", " ");
System.out.println("Critic Done"); wholeline = Common.replaceAll(wholeline, ptnheadcomment,
} "/** @file$1**/");
wholeline = Common.replaceAll(wholeline, ptnfunccomment,
"$1\n/**$3\n**/\n$4$2");
// wholeline = Common.replaceAll(wholeline, ptncommentstructure,
// "/**\n#%\n$1\n%#\n#%%\n$2\n%%#\n#%%%\n$3\n%%%#\n**/");
// first scan
boolean description = false;
boolean arguments = false;
boolean returns = false;
boolean inequation = false;
rd = new BufferedReader(new StringReader(wholeline));
while ((line = rd.readLine()) != null) {
if (line.matches("\\/\\*\\*")) {
incomment = true;
description = false;
arguments = false;
returns = false;
templine.append(line + "\n");
} else if (line.matches("\\*\\*\\/")) {
incomment = false;
templine.append("\n" + line + "\n");
} else if (incomment) {
if (line.contains("Routine Description:")) {
description = true;
arguments = false;
returns = false;
} else if (line.contains("Arguments:")) {
description = false;
arguments = true;
returns = false;
templine.append("\n");
} else if (line.contains("Returns:")) {
description = false;
arguments = false;
returns = true;
templine.append("\n");
} else if (description) {
if (line.trim().length() != 0) {
templine.append(" " + line.trim() + "\n");
}
} else if (arguments) {
mtrcommentequation = ptncommentequation.matcher(line);
if (mtrcommentequation.find()) {
inequation = true;
templine.append(" @param "
+ mtrcommentequation.group(1) + " "
+ mtrcommentequation.group(2) + "\n");
} else if (inequation && line.trim().length() == 0) {
inequation = false;
} else if (inequation && line.trim().length() != 0) {
templine.append("#%#%" + line + "\n");
} else {
if (line.trim().length() != 0) {
templine.append(" " + line.trim() + "\n");
}
}
} else if (returns) {
mtrcommentequation = ptncommentequation.matcher(line);
if (mtrcommentequation.find()) {
inequation = true;
templine.append(" @retval "
+ mtrcommentequation.group(1) + " "
+ mtrcommentequation.group(2) + "\n");
} else if (inequation && line.trim().length() == 0) {
inequation = false;
} else if (inequation && line.trim().length() != 0) {
templine.append("#%#%" + line + "\n");
} else {
if (line.trim().length() != 0) {
templine.append(" @return " + line.trim()
+ "\n");
}
}
}
} else {
templine.append(line + "\n");
}
}
wholeline = templine.toString();
wholeline = wholeline.replaceAll("\n#%#%\\s*", " ");
//
// secend scan
int startmax = 0;
rd = new BufferedReader(new StringReader(wholeline));
while ((line = rd.readLine()) != null) {
if (line.matches("\\/\\*\\*")) {
incomment = true;
templine.append(line + "\n");
} else if (line.matches("\\*\\*\\/")) {
incomment = false;
templine.append(line + "\n");
} else if (incomment) {
mtrnewcomment = ptnnewcomment.matcher(line);
if (mtrnewcomment.find()) {
startmax = mtrnewcomment.group(1).length() > startmax ? mtrnewcomment
.group(1).length()
: startmax;
}
}
}
startmax++;
//
// third scan
int n = 0;
String temp = null;
String[] tempcont = null;
int count = 0;
templine = new StringBuffer();
rd = new BufferedReader(new StringReader(wholeline));
while ((line = rd.readLine()) != null) {
if (line.matches("\\/\\*\\*")) {
incomment = true;
templine.append(line + "\n");
} else if (line.matches("\\*\\*\\/")) {
incomment = false;
templine.append(line + "\n");
} else if (incomment) {
mtrnewcomment = ptnnewcomment.matcher(line);
if (mtrnewcomment.find()) {
n = startmax - mtrnewcomment.group(1).length();
templine.append(mtrnewcomment.group(1));
while (n-- >= 0) {
templine.append(" ");
}
temp = mtrnewcomment.group(3);
tempcont = temp.split(" "); // use \\s+ ?
count = 0;
for (int i = 0; i < tempcont.length; i++) {
count += tempcont[i].length();
if (count <= (totallinelength - startmax)) {
templine.append(tempcont[i] + " ");
count += 1;
} else {
templine.append("\n");
n = startmax;
while (n-- >= 0) {
templine.append(" ");
}
templine.append(tempcont[i] + " ");
count = tempcont[i].length() + 1;
}
}
templine.append("\n");
} else {
templine.append(line + "\n");
}
} else {
templine.append(line + "\n");
}
}
wholeline = templine.toString();
//
// Remove trailing blanks.
//
wholeline = wholeline.replaceAll(" +\n", "\n");
Common.string2file(wholeline, filepath);
}
}
public static final void fireAt(String path) throws Exception {
// Common.toDoAll(Common.dirCopy_(path),
// Critic.class.getMethod("critic", String.class), null, null,
// Common.FILE);
Common.toDoAll(path, Critic.class.getMethod("run", String.class), null,
null, Common.FILE);
// Common.toDoAll(Common.dirCopy_(path), critic, Common.FILE);
System.out.println("Critic Done");
}
} }

View File

@ -12,442 +12,494 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.io.*; import java.io.BufferedReader;
import java.util.*; import java.io.File;
import java.util.regex.*; import java.io.FileReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlObject.Factory;
import org.tianocore.DbPathAndFilename; import org.tianocore.DbPathAndFilename;
import org.tianocore.FrameworkDatabaseDocument; import org.tianocore.FrameworkDatabaseDocument;
import org.tianocore.PackageSurfaceAreaDocument;
import org.tianocore.FrameworkDatabaseDocument.FrameworkDatabase; import org.tianocore.FrameworkDatabaseDocument.FrameworkDatabase;
import org.tianocore.GuidDeclarationsDocument.GuidDeclarations; import org.tianocore.GuidDeclarationsDocument.GuidDeclarations;
import org.tianocore.PackageListDocument.PackageList; import org.tianocore.LibraryClassDeclarationsDocument.LibraryClassDeclarations;
import org.tianocore.PackageSurfaceAreaDocument; import org.tianocore.LibraryClassDeclarationsDocument.LibraryClassDeclarations.LibraryClass;
import org.tianocore.PackageSurfaceAreaDocument.PackageSurfaceArea; import org.tianocore.PackageSurfaceAreaDocument.PackageSurfaceArea;
import org.tianocore.PpiDeclarationsDocument.PpiDeclarations; import org.tianocore.PpiDeclarationsDocument.PpiDeclarations;
import org.tianocore.ProtocolDeclarationsDocument.ProtocolDeclarations; import org.tianocore.ProtocolDeclarationsDocument.ProtocolDeclarations;
import org.tianocore.LibraryClassDeclarationsDocument.LibraryClassDeclarations;
import org.tianocore.LibraryClassDeclarationsDocument.LibraryClassDeclarations.LibraryClass;
public final class Database { public final class Database {
private static final Database INSTANCE = Database.init();; private static final Database INSTANCE = Database.init();;
Database(String path) { Database(String path) {
DatabasePath = path; DatabasePath = path;
try { try {
//collectWorkSpaceDatabase(); // collectWorkSpaceDatabase();
importPkgGuid("PkgGuid.csv"); importPkgGuid("PkgGuid.csv");
importDBLib("Library.csv"); importDBLib("Library.csv");
importDBGuid("Guid.csv", "Guid"); importDBGuid("Guid.csv", "Guid");
importDBGuid("Ppi.csv", "Ppi"); importDBGuid("Ppi.csv", "Ppi");
importDBGuid("Protocol.csv", "Protocol"); importDBGuid("Protocol.csv", "Protocol");
importDBMacro("Macro.csv"); importDBMacro("Macro.csv");
importListR8Only(); importListR8Only();
} catch (Exception e) { } catch (Exception e) {
System.out.println(e.getMessage()); System.out.println(e.getMessage());
} }
} }
public String DatabasePath; public String DatabasePath;
public Set<String> error = new HashSet<String>();
public Set<String> r8only = new HashSet<String>(); public Set<String> error = new HashSet<String>();
private Map<String,Guid> hashguid = new HashMap<String,Guid>(); public Set<String> r8only = new HashSet<String>();
private Map<String,Func> hashfunc = new HashMap<String,Func>();
private Map<String,Macro> hashmacro = new HashMap<String,Macro>(); private Map<String, Guid> hashguid = new HashMap<String, Guid>();
private Map<String,String> hashPkgGuid = new HashMap<String,String>();
private Map<String, Func> hashfunc = new HashMap<String, Func>();
//-------------------------------------import------------------------------------------// private Map<String, Macro> hashmacro = new HashMap<String, Macro>();
private void importPkgGuid(String filename) throws Exception {
BufferedReader rd = new BufferedReader(new FileReader(DatabasePath + File.separator + filename)); private Map<String, String> hashPkgGuid = new HashMap<String, String>();
String line;
String[] linecontext; // -------------------------------------import------------------------------------------//
private void importPkgGuid(String filename) throws Exception {
if (rd.ready()) { BufferedReader rd = new BufferedReader(new FileReader(DatabasePath
System.out.println("Found " + filename + ", Importing Package Guid Database."); + File.separator + filename));
// String line;
// Skip the title row. String[] linecontext;
//
line = rd.readLine(); if (rd.ready()) {
while ((line = rd.readLine()) != null) { System.out.println("Found " + filename
if (line.length() != 0) { + ", Importing Package Guid Database.");
linecontext = line.split(","); //
hashPkgGuid.put(linecontext[0], linecontext[1]); // Skip the title row.
} //
} line = rd.readLine();
} while ((line = rd.readLine()) != null) {
} if (line.length() != 0) {
public Iterator<String> dumpAllPkgGuid() { linecontext = line.split(",");
return hashPkgGuid.values().iterator(); hashPkgGuid.put(linecontext[0], linecontext[1]);
} }
private void importDBLib(String filename) throws Exception { }
BufferedReader rd = new BufferedReader(new FileReader(DatabasePath + File.separator + filename)); }
String line; }
String[] linecontext;
Func lf; public Iterator<String> dumpAllPkgGuid() {
return hashPkgGuid.values().iterator();
if (rd.ready()) { }
System.out.println("Found " + filename + ", Importing Library Database.");
while ((line = rd.readLine()) != null) { private void importDBLib(String filename) throws Exception {
if (line.length() != 0) { BufferedReader rd = new BufferedReader(new FileReader(DatabasePath
linecontext = line.split(","); + File.separator + filename));
lf = new Func(linecontext); String line;
hashfunc.put(lf.r8funcname,lf); String[] linecontext;
} Func lf;
}
} if (rd.ready()) {
} System.out.println("Found " + filename
+ ", Importing Library Database.");
private void importDBGuid(String filename, String type) throws Exception { while ((line = rd.readLine()) != null) {
BufferedReader rd = new BufferedReader(new FileReader(DatabasePath + File.separator + filename)); if (line.length() != 0) {
String line; linecontext = line.split(",");
String[] linecontext; lf = new Func(linecontext);
Guid gu; hashfunc.put(lf.r8funcname, lf);
}
if (rd.ready()) { }
System.out.println("Found " + filename + ", Importing " + type + " Database."); }
while ((line = rd.readLine()) != null) { }
if (line.length() != 0) {
linecontext = line.split(","); private void importDBGuid(String filename, String type) throws Exception {
gu = new Guid(linecontext, type); BufferedReader rd = new BufferedReader(new FileReader(DatabasePath
hashguid.put(gu.r8name,gu); + File.separator + filename));
} String line;
} String[] linecontext;
} Guid gu;
}
if (rd.ready()) {
private void importDBMacro(String filename) throws Exception { System.out.println("Found " + filename + ", Importing " + type
BufferedReader rd = new BufferedReader(new FileReader(DatabasePath + File.separator + filename)); + " Database.");
String line; while ((line = rd.readLine()) != null) {
String[] linecontext; if (line.length() != 0) {
Macro mc; linecontext = line.split(",");
gu = new Guid(linecontext, type);
if (rd.ready()) { hashguid.put(gu.r8name, gu);
System.out.println("Found " + filename + ", Importing Macro Database."); }
while ((line = rd.readLine()) != null) { }
if (line.length() != 0) { }
linecontext = line.split(","); }
mc = new Macro(linecontext);
hashmacro.put(mc.r8name,mc); private void importDBMacro(String filename) throws Exception {
} BufferedReader rd = new BufferedReader(new FileReader(DatabasePath
} + File.separator + filename));
} String line;
} String[] linecontext;
Macro mc;
private void importListR8Only() throws Exception {
Pattern ptnr8only = Pattern.compile("////#?(\\w*)?.*?R8_(.*?)\\s*\\(.*?////~", Pattern.DOTALL); if (rd.ready()) {
String wholeline = Common.file2string(DatabasePath + File.separator + "R8Lib.c"); System.out.println("Found " + filename
System.out.println("Found " + "R8Lib.c" + ", Importing R8Lib Database."); + ", Importing Macro Database.");
Matcher mtrr8only = ptnr8only.matcher(wholeline); while ((line = rd.readLine()) != null) {
while (mtrr8only.find()) { if (line.length() != 0) {
r8only.add(mtrr8only.group(2)); linecontext = line.split(",");
} mc = new Macro(linecontext);
} hashmacro.put(mc.r8name, mc);
}
//-------------------------------------import------------------------------------------// }
}
//-------------------------------------get------------------------------------------// }
public String getR9Lib(String r8funcname) { private void importListR8Only() throws Exception {
String temp = null; Pattern ptnr8only = Pattern.compile(
if (hashfunc.containsKey(r8funcname)) { "////#?(\\w*)?.*?R8_(.*?)\\s*\\(.*?////~", Pattern.DOTALL);
temp = hashfunc.get(r8funcname).r9libname; String wholeline = Common.file2string(DatabasePath + File.separator
} + "R8Lib.c");
return temp; System.out
} .println("Found " + "R8Lib.c" + ", Importing R8Lib Database.");
Matcher mtrr8only = ptnr8only.matcher(wholeline);
public String getR9Func(String r8funcname) { while (mtrr8only.find()) {
String temp = null; r8only.add(mtrr8only.group(2));
if (hashfunc.containsKey(r8funcname)) { }
temp = hashfunc.get(r8funcname).r9funcname; }
}
return temp; // -------------------------------------import------------------------------------------//
}
// -------------------------------------get------------------------------------------//
public String getR9Macro(String r8macro) {
return hashmacro.get(r8macro).r9name; // the verification job of if the macro exists in the database is done when registering it public String getR9Lib(String r8funcname) {
} String temp = null;
if (hashfunc.containsKey(r8funcname)) {
public String getR9Guidname(String r8Guid) { temp = hashfunc.get(r8funcname).r9libname;
String temp = null; }
try { return temp;
temp = hashguid.get(r8Guid).r9name; }
} catch (NullPointerException e) {
error.add("getR9Guidname :" + r8Guid); public String getR9Func(String r8funcname) {
} String temp = null;
return temp; if (hashfunc.containsKey(r8funcname)) {
} temp = hashfunc.get(r8funcname).r9funcname;
}
public String getGuidType(String r8Guid) { return temp;
String temp = null; }
try {
temp = hashguid.get(r8Guid).type; public String getR9Macro(String r8macro) {
} catch (NullPointerException e) { return hashmacro.get(r8macro).r9name; // the verification job of if
error.add("getR9Guidname :" + r8Guid); // the macro exists in the
} // database is done when
return temp; // registering it
} }
//-------------------------------------get------------------------------------------// public String getR9Guidname(String r8Guid) {
String temp = null;
//-------------------------------------has------------------------------------------// try {
temp = hashguid.get(r8Guid).r9name;
public boolean hasFunc(String r8lib) { } catch (NullPointerException e) {
return hashfunc.containsKey(r8lib); error.add("getR9Guidname :" + r8Guid);
} }
return temp;
public boolean hasGuid(String r8guid) { }
return hashguid.containsKey(r8guid);
} public String getGuidType(String r8Guid) {
String temp = null;
public boolean hasMacro(String r8macro) { try {
return hashmacro.containsKey(r8macro); temp = hashguid.get(r8Guid).type;
} } catch (NullPointerException e) {
error.add("getR9Guidname :" + r8Guid);
//-------------------------------------has------------------------------------------// }
return temp;
//-------------------------------------init------------------------------------------// }
private static final Database init() { // -------------------------------------get------------------------------------------//
if (System.getenv("WORKSPACE") == null) {
return new Database("C:" + File.separator + "tianocore" + File.separator + "edk2" + File.separator + "Tools" + File.separator + "Conf" + File.separator + "Migration"); // -------------------------------------has------------------------------------------//
} else {
return new Database(System.getenv("WORKSPACE") + File.separator + "Tools" + File.separator + "Conf" + File.separator + "Migration"); public boolean hasFunc(String r8lib) {
} return hashfunc.containsKey(r8lib);
} }
public static final Database getInstance() { public boolean hasGuid(String r8guid) {
return INSTANCE; return hashguid.containsKey(r8guid);
} }
public boolean hasMacro(String r8macro) {
return hashmacro.containsKey(r8macro);
private String workspacePath; }
private HashMap<String, String> hashDbGuids = new HashMap<String, String>();
private HashMap<String, String> hashDbPpis = new HashMap<String, String>(); // -------------------------------------has------------------------------------------//
private HashMap<String, String> hashDbProtocols = new HashMap<String, String>();
private HashMap<String, String> hashDbLibSymbols = new HashMap<String, String>(); // -------------------------------------init------------------------------------------//
private HashMap<String, String> hashDbLibFunctions = new HashMap<String, String>();
private HashMap<String, String> hashDbLibExterns = new HashMap<String, String>(); private static final Database init() {
if (System.getenv("WORKSPACE") == null) {
private final String regLibClassName = ".*\\W(\\w[\\w\\d]*)\\.h"; return new Database("C:" + File.separator + "tianocore"
private final Pattern ptnLibClassName = Pattern.compile(regLibClassName); + File.separator + "edk2" + File.separator + "Tools"
+ File.separator + "Conf" + File.separator + "Migration");
private final String regLibSymbol = "#define\\s+(\\w[\\w\\d]*)"; } else {
private final Pattern ptnLibSymbol = Pattern.compile(regLibSymbol); return new Database(System.getenv("WORKSPACE") + File.separator
+ "Tools" + File.separator + "Conf" + File.separator
private final String regLibDataType = "[A-Z][A-Z0-9_]*\\s*\\**"; + "Migration");
private final String regLibFunction = regLibDataType + "\\s*(?:EFIAPI)?\\s+" + }
"(\\w[\\w\\d]*)\\s*\\([^)]*\\)\\s*;"; }
private Pattern ptnLibFunction = Pattern.compile(regLibFunction);
public static final Database getInstance() {
private final String regLibExtern = "extern\\s+" + regLibDataType + return INSTANCE;
"\\s*(\\w[\\w\\d]*)"; }
private final Pattern ptnLibExtern = Pattern.compile(regLibExtern);
private String workspacePath;
private final String convertToOsFilePath(String filePath) {
return filePath.replace("/", File.separator).replace("\\", File.separator); private HashMap<String, String> hashDbGuids = new HashMap<String, String>();
}
private final void collectLibHeaderFileInfo(String libHeaderFile, String pkgGuid) throws Exception { private HashMap<String, String> hashDbPpis = new HashMap<String, String>();
String fileContents;
String libClassName; private HashMap<String, String> hashDbProtocols = new HashMap<String, String>();
String libContainer;
Matcher mtrLibClass; private HashMap<String, String> hashDbLibSymbols = new HashMap<String, String>();
Matcher mtrLibSymbol;
Matcher mtrLibFunction; private HashMap<String, String> hashDbLibFunctions = new HashMap<String, String>();
Matcher mtrLibExtern;
private HashMap<String, String> hashDbLibExterns = new HashMap<String, String>();
System.out.println ("Parsing: " + libHeaderFile);
mtrLibClass = ptnLibClassName.matcher(libHeaderFile); private final String regLibClassName = ".*\\W(\\w[\\w\\d]*)\\.h";
if (!mtrLibClass.matches()) {
throw new Exception("Illegal libary header file"); private final Pattern ptnLibClassName = Pattern.compile(regLibClassName);
}
libClassName = mtrLibClass.group(1); private final String regLibSymbol = "#define\\s+(\\w[\\w\\d]*)";
libContainer = libClassName + "@" + pkgGuid;
private final Pattern ptnLibSymbol = Pattern.compile(regLibSymbol);
fileContents = Common.file2string(libHeaderFile);
mtrLibSymbol = ptnLibSymbol.matcher(fileContents); private final String regLibDataType = "[A-Z][A-Z0-9_]*\\s*\\**";
while (mtrLibSymbol.find()) {
String libSymbol; private final String regLibFunction = regLibDataType
String oldLibContainer; + "\\s*(?:EFIAPI)?\\s+" + "(\\w[\\w\\d]*)\\s*\\([^)]*\\)\\s*;";
libSymbol = mtrLibSymbol.group(1); private Pattern ptnLibFunction = Pattern.compile(regLibFunction);
oldLibContainer = hashDbLibSymbols.put(libSymbol, libContainer);
if (oldLibContainer != null) { private final String regLibExtern = "extern\\s+" + regLibDataType
String warnMessage; + "\\s*(\\w[\\w\\d]*)";
warnMessage = "Duplicated Lib Symbol:" + libSymbol + " Found. " + private final Pattern ptnLibExtern = Pattern.compile(regLibExtern);
"Later package will overide the previous one";
System.out.println(warnMessage); private final String convertToOsFilePath(String filePath) {
} return filePath.replace("/", File.separator).replace("\\",
} File.separator);
}
mtrLibFunction = ptnLibFunction.matcher(fileContents);
while (mtrLibFunction.find()) { private final void collectLibHeaderFileInfo(String libHeaderFile,
String libFunction; String pkgGuid) throws Exception {
String oldLibContainer; String fileContents;
String libClassName;
libFunction = mtrLibFunction.group(1); String libContainer;
oldLibContainer = hashDbLibFunctions.put(libFunction, libContainer); Matcher mtrLibClass;
if (oldLibContainer != null) { Matcher mtrLibSymbol;
String warnMessage; Matcher mtrLibFunction;
Matcher mtrLibExtern;
warnMessage = "Duplicated Lib Function:" + libFunction + " Found. " +
"Later package will overide the previous one"; System.out.println("Parsing: " + libHeaderFile);
System.out.println(warnMessage); mtrLibClass = ptnLibClassName.matcher(libHeaderFile);
} if (!mtrLibClass.matches()) {
} throw new Exception("Illegal libary header file");
}
mtrLibExtern = ptnLibExtern.matcher(fileContents); libClassName = mtrLibClass.group(1);
while (mtrLibExtern.find()) { libContainer = libClassName + "@" + pkgGuid;
String libExtern;
String oldLibContainer; fileContents = Common.file2string(libHeaderFile);
mtrLibSymbol = ptnLibSymbol.matcher(fileContents);
libExtern = mtrLibExtern.group(1); while (mtrLibSymbol.find()) {
oldLibContainer = hashDbLibExterns.put(libExtern, libContainer); String libSymbol;
if (oldLibContainer != null) { String oldLibContainer;
String warnMessage;
libSymbol = mtrLibSymbol.group(1);
warnMessage = "Duplicated Lib Extern:" + libExtern + " Found. " + oldLibContainer = hashDbLibSymbols.put(libSymbol, libContainer);
"Later package will overide the previous one"; if (oldLibContainer != null) {
System.out.println(warnMessage); String warnMessage;
}
} warnMessage = "Duplicated Lib Symbol:" + libSymbol + " Found. "
} + "Later package will overide the previous one";
private final void collectLibDataBase(PackageSurfaceArea spdDatabase, String pkgDirectory) throws Exception { System.out.println(warnMessage);
String pkgGuid; }
LibraryClassDeclarations libClassDeclarations; }
pkgGuid = spdDatabase.getSpdHeader().getGuidValue(); mtrLibFunction = ptnLibFunction.matcher(fileContents);
libClassDeclarations = spdDatabase.getLibraryClassDeclarations(); while (mtrLibFunction.find()) {
if (libClassDeclarations != null) { String libFunction;
Iterator<LibraryClass> itLibClass; String oldLibContainer;
itLibClass = libClassDeclarations.getLibraryClassList().iterator(); libFunction = mtrLibFunction.group(1);
while (itLibClass.hasNext()) { oldLibContainer = hashDbLibFunctions.put(libFunction, libContainer);
String libHeaderFile; if (oldLibContainer != null) {
String warnMessage;
libHeaderFile = pkgDirectory + File.separator +
itLibClass.next().getIncludeHeader(); warnMessage = "Duplicated Lib Function:" + libFunction
libHeaderFile = convertToOsFilePath (libHeaderFile); + " Found. "
try { + "Later package will overide the previous one";
collectLibHeaderFileInfo(libHeaderFile, pkgGuid); System.out.println(warnMessage);
} catch (Exception e) { }
String errorMessage; }
errorMessage = "Error (" + e.getMessage() + ")occurs when parsing " + mtrLibExtern = ptnLibExtern.matcher(fileContents);
libHeaderFile; while (mtrLibExtern.find()) {
System.out.println(errorMessage); String libExtern;
} String oldLibContainer;
}
} libExtern = mtrLibExtern.group(1);
} oldLibContainer = hashDbLibExterns.put(libExtern, libContainer);
private final void collectGuidDatabase(PackageSurfaceArea spdDatabase) throws Exception { if (oldLibContainer != null) {
String pkgGuid; String warnMessage;
GuidDeclarations guidDeclarations;
warnMessage = "Duplicated Lib Extern:" + libExtern + " Found. "
pkgGuid = spdDatabase.getSpdHeader().getGuidValue(); + "Later package will overide the previous one";
guidDeclarations = spdDatabase.getGuidDeclarations(); System.out.println(warnMessage);
if (guidDeclarations != null) { }
Iterator<GuidDeclarations.Entry> itGuids; }
}
itGuids = guidDeclarations.getEntryList().iterator();
while (itGuids.hasNext()) { private final void collectLibDataBase(PackageSurfaceArea spdDatabase,
hashDbGuids.put(itGuids.next().getCName(), pkgGuid); String pkgDirectory) throws Exception {
} String pkgGuid;
} LibraryClassDeclarations libClassDeclarations;
} pkgGuid = spdDatabase.getSpdHeader().getGuidValue();
libClassDeclarations = spdDatabase.getLibraryClassDeclarations();
private final void collectPpiDatabase(PackageSurfaceArea spdDatabase) throws Exception { if (libClassDeclarations != null) {
String pkgGuid; Iterator<LibraryClass> itLibClass;
PpiDeclarations ppiDeclarations;
itLibClass = libClassDeclarations.getLibraryClassList().iterator();
pkgGuid = spdDatabase.getSpdHeader().getGuidValue(); while (itLibClass.hasNext()) {
ppiDeclarations = spdDatabase.getPpiDeclarations(); String libHeaderFile;
if (ppiDeclarations != null) { libHeaderFile = pkgDirectory + File.separator
Iterator<PpiDeclarations.Entry> itPpis; + itLibClass.next().getIncludeHeader();
libHeaderFile = convertToOsFilePath(libHeaderFile);
itPpis = ppiDeclarations.getEntryList().iterator(); try {
while (itPpis.hasNext()) { collectLibHeaderFileInfo(libHeaderFile, pkgGuid);
hashDbPpis.put(itPpis.next().getCName(), pkgGuid); } catch (Exception e) {
} String errorMessage;
}
errorMessage = "Error (" + e.getMessage()
} + ")occurs when parsing " + libHeaderFile;
System.out.println(errorMessage);
private final void collectProtocolDatabase(PackageSurfaceArea spdDatabase) throws Exception { }
String pkgGuid; }
ProtocolDeclarations protocolDeclarations; }
}
pkgGuid = spdDatabase.getSpdHeader().getGuidValue();
protocolDeclarations = spdDatabase.getProtocolDeclarations(); private final void collectGuidDatabase(PackageSurfaceArea spdDatabase)
throws Exception {
if (protocolDeclarations != null) { String pkgGuid;
Iterator<ProtocolDeclarations.Entry> itProtocols; GuidDeclarations guidDeclarations;
itProtocols = protocolDeclarations.getEntryList().iterator(); pkgGuid = spdDatabase.getSpdHeader().getGuidValue();
while (itProtocols.hasNext()) { guidDeclarations = spdDatabase.getGuidDeclarations();
hashDbGuids.put(itProtocols.next().getCName(), pkgGuid); if (guidDeclarations != null) {
} Iterator<GuidDeclarations.Entry> itGuids;
}
itGuids = guidDeclarations.getEntryList().iterator();
} while (itGuids.hasNext()) {
hashDbGuids.put(itGuids.next().getCName(), pkgGuid);
private final void collectPackageDatabase(String packageFileName) throws Exception { }
XmlObject xmlPackage; }
PackageSurfaceArea spdDatabase;
File pkgFile; }
pkgFile = new File(packageFileName); private final void collectPpiDatabase(PackageSurfaceArea spdDatabase)
xmlPackage = XmlObject.Factory.parse(pkgFile); throws Exception {
spdDatabase = ((PackageSurfaceAreaDocument) xmlPackage).getPackageSurfaceArea(); String pkgGuid;
PpiDeclarations ppiDeclarations;
collectGuidDatabase(spdDatabase);
collectProtocolDatabase(spdDatabase); pkgGuid = spdDatabase.getSpdHeader().getGuidValue();
collectPpiDatabase(spdDatabase); ppiDeclarations = spdDatabase.getPpiDeclarations();
collectLibDataBase(spdDatabase, pkgFile.getParent());
if (ppiDeclarations != null) {
Iterator<PpiDeclarations.Entry> itPpis;
}
public final void collectWorkSpaceDatabase() throws Exception { itPpis = ppiDeclarations.getEntryList().iterator();
String databaseFileName; while (itPpis.hasNext()) {
File databaseFile; hashDbPpis.put(itPpis.next().getCName(), pkgGuid);
XmlObject xmlDatabase; }
FrameworkDatabase frameworkDatabase; }
Iterator<DbPathAndFilename> packageFile;
}
workspacePath = System.getenv("WORKSPACE");
private final void collectProtocolDatabase(PackageSurfaceArea spdDatabase)
if (workspacePath == null) { throws Exception {
String errorMessage = "Envivornment variable \"WORKSPACE\" is not set!"; String pkgGuid;
throw new Exception(errorMessage); ProtocolDeclarations protocolDeclarations;
}
databaseFileName = workspacePath + File.separator + pkgGuid = spdDatabase.getSpdHeader().getGuidValue();
"Tools" + File.separator + protocolDeclarations = spdDatabase.getProtocolDeclarations();
"Conf" + File.separator +
"FrameworkDatabase.db"; if (protocolDeclarations != null) {
System.out.println("Open " + databaseFileName); Iterator<ProtocolDeclarations.Entry> itProtocols;
databaseFile = new File(databaseFileName);
xmlDatabase = XmlObject.Factory.parse(databaseFile); itProtocols = protocolDeclarations.getEntryList().iterator();
frameworkDatabase = ((FrameworkDatabaseDocument) xmlDatabase).getFrameworkDatabase(); while (itProtocols.hasNext()) {
packageFile = frameworkDatabase.getPackageList().getFilenameList().iterator(); hashDbGuids.put(itProtocols.next().getCName(), pkgGuid);
}
while (packageFile.hasNext()) { }
String packageFileName = packageFile.next().getStringValue();
packageFileName = workspacePath + File.separator + packageFileName; }
packageFileName = convertToOsFilePath(packageFileName);
private final void collectPackageDatabase(String packageFileName)
System.out.println("Parsing: " + packageFileName); throws Exception {
try { XmlObject xmlPackage;
collectPackageDatabase(packageFileName); PackageSurfaceArea spdDatabase;
} catch (Exception e) { File pkgFile;
System.out.println("Error occured when opening " + packageFileName + e.getMessage());
} pkgFile = new File(packageFileName);
} xmlPackage = XmlObject.Factory.parse(pkgFile);
} spdDatabase = ((PackageSurfaceAreaDocument) xmlPackage)
.getPackageSurfaceArea();
collectGuidDatabase(spdDatabase);
collectProtocolDatabase(spdDatabase);
collectPpiDatabase(spdDatabase);
collectLibDataBase(spdDatabase, pkgFile.getParent());
}
public final void collectWorkSpaceDatabase() throws Exception {
String databaseFileName;
File databaseFile;
XmlObject xmlDatabase;
FrameworkDatabase frameworkDatabase;
Iterator<DbPathAndFilename> packageFile;
workspacePath = System.getenv("WORKSPACE");
if (workspacePath == null) {
String errorMessage = "Envivornment variable \"WORKSPACE\" is not set!";
throw new Exception(errorMessage);
}
databaseFileName = workspacePath + File.separator + "Tools"
+ File.separator + "Conf" + File.separator
+ "FrameworkDatabase.db";
System.out.println("Open " + databaseFileName);
databaseFile = new File(databaseFileName);
xmlDatabase = XmlObject.Factory.parse(databaseFile);
frameworkDatabase = ((FrameworkDatabaseDocument) xmlDatabase)
.getFrameworkDatabase();
packageFile = frameworkDatabase.getPackageList().getFilenameList()
.iterator();
while (packageFile.hasNext()) {
String packageFileName = packageFile.next().getStringValue();
packageFileName = workspacePath + File.separator + packageFileName;
packageFileName = convertToOsFilePath(packageFileName);
System.out.println("Parsing: " + packageFileName);
try {
collectPackageDatabase(packageFileName);
} catch (Exception e) {
System.out.println("Error occured when opening "
+ packageFileName + e.getMessage());
}
}
}
} }

View File

@ -12,263 +12,294 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.awt.*; import java.awt.GridBagConstraints;
import java.awt.event.*; import java.awt.GridBagLayout;
import java.io.*; import java.awt.Insets;
import java.util.*; import java.awt.event.ActionEvent;
import javax.swing.*; import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Set;
public final class FirstPanel extends JPanel implements ActionListener, ItemListener, UI { import javax.swing.BoxLayout;
/** import javax.swing.JButton;
* Define class Serial Version UID import javax.swing.JCheckBox;
*/ import javax.swing.JFileChooser;
private static final long serialVersionUID = 207759413522910399L; import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
private static final FirstPanel INSTANCE = FirstPanel.init(); public final class FirstPanel extends JPanel implements ActionListener,
ItemListener, UI {
/**
* Define class Serial Version UID
*/
private static final long serialVersionUID = 207759413522910399L;
private String startpath = null; private static final FirstPanel INSTANCE = FirstPanel.init();
private JButton moduleButton, goButton, msaEditorButton, criticButton, specifyCommentButton; private String startpath = null;
private JTextField moduletext;
private JTextArea log;
private JFileChooser fc = new JFileChooser();
private JCheckBox filebox, screenbox, mibox, criticbox, defaultpathbox;
private boolean tofile = true, toscreen = true; private JButton moduleButton, goButton, msaEditorButton, criticButton,
private PrintWriter logfile; specifyCommentButton;
FirstPanel() { private JTextField moduletext;
GridBagLayout gridbag = new GridBagLayout();
setLayout(gridbag);
GridBagConstraints cst = new GridBagConstraints(); private JTextArea log;
goButton = new JButton("Go"); private JFileChooser fc = new JFileChooser();
goButton.addActionListener(this);
goButton.setActionCommand("go");
moduleButton = new JButton("Choose ModulePath"); private JCheckBox filebox, screenbox, mibox, criticbox, defaultpathbox;
moduleButton.addActionListener(this);
msaEditorButton = new JButton("MsaEditor"); private boolean tofile = true, toscreen = true;
msaEditorButton.addActionListener(this);
criticButton = new JButton("Critic"); private PrintWriter logfile;
criticButton.addActionListener(this);
specifyCommentButton = new JButton("Comment Style"); FirstPanel() {
specifyCommentButton.addActionListener(this); GridBagLayout gridbag = new GridBagLayout();
setLayout(gridbag);
moduletext = new JTextField(30); GridBagConstraints cst = new GridBagConstraints();
filebox = new JCheckBox("Output to logfile", true); goButton = new JButton("Go");
filebox.addItemListener(this); goButton.addActionListener(this);
goButton.setActionCommand("go");
screenbox = new JCheckBox("Specify logfile", false); moduleButton = new JButton("Choose ModulePath");
screenbox.addItemListener(this); moduleButton.addActionListener(this);
mibox = new JCheckBox("Print ModuleInfo", false); msaEditorButton = new JButton("MsaEditor");
mibox.addItemListener(this); msaEditorButton.addActionListener(this);
MigrationTool.printModuleInfo = false;
criticbox = new JCheckBox("Run Critic", true); criticButton = new JButton("Critic");
criticbox.addItemListener(this); criticButton.addActionListener(this);
MigrationTool.doCritic = true;
defaultpathbox = new JCheckBox("Use Default Output Path", true); specifyCommentButton = new JButton("Comment Style");
defaultpathbox.addItemListener(this); specifyCommentButton.addActionListener(this);
MigrationTool.defaultoutput = true;
JPanel modulePanel = new JPanel(); moduletext = new JTextField(30);
modulePanel.add(moduleButton);
modulePanel.add(moduletext);
modulePanel.add(goButton);
//modulePanel.add(msaEditorButton);
cst.gridx = 0;
cst.gridy = 0;
//cst.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(modulePanel, cst);
add(modulePanel);
cst.gridx = 1; filebox = new JCheckBox("Output to logfile", true);
cst.gridy = 0; filebox.addItemListener(this);
gridbag.setConstraints(specifyCommentButton, cst);
add(specifyCommentButton);
//gridbag.setConstraints(criticButton, cst);
//add(criticButton);
JPanel checkboxPanel = new JPanel(); screenbox = new JCheckBox("Specify logfile", false);
checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.Y_AXIS)); screenbox.addItemListener(this);
checkboxPanel.add(filebox);
checkboxPanel.add(screenbox);
checkboxPanel.add(mibox);
checkboxPanel.add(criticbox);
checkboxPanel.add(defaultpathbox);
cst.gridx = 1;
cst.gridy = 1;
//cst.gridheight = 2;
gridbag.setConstraints(checkboxPanel, cst);
add(checkboxPanel);
log = new JTextArea(10,20); mibox = new JCheckBox("Print ModuleInfo", false);
log.setMargin(new Insets(5,5,5,5)); mibox.addItemListener(this);
log.setEditable(false); MigrationTool.printModuleInfo = false;
JScrollPane logScrollPane = new JScrollPane(log);
cst.gridx = 0;
cst.gridy = 1;
cst.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(logScrollPane, cst);
add(logScrollPane);
}
//---------------------------------------------------------------------------------------// criticbox = new JCheckBox("Run Critic", true);
criticbox.addItemListener(this);
MigrationTool.doCritic = true;
public boolean yesOrNo(String question) { defaultpathbox = new JCheckBox("Use Default Output Path", true);
return JOptionPane.showConfirmDialog(this, question, "Yes or No", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; defaultpathbox.addItemListener(this);
} MigrationTool.defaultoutput = true;
public void print(String message) { JPanel modulePanel = new JPanel();
if (toscreen == true) { modulePanel.add(moduleButton);
log.append(message); modulePanel.add(moduletext);
System.out.print(message); modulePanel.add(goButton);
} // modulePanel.add(msaEditorButton);
if (tofile == true) { cst.gridx = 0;
logfile.append(message); cst.gridy = 0;
} // cst.gridwidth = GridBagConstraints.REMAINDER;
} gridbag.setConstraints(modulePanel, cst);
add(modulePanel);
public void println(String message) { cst.gridx = 1;
print(message + "\n"); cst.gridy = 0;
} gridbag.setConstraints(specifyCommentButton, cst);
add(specifyCommentButton);
// gridbag.setConstraints(criticButton, cst);
// add(criticButton);
public void println(Set<String> hash) { JPanel checkboxPanel = new JPanel();
if (toscreen == true) { checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.Y_AXIS));
log.append(hash + "\n"); checkboxPanel.add(filebox);
System.out.println(hash); checkboxPanel.add(screenbox);
} checkboxPanel.add(mibox);
if (tofile == true) { checkboxPanel.add(criticbox);
logfile.append(hash + "\n"); checkboxPanel.add(defaultpathbox);
} cst.gridx = 1;
} cst.gridy = 1;
// cst.gridheight = 2;
gridbag.setConstraints(checkboxPanel, cst);
add(checkboxPanel);
public String choose(String message, Object[] choicelist) { log = new JTextArea(10, 20);
return (String)JOptionPane.showInputDialog(this, message,"Choose",JOptionPane.PLAIN_MESSAGE,null,choicelist,choicelist[0]); log.setMargin(new Insets(5, 5, 5, 5));
} log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
cst.gridx = 0;
cst.gridy = 1;
cst.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(logScrollPane, cst);
add(logScrollPane);
}
public String getInput(String message) { // ---------------------------------------------------------------------------------------//
return (String)JOptionPane.showInputDialog(message);
}
//---------------------------------------------------------------------------------------// public boolean yesOrNo(String question) {
return JOptionPane.showConfirmDialog(this, question, "Yes or No",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
public String getFilepath(String title, int mode) { public void print(String message) {
fc.setDialogTitle(title); if (toscreen == true) {
fc.setFileSelectionMode(mode); log.append(message);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { System.out.print(message);
log.append(fc.getSelectedFile().getAbsolutePath() + "\n"); }
return fc.getSelectedFile().getAbsolutePath(); if (tofile == true) {
} logfile.append(message);
return null; }
} }
//---------------------------------------------------------------------------------------// public void println(String message) {
print(message + "\n");
}
public void actionPerformed(ActionEvent e) { public void println(Set<String> hash) {
if ( e.getSource() == moduleButton ) { if (toscreen == true) {
startpath = getFilepath("Please choose a starting path", JFileChooser.DIRECTORIES_ONLY); log.append(hash + "\n");
moduletext.setText(startpath); System.out.println(hash);
} }
if ( e.getSource() == goButton ) { if (tofile == true) {
try { logfile.append(hash + "\n");
logfile = new PrintWriter(new BufferedWriter(new FileWriter(startpath.replaceAll(Common.STRSEPARATER, "$1") + File.separator + "migration.log"))); }
MigrationTool.startMigrateAll(startpath); }
logfile.flush();
logfile.close();
} catch (Exception en) {
println(en.getMessage());
}
}
if ( e.getSource() == msaEditorButton) {
try {
MsaTreeEditor.init();
} catch (Exception en) {
println(en.getMessage());
}
}
if ( e.getSource() == criticButton) {
try {
Critic.fireAt(startpath);
} catch (Exception en) {
println(en.getMessage());
}
}
if ( e.getSource() == specifyCommentButton) {
try { // input examine is not imposed but should be added
MigrationTool.MIGRATIONCOMMENT = getInput("Please type in wanted comment style used by the tool\nbe sure to start with '//', or you won't enjoy the result");
//MsaWriter.parse("C:\\tianocore\\edk2\\MdePkg\\Library\\BaseLib\\BaseLib.msa");
} catch (Exception en) {
println(en.getMessage());
}
}
}
public void itemStateChanged(ItemEvent e) { public String choose(String message, Object[] choicelist) {
if (e.getSource() == filebox) { return (String) JOptionPane.showInputDialog(this, message, "Choose",
if (e.getStateChange() == ItemEvent.DESELECTED) { JOptionPane.PLAIN_MESSAGE, null, choicelist, choicelist[0]);
System.out.println("filebox DESELECTED"); }
} else if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("filebox SELECTED");
}
} else if (e.getSource() == screenbox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
System.out.println("screenbox DESELECTED");
} else if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("screenbox SELECTED");
}
} else if (e.getSource() == mibox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
MigrationTool.printModuleInfo = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
MigrationTool.printModuleInfo = true;
}
} else if (e.getSource() == criticbox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
MigrationTool.doCritic = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
MigrationTool.doCritic = true;
}
} else if (e.getSource() == defaultpathbox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
MigrationTool.defaultoutput = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
MigrationTool.defaultoutput = true;
}
}
}
//---------------------------------------------------------------------------------------// public String getInput(String message) {
return (String) JOptionPane.showInputDialog(message);
}
private static final FirstPanel init() { // ---------------------------------------------------------------------------------------//
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println(e.getMessage());
}
JFrame frame = new JFrame("MigrationTools"); public String getFilepath(String title, int mode) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fc.setDialogTitle(title);
fc.setFileSelectionMode(mode);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
log.append(fc.getSelectedFile().getAbsolutePath() + "\n");
return fc.getSelectedFile().getAbsolutePath();
}
return null;
}
FirstPanel fp = new FirstPanel(); // ---------------------------------------------------------------------------------------//
fp.setOpaque(true);
frame.setContentPane(fp);
frame.pack(); public void actionPerformed(ActionEvent e) {
frame.setVisible(true); if (e.getSource() == moduleButton) {
startpath = getFilepath("Please choose a starting path",
JFileChooser.DIRECTORIES_ONLY);
moduletext.setText(startpath);
}
if (e.getSource() == goButton) {
try {
logfile = new PrintWriter(new BufferedWriter(new FileWriter(
startpath.replaceAll(Common.STRSEPARATER, "$1")
+ File.separator + "migration.log")));
MigrationTool.startMigrateAll(startpath);
logfile.flush();
logfile.close();
} catch (Exception en) {
println(en.getMessage());
}
}
if (e.getSource() == msaEditorButton) {
try {
MsaTreeEditor.init();
} catch (Exception en) {
println(en.getMessage());
}
}
if (e.getSource() == criticButton) {
try {
Critic.fireAt(startpath);
} catch (Exception en) {
println(en.getMessage());
}
}
if (e.getSource() == specifyCommentButton) {
try { // input examine is not imposed but should be added
MigrationTool.MIGRATIONCOMMENT = getInput("Please type in wanted comment style used by the tool\nbe sure to start with '//', or you won't enjoy the result");
// MsaWriter.parse("C:\\tianocore\\edk2\\MdePkg\\Library\\BaseLib\\BaseLib.msa");
} catch (Exception en) {
println(en.getMessage());
}
}
}
return fp; public void itemStateChanged(ItemEvent e) {
} if (e.getSource() == filebox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
System.out.println("filebox DESELECTED");
} else if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("filebox SELECTED");
}
} else if (e.getSource() == screenbox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
System.out.println("screenbox DESELECTED");
} else if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("screenbox SELECTED");
}
} else if (e.getSource() == mibox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
MigrationTool.printModuleInfo = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
MigrationTool.printModuleInfo = true;
}
} else if (e.getSource() == criticbox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
MigrationTool.doCritic = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
MigrationTool.doCritic = true;
}
} else if (e.getSource() == defaultpathbox) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
MigrationTool.defaultoutput = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
MigrationTool.defaultoutput = true;
}
}
}
public static final FirstPanel getInstance() { // ---------------------------------------------------------------------------------------//
return INSTANCE;
} private static final FirstPanel init() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println(e.getMessage());
}
JFrame frame = new JFrame("MigrationTools");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FirstPanel fp = new FirstPanel();
fp.setOpaque(true);
frame.setContentPane(fp);
frame.pack();
frame.setVisible(true);
return fp;
}
public static final FirstPanel getInstance() {
return INSTANCE;
}
} }

View File

@ -12,44 +12,62 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.util.regex.*; import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Func { public class Func {
Func(String r8func,String r8lib,String r9func,String r9lib) { Func(String r8func, String r8lib, String r9func, String r9lib) {
r8funcname = r8func; r8funcname = r8func;
r8libname = r8lib; r8libname = r8lib;
r9funcname = r9func; r9funcname = r9func;
r9libname = r9lib; r9libname = r9lib;
} }
Func(String[] linecontext) {
r8funcname = linecontext[1];
r8libname = linecontext[0];
r9funcname = linecontext[2];
if (r9funcname.contains("n/a")) {
r9funcname = "#error Unknown or missing library function in EDKII: " + r8funcname;
}
r9libname = linecontext[3];
}
public String r8funcname;
public String r8libname;
public String r9funcname;
public String r9libname;
public static Pattern ptnbrace = Pattern.compile("\\{[^\\{\\}]*\\}",Pattern.MULTILINE); Func(String[] linecontext) {
public static Pattern ptnfuncc = Pattern.compile("(?<!->)([a-zA-Z_]\\w*)\\s*\\(",Pattern.MULTILINE); r8funcname = linecontext[1];
public static Pattern ptnfuncd = Pattern.compile("([a-zA-Z_]\\w*)\\s*\\([^\\)\\(]*\\)\\s*@",Pattern.MULTILINE); r8libname = linecontext[0];
public static Pattern ptnlowcase = Pattern.compile("[a-z]"); // must be removed r9funcname = linecontext[2];
if (r9funcname.contains("n/a")) {
r9funcname = "#error Unknown or missing library function in EDKII: "
+ r8funcname;
}
r9libname = linecontext[3];
}
private static String reservedwords = "if for pack while switch return sizeof"; public String r8funcname;
public static String register(Matcher mtr, ModuleInfo mi, Database db) { public String r8libname;
String temp = null;
temp = mtr.group(1); // both changed and not changed funcc are registered , for finding all the non-local function calls public String r9funcname;
Matcher mtrlowcase = ptnlowcase.matcher(temp); // must be removed , so the two funcs can be merged
if (!reservedwords.contains(temp) && mtrlowcase.find()) { public String r9libname;
mi.hashfuncc.add(temp);
} public static Pattern ptnbrace = Pattern.compile("\\{[^\\{\\}]*\\}",
return temp; Pattern.MULTILINE);
}
public static Pattern ptnfuncc = Pattern.compile(
"(?<!->)([a-zA-Z_]\\w*)\\s*\\(", Pattern.MULTILINE);
public static Pattern ptnfuncd = Pattern.compile(
"([a-zA-Z_]\\w*)\\s*\\([^\\)\\(]*\\)\\s*@", Pattern.MULTILINE);
public static Pattern ptnlowcase = Pattern.compile("[a-z]"); // must be
// removed
private static String reservedwords = "if for pack while switch return sizeof";
public static String register(Matcher mtr, ModuleInfo mi, Database db) {
String temp = null;
temp = mtr.group(1); // both changed and not changed funcc are
// registered , for finding all the non-local
// function calls
Matcher mtrlowcase = ptnlowcase.matcher(temp); // must be removed , so
// the two funcs can be
// merged
if (!reservedwords.contains(temp) && mtrlowcase.find()) {
mi.hashfuncc.add(temp);
}
return temp;
}
} }

View File

@ -12,55 +12,66 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.util.regex.*; import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.tianocore.UsageTypes; import org.tianocore.UsageTypes;
public class Guid { public class Guid {
Guid (String r8, String t, String n, String r9, String gv, String p) { Guid(String r8, String t, String n, String r9, String gv, String p) {
r8name = r8; r8name = r8;
type = t; type = t;
name = n; name = n;
r9name = r9; r9name = r9;
guidvalue = gv; guidvalue = gv;
pack = p; pack = p;
} }
Guid (String[] linecontext, String t) {
r8name = linecontext[1];
type = t;
name = linecontext[0];
r9name = linecontext[2];
guidvalue = linecontext[3];
pack = linecontext[4];
}
public String r8name;
public String type;
public String name;
public String r9name;
public String guidvalue;
public String pack;
public static Pattern ptnguid = Pattern.compile("g\\w*Guid"); Guid(String[] linecontext, String t) {
r8name = linecontext[1];
type = t;
name = linecontext[0];
r9name = linecontext[2];
guidvalue = linecontext[3];
pack = linecontext[4];
}
public static String register(Matcher mtr, ModuleInfo mi, Database db) { public String r8name;
String type = null;
String temp = null;
temp = mtr.group(); public String type;
if (MigrationTool.db.hasGuid(temp)) { // only changed guids registered, because both changed and not changed guids are included in database
type = MigrationTool.db.getGuidType(temp); public String name;
if (type.matches("Protocol")) {
mi.addProtocol(temp, UsageTypes.ALWAYS_CONSUMED); public String r9name;
//mi.protocols.add(temp);
} else if (type.matches("Ppi")) { public String guidvalue;
mi.addPpi(temp, UsageTypes.ALWAYS_CONSUMED);
//mi.ppis.add(temp); public String pack;
} else if (type.matches("Guid")) {
mi.addGuid(temp, UsageTypes.ALWAYS_CONSUMED); public static Pattern ptnguid = Pattern.compile("g\\w*Guid");
//mi.guids.add(temp);
} public static String register(Matcher mtr, ModuleInfo mi, Database db) {
return temp; String type = null;
} String temp = null;
return null;
} temp = mtr.group();
if (MigrationTool.db.hasGuid(temp)) { // only changed guids
// registered, because both
// changed and not changed guids
// are included in database
type = MigrationTool.db.getGuidType(temp);
if (type.matches("Protocol")) {
mi.addProtocol(temp, UsageTypes.ALWAYS_CONSUMED);
// mi.protocols.add(temp);
} else if (type.matches("Ppi")) {
mi.addPpi(temp, UsageTypes.ALWAYS_CONSUMED);
// mi.ppis.add(temp);
} else if (type.matches("Guid")) {
mi.addGuid(temp, UsageTypes.ALWAYS_CONSUMED);
// mi.guids.add(temp);
}
return temp;
}
return null;
}
} }

View File

@ -12,36 +12,43 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.util.regex.*; import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Macro { public class Macro {
Macro(String r8, String r9) { Macro(String r8, String r9) {
r8name = r8; r8name = r8;
r9name = r9; r9name = r9;
} }
Macro(String[] linecontext) {
r8name = linecontext[0];
r9name = linecontext[1];
}
public String r8name; Macro(String[] linecontext) {
public String r9name; r8name = linecontext[0];
r9name = linecontext[1];
}
public static Pattern ptntmacro = Pattern.compile("\\b\\w(\\w|\\d)*",Pattern.MULTILINE); public String r8name;
private static String unmacro = "VOID UINTN BOOLEAN ASSERT OPTIONAL STATIC NULL TRUE IN OUT FALSE"; public String r9name;
public static String register(Matcher mtr, ModuleInfo mi, Database db) { public static Pattern ptntmacro = Pattern.compile("\\b\\w(\\w|\\d)*",
String temp = null; Pattern.MULTILINE);
temp = mtr.group(); private static String unmacro = "VOID UINTN BOOLEAN ASSERT OPTIONAL STATIC NULL TRUE IN OUT FALSE";
mi.hashmacro.add(temp);
if (MigrationTool.db.hasMacro(temp)) { // only changed macros registered, because the database of macro has only changed ones public static String register(Matcher mtr, ModuleInfo mi, Database db) {
if (!unmacro.contains(temp)) { String temp = null;
mi.hashnonlocalmacro.add(temp);
} temp = mtr.group();
return temp; mi.hashmacro.add(temp);
} if (MigrationTool.db.hasMacro(temp)) { // only changed macros
return null; // registered, because the
} // database of macro has only
// changed ones
if (!unmacro.contains(temp)) {
mi.hashnonlocalmacro.add(temp);
}
return temp;
}
return null;
}
} }

View File

@ -13,102 +13,157 @@
package org.tianocore.migration; package org.tianocore.migration;
import java.io.File; import java.io.File;
import java.util.*; import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFileChooser; import javax.swing.JFileChooser;
import org.tianocore.UsageTypes; /**
* The class is used as the main class of the MigrationTool, maintains the main
* work flow, and all the global variables and constants. It extends nothing.
*
*/
public class MigrationTool { public class MigrationTool {
public static UI ui = null;
public static Database db = null;
public static String MIGRATIONCOMMENT = "//@MT:"; //
// These two objects are serves globally, it is always required, and only
// one instance is ever allowed.
//
public static UI ui = null;
public static boolean printModuleInfo = false; public static Database db = null;
public static boolean doCritic = false;
public static boolean defaultoutput = false;
public static final HashMap<ModuleInfo, String> ModuleInfoMap = new HashMap<ModuleInfo, String>(); //
// The global constant for MigrationTool generated comments.
//
public static String MIGRATIONCOMMENT = "//@MT:";
private static String startpath = null; //
// Global switches that are changed by user by the FirstPanel.
//
public static boolean printModuleInfo = false;
private static final void mainFlow(ModuleInfo mi) throws Exception { public static boolean doCritic = false;
ModuleReader.aimAt(mi);
SourceFileReplacer.fireAt(mi); // some adding library actions are taken here,so it must be put before "MsaWriter"
// show result public static boolean defaultoutput = false;
if (MigrationTool.printModuleInfo) {
MigrationTool.ui.println("\nModule Information : ");
MigrationTool.ui.println("Entrypoint : " + mi.entrypoint);
show(mi.protocols, "Protocol : ");
show(mi.ppis, "Ppi : ");
show(mi.guids, "Guid : ");
show(mi.hashfuncc, "call : ");
show(mi.hashfuncd, "def : ");
show(mi.hashEFIcall, "EFIcall : ");
show(mi.hashnonlocalmacro, "macro : ");
show(mi.hashnonlocalfunc, "nonlocal : ");
show(mi.hashr8only, "hashr8only : ");
}
new MsaWriter(mi).flush();
//mi.getMsaOwner().flush(MigrationTool.ModuleInfoMap.get(mi) + File.separator + "Migration_" + mi.modulename + File.separator + mi.modulename + ".___"); //
// A hashmap that associates the reference to a ModuleInfo with its
// outputpath.
//
public static final HashMap<ModuleInfo, String> ModuleInfoMap = new HashMap<ModuleInfo, String>();
if (MigrationTool.doCritic) { //
Critic.fireAt(ModuleInfoMap.get(mi) + File.separator + "Migration_" + mi.modulename); // The starting point of the MigrationTool.
} //
private static String startpath = null;
MigrationTool.ui.println("Errors Left : " + MigrationTool.db.error); /**
MigrationTool.ui.println("Complete!"); * This method defines the overall main work flow of the MigrationTool.
} *
* @param mi
* @throws Exception
*/
private static final void mainFlow(ModuleInfo mi) throws Exception {
ModuleReader.aimAt(mi);
SourceFileReplacer.fireAt(mi); // some adding library actions are taken
// here,so it must be put before
// "MsaWriter"
private static final void show(Set<String> hash, String show) { // show result
MigrationTool.ui.println(show + hash.size()); if (MigrationTool.printModuleInfo) {
MigrationTool.ui.println(hash); MigrationTool.ui.println("\nModule Information : ");
} MigrationTool.ui.println("Entrypoint : " + mi.entrypoint);
show(mi.protocols, "Protocol : ");
show(mi.ppis, "Ppi : ");
show(mi.guids, "Guid : ");
show(mi.hashfuncc, "call : ");
show(mi.hashfuncd, "def : ");
show(mi.hashEFIcall, "EFIcall : ");
show(mi.hashnonlocalmacro, "macro : ");
show(mi.hashnonlocalfunc, "nonlocal : ");
show(mi.hashr8only, "hashr8only : ");
}
new MsaWriter(mi).flush();
public static final String getTempDir(String modulepath) { // mi.getMsaOwner().flush(MigrationTool.ModuleInfoMap.get(mi) +
return "C:" + File.separator + "MigrationTool_Temp" + modulepath.replace(startpath, ""); // File.separator + "Migration_" + mi.modulename + File.separator +
} // mi.modulename + ".___");
private static final String assignOutPutPath(String inputpath) { if (MigrationTool.doCritic) {
if (MigrationTool.defaultoutput) { Critic.fireAt(ModuleInfoMap.get(mi) + File.separator + "Migration_"
return inputpath.replaceAll(Common.STRSEPARATER, "$1"); + mi.modulename);
} else { }
return MigrationTool.ui.getFilepath("Please choose where to place the output module", JFileChooser.DIRECTORIES_ONLY);
}
}
public static final void seekModule(String filepath) throws Exception { MigrationTool.ui.println("Errors Left : " + MigrationTool.db.error);
if (ModuleInfo.isModule(filepath)) { MigrationTool.ui.println("Complete!");
ModuleInfoMap.put(new ModuleInfo(filepath), assignOutPutPath(filepath)); }
}
}
public static final void startMigrateAll(String path) throws Exception { /**
startpath = path; * This method is specially written to print the message for ModuleInfo,
MigrationTool.ui.println("Project Migration"); * just for less code repeating.
MigrationTool.ui.println("Copyright (c) 2006, Intel Corporation"); *
* @param hash
* @param show
*/
private static final void show(Set<String> hash, String show) {
MigrationTool.ui.println(show + hash.size());
MigrationTool.ui.println(hash);
}
if (new File("C:" + File.separator + "MigrationTool_Temp").exists()) { /**
Common.deleteDir("C:" + File.separator + "MigrationTool_Temp"); * This method designates the location of temp directory.
} *
* @param modulepath
* @return
*/
public static final String getTempDir(String modulepath) {
return "C:" + File.separator + "MigrationTool_Temp"
+ modulepath.replace(startpath, "");
}
Common.toDoAll(path, MigrationTool.class.getMethod("seekModule", String.class), null, null, Common.DIR); private static final String assignOutPutPath(String inputpath) {
if (MigrationTool.defaultoutput) {
return inputpath.replaceAll(Common.STRSEPARATER, "$1");
} else {
return MigrationTool.ui.getFilepath(
"Please choose where to place the output module",
JFileChooser.DIRECTORIES_ONLY);
}
}
Iterator<ModuleInfo> miit = ModuleInfoMap.keySet().iterator(); public static final void seekModule(String filepath) throws Exception {
while (miit.hasNext()) { if (ModuleInfo.isModule(filepath)) {
mainFlow(miit.next()); ModuleInfoMap.put(new ModuleInfo(filepath),
} assignOutPutPath(filepath));
}
}
ModuleInfoMap.clear(); public static final void startMigrateAll(String path) throws Exception {
startpath = path;
MigrationTool.ui.println("Project Migration");
MigrationTool.ui.println("Copyright (c) 2006, Intel Corporation");
Common.deleteDir("C:" + File.separator + "MigrationTool_Temp"); if (new File("C:" + File.separator + "MigrationTool_Temp").exists()) {
} Common.deleteDir("C:" + File.separator + "MigrationTool_Temp");
}
public static void main(String[] args) throws Exception { Common.toDoAll(path, MigrationTool.class.getMethod("seekModule",
ui = FirstPanel.getInstance(); String.class), null, null, Common.DIR);
db = Database.getInstance();
} Iterator<ModuleInfo> miit = ModuleInfoMap.keySet().iterator();
while (miit.hasNext()) {
mainFlow(miit.next());
}
ModuleInfoMap.clear();
Common.deleteDir("C:" + File.separator + "MigrationTool_Temp");
}
public static void main(String[] args) throws Exception {
ui = FirstPanel.getInstance();
db = Database.getInstance();
}
} }

View File

@ -12,128 +12,164 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.io.*; import java.io.File;
import java.util.*; import java.util.HashSet;
import java.util.Set;
import org.tianocore.UsageTypes; import org.tianocore.UsageTypes;
import org.tianocore.SupportedArchitectures.Enum; import org.tianocore.SupportedArchitectures.Enum;
/* /*
Class ModuleInfo is built for scanning the source files, it contains all the needed * Class ModuleInfo is built for scanning the source files, it contains all the
information and all the temporary data. * needed information and all the temporary data.
*/ */
public final class ModuleInfo { public final class ModuleInfo {
ModuleInfo(String modulepath) throws Exception { ModuleInfo(String modulepath) throws Exception {
this.modulepath = modulepath; this.modulepath = modulepath;
this.temppath = MigrationTool.getTempDir(this.modulepath); this.temppath = MigrationTool.getTempDir(this.modulepath);
} }
public final String modulepath; public final String modulepath;
public final String temppath;
private MsaOwner msaowner = MsaOwner.initNewMsaOwner(); public final String temppath;
public String modulename = null; private MsaOwner msaowner = MsaOwner.initNewMsaOwner();
public String guidvalue = null;
public String moduletype = null;
public String entrypoint = null;
public String license = null;
public final Set<String> localmodulesources = new HashSet<String>(); //contains both .c and .h public String modulename = null;
public final Set<String> preprocessedccodes = new HashSet<String>();
public final Set<String> msaorinf = new HashSet<String>(); //only a little, hash may be too big for this
public final Set<String> infincludes = new HashSet<String>();
public final Set<String> infsources = new HashSet<String>();
public final Set<String> hashfuncc = new HashSet<String>(); public String guidvalue = null;
public final Set<String> hashfuncd = new HashSet<String>();
public final Set<String> hashnonlocalfunc = new HashSet<String>();
public final Set<String> hashnonlocalmacro = new HashSet<String>();
public final Set<String> hashEFIcall = new HashSet<String>();
public final Set<String> hashr8only = new HashSet<String>();
public final Set<String> hashmacro = new HashSet<String>();
public final Set<String> hashrequiredr9libs = new HashSet<String>(); // hashrequiredr9libs is now all added in SourceFileReplacer public String moduletype = null;
public final Set<String> guids = new HashSet<String>();
public final Set<String> protocols = new HashSet<String>();
public final Set<String> ppis = new HashSet<String>();
//-----------------------------------------------------------------------------------// public String entrypoint = null;
//addModuleType public String license = null;
//addGuidValue
//addModuleName
public final boolean addSourceFile (String filename, Enum en) { public final Set<String> localmodulesources = new HashSet<String>(); // contains
localmodulesources.add(filename); // both
return msaowner.addSourceFile(filename, en); // .c
} // and
// .h
public final boolean addProtocol (String proname, UsageTypes.Enum usage) { public final Set<String> preprocessedccodes = new HashSet<String>();
protocols.add(proname);
return msaowner.addProtocol(proname, usage);
}
public final boolean addPpi (String ppiname, UsageTypes.Enum usage) { public final Set<String> msaorinf = new HashSet<String>(); // only a
ppis.add(ppiname); // little, hash
return msaowner.addPpi(ppiname, usage); // may be too
} // big for this
public final boolean addGuid (String guidname, UsageTypes.Enum usage) { public final Set<String> infincludes = new HashSet<String>();
guids.add(guidname);
return msaowner.addGuid(guidname, usage);
}
public final boolean addLibraryClass(String name, UsageTypes.Enum usage) { public final Set<String> infsources = new HashSet<String>();
//
// This section is only for adding library classes, this functionality should be inside MsaOwner!!!
//
//if (!hashrequiredr9libs.contains(name)) {
msaowner.addLibraryClass(name, usage);
//}
//
hashrequiredr9libs.add(name);
return true;
}
//-----------------------------------------------------------------------------------// public final Set<String> hashfuncc = new HashSet<String>();
public final String getModuleType() { public final Set<String> hashfuncd = new HashSet<String>();
if (moduletype.contains("PEI")) {
return "PEIM";
} else {
return "DXE_DRIVER";
}
}
public final void enroll(String filepath) throws Exception { public final Set<String> hashnonlocalfunc = new HashSet<String>();
String temp = null;
if (filepath.contains(".inf") || filepath.contains(".msa")) {
temp = filepath.replace(modulepath + File.separator, "");
if (!temp.contains(File.separator)) { // .inf in subdirectory is not regarded
msaorinf.add(temp);
}
} else if (filepath.contains(".c") || filepath.contains(".C") || filepath.contains(".h") ||
filepath.contains(".H") || filepath.contains(".dxs") || filepath.contains(".uni") ||
filepath.contains(".s") || filepath.contains(".S") || filepath.contains(".i") ||
filepath.contains(".asm")) {
addSourceFile(filepath.replace(modulepath + File.separator, ""), null);
}
}
public static final boolean isModule(String path) { public final Set<String> hashnonlocalmacro = new HashSet<String>();
String[] list = new File(path).list();
for (int i = 0 ; i < list.length ; i++) {
if (!new File(list[i]).isDirectory()) {
if (list[i].contains(".inf") || list[i].contains(".msa")) {
return true;
}
}
}
return false;
}
public final MsaOwner getMsaOwner() { public final Set<String> hashEFIcall = new HashSet<String>();
return msaowner;
} public final Set<String> hashr8only = new HashSet<String>();
public final Set<String> hashmacro = new HashSet<String>();
public final Set<String> hashrequiredr9libs = new HashSet<String>(); // hashrequiredr9libs
// is
// now
// all
// added
// in
// SourceFileReplacer
public final Set<String> guids = new HashSet<String>();
public final Set<String> protocols = new HashSet<String>();
public final Set<String> ppis = new HashSet<String>();
// -----------------------------------------------------------------------------------//
// addModuleType
// addGuidValue
// addModuleName
public final boolean addSourceFile(String filename, Enum en) {
localmodulesources.add(filename);
return msaowner.addSourceFile(filename, en);
}
public final boolean addProtocol(String proname, UsageTypes.Enum usage) {
protocols.add(proname);
return msaowner.addProtocol(proname, usage);
}
public final boolean addPpi(String ppiname, UsageTypes.Enum usage) {
ppis.add(ppiname);
return msaowner.addPpi(ppiname, usage);
}
public final boolean addGuid(String guidname, UsageTypes.Enum usage) {
guids.add(guidname);
return msaowner.addGuid(guidname, usage);
}
public final boolean addLibraryClass(String name, UsageTypes.Enum usage) {
//
// This section is only for adding library classes, this functionality
// should be inside MsaOwner!!!
//
// if (!hashrequiredr9libs.contains(name)) {
msaowner.addLibraryClass(name, usage);
// }
//
hashrequiredr9libs.add(name);
return true;
}
// -----------------------------------------------------------------------------------//
public final String getModuleType() {
if (moduletype.contains("PEI")) {
return "PEIM";
} else {
return "DXE_DRIVER";
}
}
public final void enroll(String filepath) throws Exception {
String temp = null;
if (filepath.contains(".inf") || filepath.contains(".msa")) {
temp = filepath.replace(modulepath + File.separator, "");
if (!temp.contains(File.separator)) { // .inf in subdirectory is
// not regarded
msaorinf.add(temp);
}
} else if (filepath.contains(".c") || filepath.contains(".C")
|| filepath.contains(".h") || filepath.contains(".H")
|| filepath.contains(".dxs") || filepath.contains(".uni")
|| filepath.contains(".s") || filepath.contains(".S")
|| filepath.contains(".i") || filepath.contains(".asm")) {
addSourceFile(filepath.replace(modulepath + File.separator, ""),
null);
}
}
public static final boolean isModule(String path) {
String[] list = new File(path).list();
for (int i = 0; i < list.length; i++) {
if (!new File(list[i]).isDirectory()) {
if (list[i].contains(".inf") || list[i].contains(".msa")) {
return true;
}
}
}
return false;
}
public final MsaOwner getMsaOwner() {
return msaowner;
}
} }

View File

@ -12,331 +12,395 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.io.*; import java.io.BufferedReader;
import java.util.*; import java.io.File;
import java.util.regex.*; import java.io.FileReader;
import java.io.StringReader;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.tianocore.*; import org.tianocore.FilenameDocument;
import org.tianocore.ModuleSurfaceAreaDocument;
import org.tianocore.MsaHeaderDocument;
import org.tianocore.SourceFilesDocument;
public final class ModuleReader implements Common.ForDoAll { public final class ModuleReader implements Common.ForDoAll {
private static final ModuleReader modulereader = new ModuleReader(); private static final ModuleReader modulereader = new ModuleReader();
private ModuleInfo mi;
private final CommentLaplace commentlaplace = new CommentLaplace();
private static final Pattern ptninfequation = Pattern.compile("([^\\s]*)\\s*=\\s*([^\\s]*)"); private ModuleInfo mi;
private static final Pattern ptnsection = Pattern.compile("\\[([^\\[\\]]*)\\]([^\\[\\]]*)\\n", Pattern.MULTILINE);
private static final Pattern ptnfilename = Pattern.compile("[^\\s]+");
public final void ModuleScan() throws Exception { private final CommentLaplace commentlaplace = new CommentLaplace();
Common.toDoAll(mi.modulepath, ModuleInfo.class.getMethod("enroll", String.class), mi, null, Common.FILE);
// inf&msa private static final Pattern ptninfequation = Pattern
String filename = null; .compile("([^\\s]*)\\s*=\\s*([^\\s]*)");
if (mi.msaorinf.isEmpty()) {
MigrationTool.ui.println("No INF nor MSA file found!");
System.exit(0);
} else {
if (mi.msaorinf.size() == 1) {
filename = (String)mi.msaorinf.toArray()[0];
} else {
filename = MigrationTool.ui.choose("Found .inf or .msa file for module\n" + mi.modulepath + "\nChoose one Please", mi.msaorinf.toArray());
}
}
if (filename.contains(".inf")) { private static final Pattern ptnsection = Pattern.compile(
readInf(filename); "\\[([^\\[\\]]*)\\]([^\\[\\]]*)\\n", Pattern.MULTILINE);
} else if (filename.contains(".msa")) {
readMsa(filename);
}
// inf&msa
preProcessModule(); private static final Pattern ptnfilename = Pattern.compile("[^\\s]+");
}
private final void readMsa(String name) throws Exception { public final void ModuleScan() throws Exception {
ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory.parse(new File(mi.modulepath + File.separator + name)); Common.toDoAll(mi.modulepath, ModuleInfo.class.getMethod("enroll",
ModuleSurfaceAreaDocument.ModuleSurfaceArea msa = msadoc.getModuleSurfaceArea(); String.class), mi, null, Common.FILE);
MsaHeaderDocument.MsaHeader msaheader = msa.getMsaHeader();
mi.modulename = msaheader.getModuleName(); // inf&msa
mi.guidvalue = msaheader.getGuidValue(); String filename = null;
mi.moduletype = msaheader.getModuleType().toString(); // ??? if (mi.msaorinf.isEmpty()) {
MigrationTool.ui.println("No INF nor MSA file found!");
System.exit(0);
} else {
if (mi.msaorinf.size() == 1) {
filename = (String) mi.msaorinf.toArray()[0];
} else {
filename = MigrationTool.ui.choose(
"Found .inf or .msa file for module\n" + mi.modulepath
+ "\nChoose one Please", mi.msaorinf.toArray());
}
}
SourceFilesDocument.SourceFiles sourcefiles = msa.getSourceFiles(); if (filename.contains(".inf")) {
readInf(filename);
} else if (filename.contains(".msa")) {
readMsa(filename);
}
// inf&msa
String temp; preProcessModule();
Iterator<FilenameDocument.Filename> li = sourcefiles.getFilenameList().iterator(); }
while (li.hasNext()) {
if (!mi.localmodulesources.contains(temp = li.next().toString())) {
System.out.println("Source File Missing! : " + temp);
}
}
}
private final String extractLicense(String wholeline) throws Exception {
String tempLine;
String license = null;
BufferedReader rd = new BufferedReader(new StringReader(wholeline)); private final void readMsa(String name) throws Exception {
while ((tempLine = rd.readLine()) != null) { ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory
if (tempLine.contains("#")) { .parse(new File(mi.modulepath + File.separator + name));
if (tempLine.contains("Copyright")) { ModuleSurfaceAreaDocument.ModuleSurfaceArea msa = msadoc
// .getModuleSurfaceArea();
// Find license info. MsaHeaderDocument.MsaHeader msaheader = msa.getMsaHeader();
//
license = "";
while ((tempLine = rd.readLine())!= null) {
if (!tempLine.contains("#") ||
tempLine.contains("Module Name:") ||
tempLine.contains("Abstract:")) {
//
// We assume license ends here.
//
break;
}
license += " " + tempLine.replaceAll("\\s*[#]\\s*(.*)", "$1\n");
}
break;
}
}
}
return license;
}
private final void readInf(String name) throws Exception { mi.modulename = msaheader.getModuleName();
System.out.println("\nParsing INF file: " + name); mi.guidvalue = msaheader.getGuidValue();
String wholeline; mi.moduletype = msaheader.getModuleType().toString(); // ???
Matcher mtrinfequation;
Matcher mtrsection;
Matcher mtrfilename;
wholeline = Common.file2string(mi.modulepath + File.separator + name); SourceFilesDocument.SourceFiles sourcefiles = msa.getSourceFiles();
mi.license = extractLicense(wholeline);
mtrsection = ptnsection.matcher(wholeline);
while (mtrsection.find()) {
if (mtrsection.group(1).matches("defines")) {
mtrinfequation = ptninfequation.matcher(mtrsection.group(2));
while (mtrinfequation.find()) {
if (mtrinfequation.group(1).matches("BASE_NAME")) {
mi.modulename = mtrinfequation.group(2);
}
if (mtrinfequation.group(1).matches("FILE_GUID")) {
mi.guidvalue = mtrinfequation.group(2);
}
if (mtrinfequation.group(1).matches("COMPONENT_TYPE")) {
mi.moduletype = mtrinfequation.group(2);
}
}
}
if (mtrsection.group(1).contains("nmake.")) {
mtrinfequation = ptninfequation.matcher(mtrsection.group(2));
while (mtrinfequation.find()) {
if (mtrinfequation.group(1).matches("IMAGE_ENTRY_POINT")) {
mi.entrypoint = mtrinfequation.group(2);
}
if (mtrinfequation.group(1).matches("DPX_SOURCE")) {
if (!mi.localmodulesources.contains(mtrinfequation.group(2))) {
MigrationTool.ui.println("DPX File Missing! : " + mtrinfequation.group(2));
}
}
}
}
if (mtrsection.group(1).contains("sources.")) {
mtrfilename = ptnfilename.matcher(mtrsection.group(2));
while (mtrfilename.find()) {
mi.infsources.add(mtrfilename.group());
if (!mi.localmodulesources.contains(mtrfilename.group())) {
MigrationTool.ui.println("Warn: Source File Missing! : " + mtrfilename.group());
}
}
}
if (mtrsection.group(1).matches("includes.")) {
mtrfilename = ptnfilename.matcher(mtrsection.group(2));
while (mtrfilename.find()) {
mi.infincludes.add(mtrfilename.group());
}
}
}
}
private final void preProcessModule() throws Exception { String temp;
// according to .inf file, add extraordinary includes and sourcefiles Iterator<FilenameDocument.Filename> li = sourcefiles.getFilenameList()
Common.dirCopy(mi.modulepath, mi.temppath); // collect all Laplace.namechange to here??? .iterator();
while (li.hasNext()) {
if (!mi.localmodulesources.contains(temp = li.next().toString())) {
System.out.println("Source File Missing! : " + temp);
}
}
}
if (!mi.infincludes.isEmpty()) { private final String extractLicense(String wholeline) throws Exception {
Iterator<String> it = mi.infincludes.iterator(); String tempLine;
String tempincludename = null; String license = null;
while (it.hasNext()) {
tempincludename = it.next();
if (tempincludename.contains("..")) {
Matcher mtr = Common.PTNSEPARATER.matcher(tempincludename);
if (mtr.find() && !mtr.group(2).matches(".")) {
Common.oneLevelDirCopy(mi.modulepath.replaceAll(Common.STRSEPARATER, "$1") + File.separator + mtr.group(2), mi.temppath, ".h");
} else {
Common.oneLevelDirCopy(mi.modulepath.replaceAll(Common.STRSEPARATER, "$1"), mi.temppath, ".h");
}
}
}
}
if (!mi.infsources.isEmpty()) {
Iterator<String> it = mi.infsources.iterator();
String tempsourcename = null;
while (it.hasNext()) {
tempsourcename = it.next();
if (tempsourcename.contains("..")) {
Common.ensureDir(mi.temppath + File.separator + "MT_Parent_Sources");
Matcher mtr = Common.PTNSEPARATER.matcher(tempsourcename);
if (mtr.find()) {
Common.fileCopy(mi.modulepath.replaceAll(Common.STRSEPARATER, "$1") + File.separator + mtr.group(2), mi.temppath + File.separator + "MT_Parent_Sources" + File.separator + mtr.group(2));
}
}
}
}
Common.toDoAll(mi.temppath, this, Common.FILE); BufferedReader rd = new BufferedReader(new StringReader(wholeline));
while ((tempLine = rd.readLine()) != null) {
if (tempLine.contains("#")) {
if (tempLine.contains("Copyright")) {
//
// Find license info.
//
license = "";
while ((tempLine = rd.readLine()) != null) {
if (!tempLine.contains("#")
|| tempLine.contains("Module Name:")
|| tempLine.contains("Abstract:")) {
//
// We assume license ends here.
//
break;
}
license += " "
+ tempLine
.replaceAll("\\s*[#]\\s*(.*)", "$1\n");
}
break;
}
}
}
return license;
}
parsePreProcessedSourceCode(); private final void readInf(String name) throws Exception {
System.out.println("\nParsing INF file: " + name);
String wholeline;
Matcher mtrinfequation;
Matcher mtrsection;
Matcher mtrfilename;
} wholeline = Common.file2string(mi.modulepath + File.separator + name);
mi.license = extractLicense(wholeline);
mtrsection = ptnsection.matcher(wholeline);
while (mtrsection.find()) {
if (mtrsection.group(1).matches("defines")) {
mtrinfequation = ptninfequation.matcher(mtrsection.group(2));
while (mtrinfequation.find()) {
if (mtrinfequation.group(1).matches("BASE_NAME")) {
mi.modulename = mtrinfequation.group(2);
}
if (mtrinfequation.group(1).matches("FILE_GUID")) {
mi.guidvalue = mtrinfequation.group(2);
}
if (mtrinfequation.group(1).matches("COMPONENT_TYPE")) {
mi.moduletype = mtrinfequation.group(2);
}
}
}
if (mtrsection.group(1).contains("nmake.")) {
mtrinfequation = ptninfequation.matcher(mtrsection.group(2));
while (mtrinfequation.find()) {
if (mtrinfequation.group(1).matches("IMAGE_ENTRY_POINT")) {
mi.entrypoint = mtrinfequation.group(2);
}
if (mtrinfequation.group(1).matches("DPX_SOURCE")) {
if (!mi.localmodulesources.contains(mtrinfequation
.group(2))) {
MigrationTool.ui.println("DPX File Missing! : "
+ mtrinfequation.group(2));
}
}
}
}
if (mtrsection.group(1).contains("sources.")) {
mtrfilename = ptnfilename.matcher(mtrsection.group(2));
while (mtrfilename.find()) {
mi.infsources.add(mtrfilename.group());
if (!mi.localmodulesources.contains(mtrfilename.group())) {
MigrationTool.ui
.println("Warn: Source File Missing! : "
+ mtrfilename.group());
}
}
}
if (mtrsection.group(1).matches("includes.")) {
mtrfilename = ptnfilename.matcher(mtrsection.group(2));
while (mtrfilename.find()) {
mi.infincludes.add(mtrfilename.group());
}
}
}
}
private final void parsePreProcessedSourceCode() throws Exception { private final void preProcessModule() throws Exception {
BufferedReader rd = null; // according to .inf file, add extraordinary includes and sourcefiles
String ifile = null; Common.dirCopy(mi.modulepath, mi.temppath); // collect all
String line = null; // Laplace.namechange to
String temp = null; // here???
Iterator<String> ii = mi.localmodulesources.iterator(); if (!mi.infincludes.isEmpty()) {
while (ii.hasNext()) { Iterator<String> it = mi.infincludes.iterator();
temp = ii.next(); String tempincludename = null;
if (temp.contains(".c") || temp.contains(".dxs")) { while (it.hasNext()) {
mi.preprocessedccodes.add(temp); tempincludename = it.next();
} if (tempincludename.contains("..")) {
} Matcher mtr = Common.PTNSEPARATER.matcher(tempincludename);
if (mtr.find() && !mtr.group(2).matches(".")) {
Common.oneLevelDirCopy(mi.modulepath.replaceAll(
Common.STRSEPARATER, "$1")
+ File.separator + mtr.group(2), mi.temppath,
".h");
} else {
Common.oneLevelDirCopy(mi.modulepath.replaceAll(
Common.STRSEPARATER, "$1"), mi.temppath, ".h");
}
}
}
}
if (!mi.infsources.isEmpty()) {
Iterator<String> it = mi.infsources.iterator();
String tempsourcename = null;
while (it.hasNext()) {
tempsourcename = it.next();
if (tempsourcename.contains("..")) {
Common.ensureDir(mi.temppath + File.separator
+ "MT_Parent_Sources");
Matcher mtr = Common.PTNSEPARATER.matcher(tempsourcename);
if (mtr.find()) {
Common.fileCopy(mi.modulepath.replaceAll(
Common.STRSEPARATER, "$1")
+ File.separator + mtr.group(2), mi.temppath
+ File.separator + "MT_Parent_Sources"
+ File.separator + mtr.group(2));
}
}
}
}
ii = mi.preprocessedccodes.iterator(); Common.toDoAll(mi.temppath, this, Common.FILE);
Pattern patefifuncc = Pattern.compile("g?(BS|RT)\\s*->\\s*([a-zA-Z_]\\w*)",Pattern.MULTILINE); parsePreProcessedSourceCode();
Matcher matguid;
Matcher matfuncc;
Matcher matfuncd;
Matcher matenclosereplace;
Matcher matefifuncc;
Matcher matmacro;
while (ii.hasNext()) { }
StringBuffer wholefile = new StringBuffer();
ifile = ii.next();
rd = new BufferedReader(new FileReader(mi.temppath + File.separator + ifile));
while ((line = rd.readLine()) != null) {
wholefile.append(line + '\n');
}
line = wholefile.toString();
// find guid private final void parsePreProcessedSourceCode() throws Exception {
matguid = Guid.ptnguid.matcher(line); // several ways to implement this , which one is faster ? : BufferedReader rd = null;
while (matguid.find()) { // 1.currently , find once , then call to identify which is it String ifile = null;
if ((temp = Guid.register(matguid, mi, MigrationTool.db)) != null) { // 2.use 3 different matchers , search 3 times to find each String line = null;
//matguid.appendReplacement(result, MigrationTool.db.getR9Guidname(temp)); // search the database for all 3 kinds of guids , high cost String temp = null;
}
}
//matguid.appendTail(result);
//line = result.toString();
// find EFI call in form of '->' , many 'gUnicodeCollationInterface->' like things are not changed Iterator<String> ii = mi.localmodulesources.iterator();
// This item is not simply replaced , special operation is required. while (ii.hasNext()) {
matefifuncc = patefifuncc.matcher(line); temp = ii.next();
while (matefifuncc.find()) { if (temp.contains(".c") || temp.contains(".dxs")) {
mi.hashEFIcall.add(matefifuncc.group(2)); mi.preprocessedccodes.add(temp);
} }
}
// find function call ii = mi.preprocessedccodes.iterator();
matfuncc = Func.ptnfuncc.matcher(line);
while (matfuncc.find()) {
if ((temp = Func.register(matfuncc, mi, MigrationTool.db)) != null) {
//MigrationTool.ui.println(ifile + " dofunc " + temp);
//matfuncc.appendReplacement(result, MigrationTool.db.getR9Func(temp));
}
}
//matfuncc.appendTail(result);
//line = result.toString();
// find macro Pattern patefifuncc = Pattern.compile(
matmacro = Macro.ptntmacro.matcher(line); "g?(BS|RT)\\s*->\\s*([a-zA-Z_]\\w*)", Pattern.MULTILINE);
while (matmacro.find()) { Matcher matguid;
if ((temp = Macro.register(matmacro, mi, MigrationTool.db)) != null) { Matcher matfuncc;
} Matcher matfuncd;
} Matcher matenclosereplace;
Matcher matefifuncc;
Matcher matmacro;
// find function definition while (ii.hasNext()) {
// replace all {} to @ StringBuffer wholefile = new StringBuffer();
while ((matenclosereplace = Func.ptnbrace.matcher(line)).find()) { ifile = ii.next();
line = matenclosereplace.replaceAll("@"); rd = new BufferedReader(new FileReader(mi.temppath + File.separator
} + ifile));
while ((line = rd.readLine()) != null) {
wholefile.append(line + '\n');
}
line = wholefile.toString();
matfuncd = Func.ptnfuncd.matcher(line); // find guid
while (matfuncd.find()) { matguid = Guid.ptnguid.matcher(line); // several ways to implement
if ((temp = Func.register(matfuncd, mi, MigrationTool.db)) != null) { // this , which one is
} // faster ? :
} while (matguid.find()) { // 1.currently , find once , then call
} // to identify which is it
if ((temp = Guid.register(matguid, mi, MigrationTool.db)) != null) { // 2.use
// 3
// different
// matchers
// ,
// search
// 3
// times
// to
// find
// each
// matguid.appendReplacement(result,
// MigrationTool.db.getR9Guidname(temp)); // search the
// database for all 3 kinds of guids , high cost
}
}
// matguid.appendTail(result);
// line = result.toString();
// op on hash // find EFI call in form of '->' , many
Iterator<String> funcci = mi.hashfuncc.iterator(); // 'gUnicodeCollationInterface->' like things are not changed
while (funcci.hasNext()) { // This item is not simply replaced , special operation is required.
if (!mi.hashfuncd.contains(temp = funcci.next()) && !mi.hashEFIcall.contains(temp)) { matefifuncc = patefifuncc.matcher(line);
mi.hashnonlocalfunc.add(temp); // this set contains both changed and not changed items while (matefifuncc.find()) {
} mi.hashEFIcall.add(matefifuncc.group(2));
} }
}
public class CommentLaplace extends Common.Laplace { // find function call
public String operation(String wholeline) { matfuncc = Func.ptnfuncc.matcher(line);
StringBuffer wholebuffer = new StringBuffer(); while (matfuncc.find()) {
String templine = null; if ((temp = Func.register(matfuncc, mi, MigrationTool.db)) != null) {
Pattern ptnincludefile = Pattern.compile("[\"<](.*[.]h)[\">]"); // MigrationTool.ui.println(ifile + " dofunc " + temp);
Pattern ptninclude = Pattern.compile("#include\\s*(.*)"); // matfuncc.appendReplacement(result,
Matcher mtrinclude = ptninclude.matcher(wholeline); // MigrationTool.db.getR9Func(temp));
Matcher mtrincludefile = null; }
while (mtrinclude.find()) { }
mtrincludefile = ptnincludefile.matcher(mtrinclude.group(1)); // matfuncc.appendTail(result);
if (mtrincludefile.find() && mi.localmodulesources.contains(mtrincludefile.group(1))) { // line = result.toString();
templine = mtrinclude.group();
} else {
templine = MigrationTool.MIGRATIONCOMMENT + mtrinclude.group();
}
mtrinclude.appendReplacement(wholebuffer, templine);
}
mtrinclude.appendTail(wholebuffer);
return wholebuffer.toString();
}
public boolean recognize(String filename) { // find macro
return filename.contains(".c") || filename.contains(".h") || filename.contains(".dxs"); matmacro = Macro.ptntmacro.matcher(line);
} while (matmacro.find()) {
if ((temp = Macro.register(matmacro, mi, MigrationTool.db)) != null) {
}
}
public String namechange(String oldname) { // find function definition
return oldname; // replace all {} to @
} while ((matenclosereplace = Func.ptnbrace.matcher(line)).find()) {
} line = matenclosereplace.replaceAll("@");
}
//-----------------------------------ForDoAll-----------------------------------// matfuncd = Func.ptnfuncd.matcher(line);
public void run(String filepath) throws Exception { while (matfuncd.find()) {
String name = mi.temppath + File.separator + filepath.replace(mi.temppath + File.separator, ""); if ((temp = Func.register(matfuncd, mi, MigrationTool.db)) != null) {
if (commentlaplace.recognize(name)) { }
commentlaplace.transform(name, name); }
} }
}
public boolean filter(File dir) { // op on hash
return true; Iterator<String> funcci = mi.hashfuncc.iterator();
} while (funcci.hasNext()) {
//-----------------------------------ForDoAll-----------------------------------// if (!mi.hashfuncd.contains(temp = funcci.next())
&& !mi.hashEFIcall.contains(temp)) {
mi.hashnonlocalfunc.add(temp); // this set contains both
// changed and not changed items
}
}
}
public final void setModuleInfo(ModuleInfo m) { public class CommentLaplace extends Common.Laplace {
mi = m; public String operation(String wholeline) {
} StringBuffer wholebuffer = new StringBuffer();
String templine = null;
Pattern ptnincludefile = Pattern.compile("[\"<](.*[.]h)[\">]");
Pattern ptninclude = Pattern.compile("#include\\s*(.*)");
Matcher mtrinclude = ptninclude.matcher(wholeline);
Matcher mtrincludefile = null;
while (mtrinclude.find()) {
mtrincludefile = ptnincludefile.matcher(mtrinclude.group(1));
if (mtrincludefile.find()
&& mi.localmodulesources.contains(mtrincludefile
.group(1))) {
templine = mtrinclude.group();
} else {
templine = MigrationTool.MIGRATIONCOMMENT
+ mtrinclude.group();
}
mtrinclude.appendReplacement(wholebuffer, templine);
}
mtrinclude.appendTail(wholebuffer);
return wholebuffer.toString();
}
public static final void aimAt(ModuleInfo mi) throws Exception { public boolean recognize(String filename) {
modulereader.setModuleInfo(mi); return filename.contains(".c") || filename.contains(".h")
modulereader.ModuleScan(); || filename.contains(".dxs");
} }
public String namechange(String oldname) {
return oldname;
}
}
// -----------------------------------ForDoAll-----------------------------------//
public void run(String filepath) throws Exception {
String name = mi.temppath + File.separator
+ filepath.replace(mi.temppath + File.separator, "");
if (commentlaplace.recognize(name)) {
commentlaplace.transform(name, name);
}
}
public boolean filter(File dir) {
return true;
}
// -----------------------------------ForDoAll-----------------------------------//
public final void setModuleInfo(ModuleInfo m) {
mi = m;
}
public static final void aimAt(ModuleInfo mi) throws Exception {
modulereader.setModuleInfo(mi);
modulereader.ModuleScan();
}
} }

View File

@ -14,369 +14,412 @@ package org.tianocore.migration;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.FileWriter; import java.io.FileWriter;
import java.util.*; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlOptions;
import org.tianocore.*; import org.tianocore.ExternsDocument;
import org.tianocore.FilenameDocument;
import org.tianocore.GuidsDocument;
import org.tianocore.LibraryClassDefinitionsDocument;
import org.tianocore.LibraryClassDocument;
import org.tianocore.LicenseDocument;
import org.tianocore.ModuleDefinitionsDocument;
import org.tianocore.ModuleSurfaceAreaDocument;
import org.tianocore.ModuleTypeDef;
import org.tianocore.MsaHeaderDocument;
import org.tianocore.PPIsDocument;
import org.tianocore.PackageDependenciesDocument;
import org.tianocore.ProtocolsDocument;
import org.tianocore.SourceFilesDocument;
import org.tianocore.SupportedArchitectures;
import org.tianocore.UsageTypes;
import org.tianocore.SupportedArchitectures.Enum; import org.tianocore.SupportedArchitectures.Enum;
public class MsaOwner { public class MsaOwner {
public static final String COPYRIGHT = "Copyright (c) 2006, Intel Corporation"; public static final String COPYRIGHT = "Copyright (c) 2006, Intel Corporation";
public static final String VERSION = "1.0";
public static final String ABSTRACT = "Component name for module ";
public static final String DESCRIPTION = "FIX ME!";
public static final String LICENSE = "All rights reserved.\n" +
" This software and associated documentation (if any) is furnished\n" +
" under a license and may only be used or copied in accordance\n" +
" with the terms of the license. Except as permitted by such\n" +
" license, no part of this software or documentation may be\n" +
" reproduced, stored in a retrieval system, or transmitted in any\n" +
" form or by any means without the express written consent of\n" +
" Intel Corporation.";
public static final String SPECIFICATION = "FRAMEWORK_BUILD_PACKAGING_SPECIFICATION 0x00000052";
public static final Enum IA32 = SupportedArchitectures.IA_32; public static final String VERSION = "1.0";
public static final Enum X64 = SupportedArchitectures.X_64;
public static final Enum IPF = SupportedArchitectures.IPF;
public static final Enum EBC = SupportedArchitectures.EBC;
private ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory.newInstance(); public static final String ABSTRACT = "Component name for module ";
private ModuleSurfaceAreaDocument.ModuleSurfaceArea msa = null; public static final String DESCRIPTION = "FIX ME!";
private MsaHeaderDocument.MsaHeader msaheader = null;
private LicenseDocument.License license = null;
private ModuleDefinitionsDocument.ModuleDefinitions moduledefinitions = null;
private SourceFilesDocument.SourceFiles sourcefiles = null; //found local .h files are not written
private GuidsDocument.Guids guids = null;
private ProtocolsDocument.Protocols protocols = null;
private PPIsDocument.PPIs ppis = null;
private PackageDependenciesDocument.PackageDependencies packagedependencies = null;
private LibraryClassDefinitionsDocument.LibraryClassDefinitions libclassdefs = null;
private ExternsDocument.Externs externs = null;
private List<Enum> listarch = new ArrayList<Enum>(); public static final String LICENSE = "All rights reserved.\n"
//private Map<String, Enum> mapfilenames = new HashMap<String, Enum>(); //this need to be installed manually when msa is to be written + " This software and associated documentation (if any) is furnished\n"
//private Map<String, UsageTypes.Enum> mapprotocols = new HashMap<String, UsageTypes.Enum>(); + " under a license and may only be used or copied in accordance\n"
+ " with the terms of the license. Except as permitted by such\n"
+ " license, no part of this software or documentation may be\n"
+ " reproduced, stored in a retrieval system, or transmitted in any\n"
+ " form or by any means without the express written consent of\n"
+ " Intel Corporation.";
//-----------------------------msaheader-------------------------------------// public static final String SPECIFICATION = "FRAMEWORK_BUILD_PACKAGING_SPECIFICATION 0x00000052";
public final boolean addLibraryClass (String name, UsageTypes.Enum usage) { public static final Enum IA32 = SupportedArchitectures.IA_32;
/*
if (!libclassdefs.getLibraryClassList().contains(name)) {
LibraryClassDocument.LibraryClass classname;
classname = libclassdefs.addNewLibraryClass();
classname.setKeyword(name);
classname.setUsage(usage);
return true;
} else {
return false;
}
*/
if (name == null) {
return false;
} else {
Iterator<LibraryClassDocument.LibraryClass> classit = libclassdefs.getLibraryClassList().iterator();
while (classit.hasNext()) {
if (classit.next().getKeyword().matches(name)) {
//MigrationTool.ui.println ("Warning: Duplicate LibraryClass");
return false;
}
}
LibraryClassDocument.LibraryClass classname; public static final Enum X64 = SupportedArchitectures.X_64;
classname = libclassdefs.addNewLibraryClass();
classname.setKeyword(name);
classname.setUsage(usage);
return true;
} public static final Enum IPF = SupportedArchitectures.IPF;
}
public final boolean addGuid (String guidname, UsageTypes.Enum usage) { public static final Enum EBC = SupportedArchitectures.EBC;
if (guids == null) {
guids = msa.addNewGuids();
}
Iterator<GuidsDocument.Guids.GuidCNames> guidit = guids.getGuidCNamesList().iterator(); private ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory
while (guidit.hasNext()) { .newInstance();
if (guidit.next().getGuidCName() == guidname) {
//MigrationTool.ui.println ("Warning: Duplicate Guid");
return false;
}
}
GuidsDocument.Guids.GuidCNames guid; private ModuleSurfaceAreaDocument.ModuleSurfaceArea msa = null;
guid = guids.addNewGuidCNames();
guid.setGuidCName(guidname);
guid.setUsage(usage);
return true;
}
private MsaHeaderDocument.MsaHeader msaheader = null;
public final boolean addPpi (String ppiname, UsageTypes.Enum usage) { private LicenseDocument.License license = null;
if (ppis == null) {
ppis = msa.addNewPPIs();
}
Iterator<PPIsDocument.PPIs.Ppi> ppiit = ppis.getPpiList().iterator(); private ModuleDefinitionsDocument.ModuleDefinitions moduledefinitions = null;
while (ppiit.hasNext()) {
if (ppiit.next().getPpiCName() == ppiname) {
//MigrationTool.ui.println ("Warning: Duplicate Ppi");
return false;
}
}
PPIsDocument.PPIs.Ppi ppi; private SourceFilesDocument.SourceFiles sourcefiles = null; // found local
ppi = ppis.addNewPpi(); // .h files are
ppi.setPpiCName(ppiname); // not written
ppi.setUsage(usage);
return true;
}
public final boolean addProtocol (String proname, UsageTypes.Enum usage) { private GuidsDocument.Guids guids = null;
if (protocols == null) {
protocols = msa.addNewProtocols();
}
Iterator<ProtocolsDocument.Protocols.Protocol> proit = protocols.getProtocolList().iterator(); private ProtocolsDocument.Protocols protocols = null;
while (proit.hasNext()) {
if (proit.next().getProtocolCName() == proname) {
//MigrationTool.ui.println ("Warning: Duplicate Protocol");
return false;
}
}
ProtocolsDocument.Protocols.Protocol protocol; private PPIsDocument.PPIs ppis = null;
protocol = protocols.addNewProtocol();
protocol.setProtocolCName(proname);
protocol.setUsage(usage);
return true;
}
public final boolean addSourceFile (String name, Enum en) { private PackageDependenciesDocument.PackageDependencies packagedependencies = null;
Iterator<FilenameDocument.Filename> fileit = sourcefiles.getFilenameList().iterator();
while (fileit.hasNext()) {
if (fileit.next().getStringValue() == name) {
MigrationTool.ui.println ("Warning: Duplicate SourceFileName");
return false;
}
}
FilenameDocument.Filename filename; private LibraryClassDefinitionsDocument.LibraryClassDefinitions libclassdefs = null;
List<Enum> arch = new ArrayList<Enum>();
filename = sourcefiles.addNewFilename();
filename.setStringValue(name);
arch.add(en);
filename.setSupArchList(arch);
return true;
}
// entry point todo private ExternsDocument.Externs externs = null;
public final boolean setupExternSpecification () { private List<Enum> listarch = new ArrayList<Enum>();
addExternSpecification("EFI_SPECIFICATION_VERSION 0x00020000");
addExternSpecification("EDK_RELEASE_VERSION 0x00020000");
return true;
}
public final boolean addExternSpecification (String specification) { // private Map<String, Enum> mapfilenames = new HashMap<String, Enum>();
if (externs.getSpecificationList().contains(specification)) { // //this need to be installed manually when msa is to be written
return false; // private Map<String, UsageTypes.Enum> mapprotocols = new HashMap<String,
} else { // UsageTypes.Enum>();
externs.addSpecification(specification);
return true;
}
}
public final boolean setupPackageDependencies() { // -----------------------------msaheader-------------------------------------//
Iterator<String> it;
//
// For now, simply add all package guids in the database.
//
it = MigrationTool.db.dumpAllPkgGuid();
while (it.hasNext()) {
packagedependencies.addNewPackage().setPackageGuid(it.next());
}
return true;
}
public final boolean addPackage (String guid) { public final boolean addLibraryClass(String name, UsageTypes.Enum usage) {
if (packagedependencies.getPackageList().contains(guid)) { /*
return false; * if (!libclassdefs.getLibraryClassList().contains(name)) {
} else { * LibraryClassDocument.LibraryClass classname; classname =
packagedependencies.addNewPackage().setPackageGuid(guid); * libclassdefs.addNewLibraryClass(); classname.setKeyword(name);
return true; * classname.setUsage(usage); return true; } else { return false; }
} */
} if (name == null) {
return false;
} else {
Iterator<LibraryClassDocument.LibraryClass> classit = libclassdefs
.getLibraryClassList().iterator();
while (classit.hasNext()) {
if (classit.next().getKeyword().matches(name)) {
// MigrationTool.ui.println ("Warning: Duplicate
// LibraryClass");
return false;
}
}
public final boolean setupModuleDefinitions () { //????????? give this job to moduleinfo LibraryClassDocument.LibraryClass classname;
moduledefinitions.setBinaryModule(false); classname = libclassdefs.addNewLibraryClass();
moduledefinitions.setOutputFileBasename(msaheader.getModuleName()); classname.setKeyword(name);
return true; classname.setUsage(usage);
} return true;
public final boolean addSupportedArchitectures (Enum arch) {
if (listarch.contains(arch)) {
return false;
} else {
listarch.add(arch);
return true;
}
}
public final boolean addSpecification (String specification) { }
if (msaheader.getSpecification() == null) { }
if (specification == null) {
msaheader.setSpecification(SPECIFICATION);
} else {
msaheader.setSpecification(specification);
}
return true;
} else {
MigrationTool.ui.println ("Warning: Duplicate Specification");
return false;
}
}
public final boolean addLicense (String licensecontent) { public final boolean addGuid(String guidname, UsageTypes.Enum usage) {
if (msaheader.getLicense() == null) { if (guids == null) {
license = msaheader.addNewLicense(); guids = msa.addNewGuids();
if (licensecontent == null) { }
license.setStringValue(LICENSE);
} else {
license.setStringValue(licensecontent);
}
return true;
} else {
MigrationTool.ui.println ("Warning: Duplicate License");
return false;
}
}
public final boolean addDescription (String description) { Iterator<GuidsDocument.Guids.GuidCNames> guidit = guids
if (msaheader.getDescription() == null) { .getGuidCNamesList().iterator();
if (description == null) { while (guidit.hasNext()) {
msaheader.setDescription(DESCRIPTION); if (guidit.next().getGuidCName() == guidname) {
} else { // MigrationTool.ui.println ("Warning: Duplicate Guid");
msaheader.setDescription(description); return false;
} }
return true; }
} else {
MigrationTool.ui.println ("Warning: Duplicate Description");
return false;
}
}
public final boolean addAbstract (String abs) { GuidsDocument.Guids.GuidCNames guid;
if (msaheader.getAbstract() == null) { guid = guids.addNewGuidCNames();
if (abs == null) { guid.setGuidCName(guidname);
msaheader.setAbstract(ABSTRACT + msaheader.getModuleName()); guid.setUsage(usage);
} else { return true;
msaheader.setVersion(abs); }
}
return true;
} else {
MigrationTool.ui.println ("Warning: Duplicate Abstract");
return false;
}
}
public final boolean addVersion (String version) { public final boolean addPpi(String ppiname, UsageTypes.Enum usage) {
if (msaheader.getVersion() == null) { if (ppis == null) {
if (version == null) { ppis = msa.addNewPPIs();
msaheader.setVersion(VERSION); }
} else {
msaheader.setVersion(version);
}
return true;
} else {
MigrationTool.ui.println ("Warning: Duplicate Version");
return false;
}
}
public final boolean addCopyRight (String copyright) { Iterator<PPIsDocument.PPIs.Ppi> ppiit = ppis.getPpiList().iterator();
if (msaheader.getCopyright() == null) { while (ppiit.hasNext()) {
if (copyright == null) { if (ppiit.next().getPpiCName() == ppiname) {
msaheader.setCopyright(COPYRIGHT); // MigrationTool.ui.println ("Warning: Duplicate Ppi");
} else { return false;
msaheader.setCopyright(copyright); }
} }
return true;
} else {
MigrationTool.ui.println ("Warning: Duplicate CopyRight");
return false;
}
}
public final boolean addModuleType (String moduletype) { PPIsDocument.PPIs.Ppi ppi;
if (msaheader.getModuleType() == null) { ppi = ppis.addNewPpi();
msaheader.setModuleType(ModuleTypeDef.Enum.forString(moduletype)); ppi.setPpiCName(ppiname);
return true; ppi.setUsage(usage);
} else { return true;
MigrationTool.ui.println ("Warning: Duplicate ModuleType"); }
return false;
}
}
public final boolean addGuidValue (String guidvalue) { public final boolean addProtocol(String proname, UsageTypes.Enum usage) {
if (msaheader.getGuidValue() == null) { if (protocols == null) {
msaheader.setGuidValue(guidvalue); protocols = msa.addNewProtocols();
return true; }
} else {
MigrationTool.ui.println ("Warning: Duplicate GuidValue");
return false;
}
}
public final boolean addModuleName (String modulename) { Iterator<ProtocolsDocument.Protocols.Protocol> proit = protocols
if (msaheader.getModuleName() == null) { .getProtocolList().iterator();
msaheader.setModuleName(modulename); while (proit.hasNext()) {
return true; if (proit.next().getProtocolCName() == proname) {
} else { // MigrationTool.ui.println ("Warning: Duplicate Protocol");
MigrationTool.ui.println ("Warning: Duplicate ModuleName"); return false;
return false; }
} }
}
//-----------------------------msaheader-------------------------------------//
private final void fullfill () throws Exception { ProtocolsDocument.Protocols.Protocol protocol;
addCopyRight(null); protocol = protocols.addNewProtocol();
addVersion(null); protocol.setProtocolCName(proname);
addAbstract(null); protocol.setUsage(usage);
addDescription(null); return true;
addLicense(null); }
addSpecification(null);
}
public final void flush(String outputpath) throws Exception { public final boolean addSourceFile(String name, Enum en) {
XmlOptions options = new XmlOptions(); Iterator<FilenameDocument.Filename> fileit = sourcefiles
.getFilenameList().iterator();
while (fileit.hasNext()) {
if (fileit.next().getStringValue() == name) {
MigrationTool.ui.println("Warning: Duplicate SourceFileName");
return false;
}
}
options.setCharacterEncoding("UTF-8"); FilenameDocument.Filename filename;
options.setSavePrettyPrint(); List<Enum> arch = new ArrayList<Enum>();
options.setSavePrettyPrintIndent(2); filename = sourcefiles.addNewFilename();
options.setUseDefaultNamespace(); filename.setStringValue(name);
arch.add(en);
filename.setSupArchList(arch);
return true;
}
BufferedWriter bw = new BufferedWriter(new FileWriter(outputpath)); // entry point todo
fullfill();
msadoc.save(bw, options);
bw.flush();
bw.close();
}
private final MsaOwner init () { public final boolean setupExternSpecification() {
msa = msadoc.addNewModuleSurfaceArea(); addExternSpecification("EFI_SPECIFICATION_VERSION 0x00020000");
msaheader = msa.addNewMsaHeader(); addExternSpecification("EDK_RELEASE_VERSION 0x00020000");
moduledefinitions = msa.addNewModuleDefinitions(); return true;
moduledefinitions.setSupportedArchitectures(listarch); }
sourcefiles = msa.addNewSourceFiles(); public final boolean addExternSpecification(String specification) {
packagedependencies = msa.addNewPackageDependencies(); if (externs.getSpecificationList().contains(specification)) {
libclassdefs = msa.addNewLibraryClassDefinitions(); return false;
externs = msa.addNewExterns(); } else {
return this; externs.addSpecification(specification);
} return true;
}
}
public static final MsaOwner initNewMsaOwner() { public final boolean setupPackageDependencies() {
return new MsaOwner().init(); Iterator<String> it;
} //
// For now, simply add all package guids in the database.
//
it = MigrationTool.db.dumpAllPkgGuid();
while (it.hasNext()) {
packagedependencies.addNewPackage().setPackageGuid(it.next());
}
return true;
}
public final boolean addPackage(String guid) {
if (packagedependencies.getPackageList().contains(guid)) {
return false;
} else {
packagedependencies.addNewPackage().setPackageGuid(guid);
return true;
}
}
public final boolean setupModuleDefinitions() { // ????????? give this job
// to moduleinfo
moduledefinitions.setBinaryModule(false);
moduledefinitions.setOutputFileBasename(msaheader.getModuleName());
return true;
}
public final boolean addSupportedArchitectures(Enum arch) {
if (listarch.contains(arch)) {
return false;
} else {
listarch.add(arch);
return true;
}
}
public final boolean addSpecification(String specification) {
if (msaheader.getSpecification() == null) {
if (specification == null) {
msaheader.setSpecification(SPECIFICATION);
} else {
msaheader.setSpecification(specification);
}
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate Specification");
return false;
}
}
public final boolean addLicense(String licensecontent) {
if (msaheader.getLicense() == null) {
license = msaheader.addNewLicense();
if (licensecontent == null) {
license.setStringValue(LICENSE);
} else {
license.setStringValue(licensecontent);
}
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate License");
return false;
}
}
public final boolean addDescription(String description) {
if (msaheader.getDescription() == null) {
if (description == null) {
msaheader.setDescription(DESCRIPTION);
} else {
msaheader.setDescription(description);
}
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate Description");
return false;
}
}
public final boolean addAbstract(String abs) {
if (msaheader.getAbstract() == null) {
if (abs == null) {
msaheader.setAbstract(ABSTRACT + msaheader.getModuleName());
} else {
msaheader.setVersion(abs);
}
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate Abstract");
return false;
}
}
public final boolean addVersion(String version) {
if (msaheader.getVersion() == null) {
if (version == null) {
msaheader.setVersion(VERSION);
} else {
msaheader.setVersion(version);
}
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate Version");
return false;
}
}
public final boolean addCopyRight(String copyright) {
if (msaheader.getCopyright() == null) {
if (copyright == null) {
msaheader.setCopyright(COPYRIGHT);
} else {
msaheader.setCopyright(copyright);
}
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate CopyRight");
return false;
}
}
public final boolean addModuleType(String moduletype) {
if (msaheader.getModuleType() == null) {
msaheader.setModuleType(ModuleTypeDef.Enum.forString(moduletype));
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate ModuleType");
return false;
}
}
public final boolean addGuidValue(String guidvalue) {
if (msaheader.getGuidValue() == null) {
msaheader.setGuidValue(guidvalue);
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate GuidValue");
return false;
}
}
public final boolean addModuleName(String modulename) {
if (msaheader.getModuleName() == null) {
msaheader.setModuleName(modulename);
return true;
} else {
MigrationTool.ui.println("Warning: Duplicate ModuleName");
return false;
}
}
// -----------------------------msaheader-------------------------------------//
private final void fullfill() throws Exception {
addCopyRight(null);
addVersion(null);
addAbstract(null);
addDescription(null);
addLicense(null);
addSpecification(null);
}
public final void flush(String outputpath) throws Exception {
XmlOptions options = new XmlOptions();
options.setCharacterEncoding("UTF-8");
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(2);
options.setUseDefaultNamespace();
BufferedWriter bw = new BufferedWriter(new FileWriter(outputpath));
fullfill();
msadoc.save(bw, options);
bw.flush();
bw.close();
}
private final MsaOwner init() {
msa = msadoc.addNewModuleSurfaceArea();
msaheader = msa.addNewMsaHeader();
moduledefinitions = msa.addNewModuleDefinitions();
moduledefinitions.setSupportedArchitectures(listarch);
sourcefiles = msa.addNewSourceFiles();
packagedependencies = msa.addNewPackageDependencies();
libclassdefs = msa.addNewLibraryClassDefinitions();
externs = msa.addNewExterns();
return this;
}
public static final MsaOwner initNewMsaOwner() {
return new MsaOwner().init();
}
} }

View File

@ -1,129 +1,166 @@
package org.tianocore.migration; package org.tianocore.migration;
import java.awt.*; import java.awt.GridBagLayout;
import java.awt.event.*; import java.awt.event.ActionEvent;
import javax.swing.*; import java.awt.event.ActionListener;
import javax.swing.tree.*; import java.awt.event.MouseAdapter;
import javax.xml.parsers.*; import java.awt.event.MouseEvent;
import org.w3c.dom.*;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MsaTreeEditor extends JPanel { public class MsaTreeEditor extends JPanel {
/** /**
* Define class Serial Version UID * Define class Serial Version UID
*/ */
private static final long serialVersionUID = 3169905938472150649L; private static final long serialVersionUID = 3169905938472150649L;
MsaTreeEditor() throws Exception { MsaTreeEditor() throws Exception {
rootNode = new DefaultMutableTreeNode("Root Node"); rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode); treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel); tree = new JTree(treeModel);
tree.setEditable(true); tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.getSelectionModel().setSelectionMode(
tree.setShowsRootHandles(false); TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addMouseListener(mouseadapter); tree.setShowsRootHandles(false);
tree.addMouseListener(mouseadapter);
JScrollPane scrollPane = new JScrollPane(tree); JScrollPane scrollPane = new JScrollPane(tree);
//scrollPane.setSize(800, 600); // scrollPane.setSize(800, 600);
add(scrollPane); add(scrollPane);
popupmenu = new JPopupMenu(); popupmenu = new JPopupMenu();
menuitemadd = new JMenuItem("Add Node"); menuitemadd = new JMenuItem("Add Node");
menuitemdel = new JMenuItem("Delete Node"); menuitemdel = new JMenuItem("Delete Node");
menuitemedit = new JMenuItem("Edit Node"); menuitemedit = new JMenuItem("Edit Node");
popupmenu.add(menuitemadd); popupmenu.add(menuitemadd);
popupmenu.add(menuitemdel); popupmenu.add(menuitemdel);
popupmenu.add(menuitemedit); popupmenu.add(menuitemedit);
menuitemadd.addActionListener(actionListener); menuitemadd.addActionListener(actionListener);
menuitemdel.addActionListener(actionListener); menuitemdel.addActionListener(actionListener);
menuitemedit.addActionListener(actionListener); menuitemedit.addActionListener(actionListener);
genDomTree(MigrationTool.ui.getFilepath("Select a msa file", JFileChooser.FILES_AND_DIRECTORIES)); genDomTree(MigrationTool.ui.getFilepath("Select a msa file",
} JFileChooser.FILES_AND_DIRECTORIES));
}
//private ModuleSurfaceAreaDocument msadoc; // private ModuleSurfaceAreaDocument msadoc;
private JTree tree; private JTree tree;
private DefaultMutableTreeNode rootNode;
private DefaultTreeModel treeModel;
private JMenuItem menuitemadd, menuitemdel, menuitemedit;
private JPopupMenu popupmenu; private DefaultMutableTreeNode rootNode;
private MouseAdapter mouseadapter = new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
if (me.getClickCount() == 1 && SwingUtilities.isRightMouseButton(me)) {
tree.setSelectionPath(tree.getPathForLocation(me.getX(), me.getY()));
popupmenu.show(tree, me.getX(), me.getY());
}
}
};
private ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == menuitemadd) {
addNode();
} else if (ae.getSource() == menuitemdel) {
delNode();
} else if (ae.getSource() == menuitemedit) {
editNode();
}
}
};
private void editNode() { private DefaultTreeModel treeModel;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)(tree.getSelectionPath().getLastPathComponent());
Element element = (Element)node.getUserObject();
System.out.println(element.getTextContent());
}
private void delNode() { private JMenuItem menuitemadd, menuitemdel, menuitemedit;
treeModel.removeNodeFromParent((DefaultMutableTreeNode)(tree.getSelectionPath().getLastPathComponent()));
}
private void addNode() { private JPopupMenu popupmenu;
addNode((DefaultMutableTreeNode)(tree.getSelectionPath().getLastPathComponent()), MigrationTool.ui.getInput("Input Node Name"));
}
private DefaultMutableTreeNode addNode(DefaultMutableTreeNode parentNode, Object child) { private MouseAdapter mouseadapter = new MouseAdapter() {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child); public void mouseReleased(MouseEvent me) {
treeModel.insertNodeInto(childNode, parentNode, parentNode.getChildCount()); if (me.getClickCount() == 1
tree.scrollPathToVisible(new TreePath(childNode.getPath())); && SwingUtilities.isRightMouseButton(me)) {
return childNode; tree.setSelectionPath(tree.getPathForLocation(me.getX(), me
} .getY()));
popupmenu.show(tree, me.getX(), me.getY());
}
}
};
private final void handleNode(Node node, DefaultMutableTreeNode parentNode) { private ActionListener actionListener = new ActionListener() {
DefaultMutableTreeNode curNode = null; public void actionPerformed(ActionEvent ae) {
if (node.getNodeType() == Node.ELEMENT_NODE) { if (ae.getSource() == menuitemadd) {
System.out.println("elem"); addNode();
curNode = addNode(parentNode, node); } else if (ae.getSource() == menuitemdel) {
} else if (node.getNodeType() == Node.DOCUMENT_NODE){ delNode();
System.out.println("doc"); } else if (ae.getSource() == menuitemedit) {
curNode = addNode(parentNode, "MsaDocum"); // can Docum be with Root Node? editNode();
} }
}
};
NodeList nodelist = node.getChildNodes(); private void editNode() {
for (int i = 0; i < nodelist.getLength(); i++) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) (tree
handleNode(nodelist.item(i), curNode); .getSelectionPath().getLastPathComponent());
} Element element = (Element) node.getUserObject();
} System.out.println(element.getTextContent());
}
private final void genDomTree(String filename) throws Exception { private void delNode() {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); treeModel.removeNodeFromParent((DefaultMutableTreeNode) (tree
Document document = builder.parse(filename); .getSelectionPath().getLastPathComponent()));
handleNode(document, rootNode); }
}
public static final void init() throws Exception { private void addNode() {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); addNode((DefaultMutableTreeNode) (tree.getSelectionPath()
.getLastPathComponent()), MigrationTool.ui
.getInput("Input Node Name"));
}
JFrame frame = new JFrame("MsaTreeEditor"); private DefaultMutableTreeNode addNode(DefaultMutableTreeNode parentNode,
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Object child) {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
treeModel.insertNodeInto(childNode, parentNode, parentNode
.getChildCount());
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
return childNode;
}
MsaTreeEditor mte = new MsaTreeEditor(); private final void handleNode(Node node, DefaultMutableTreeNode parentNode) {
mte.setLayout(new GridBagLayout()); DefaultMutableTreeNode curNode = null;
mte.setOpaque(true); if (node.getNodeType() == Node.ELEMENT_NODE) {
frame.setContentPane(mte); System.out.println("elem");
curNode = addNode(parentNode, node);
} else if (node.getNodeType() == Node.DOCUMENT_NODE) {
System.out.println("doc");
curNode = addNode(parentNode, "MsaDocum"); // can Docum be with
// Root Node?
}
frame.pack(); NodeList nodelist = node.getChildNodes();
frame.setVisible(true); for (int i = 0; i < nodelist.getLength(); i++) {
} handleNode(nodelist.item(i), curNode);
}
}
private final void genDomTree(String filename) throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.parse(filename);
handleNode(document, rootNode);
}
public static final void init() throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("MsaTreeEditor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MsaTreeEditor mte = new MsaTreeEditor();
mte.setLayout(new GridBagLayout());
mte.setOpaque(true);
frame.setContentPane(mte);
frame.pack();
frame.setVisible(true);
}
} }

View File

@ -12,214 +12,277 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.io.*; import java.io.BufferedReader;
import java.util.*; import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.tianocore.*; import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlOptions;
import org.tianocore.ExternsDocument;
import org.tianocore.FilenameDocument;
import org.tianocore.GuidsDocument;
import org.tianocore.LibraryClassDefinitionsDocument;
import org.tianocore.LibraryClassDocument;
import org.tianocore.ModuleDefinitionsDocument;
import org.tianocore.ModuleSurfaceAreaDocument;
import org.tianocore.ModuleTypeDef;
import org.tianocore.MsaHeaderDocument;
import org.tianocore.PPIsDocument;
import org.tianocore.PackageDependenciesDocument;
import org.tianocore.ProtocolsDocument;
import org.tianocore.SourceFilesDocument;
import org.tianocore.SupportedArchitectures;
import org.tianocore.UsageTypes;
import org.tianocore.SupportedArchitectures.Enum; import org.tianocore.SupportedArchitectures.Enum;
import org.apache.xmlbeans.*;
public class MsaWriter { public class MsaWriter {
MsaWriter(ModuleInfo moduleinfo) { MsaWriter(ModuleInfo moduleinfo) {
mi = moduleinfo; mi = moduleinfo;
} }
private ModuleInfo mi; private ModuleInfo mi;
private ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory.newInstance();
private ModuleSurfaceAreaDocument.ModuleSurfaceArea msa = msadoc.addNewModuleSurfaceArea(); private ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory
private MsaHeaderDocument.MsaHeader msaheader = msa.addNewMsaHeader(); .newInstance();
private ModuleDefinitionsDocument.ModuleDefinitions md = msa.addNewModuleDefinitions();
private SourceFilesDocument.SourceFiles sourcefiles = msa.addNewSourceFiles(); //found local .h files are not written
private GuidsDocument.Guids guids;
private ProtocolsDocument.Protocols protocols;
private PPIsDocument.PPIs ppis;
private PackageDependenciesDocument.PackageDependencies pd = msa.addNewPackageDependencies();
private LibraryClassDefinitionsDocument.LibraryClassDefinitions libclassdefs = msa.addNewLibraryClassDefinitions();
private ExternsDocument.Externs externs = msa.addNewExterns();
private String Query (String requirement) throws Exception { private ModuleSurfaceAreaDocument.ModuleSurfaceArea msa = msadoc
String answer; .addNewModuleSurfaceArea();
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
System.out.println(requirement);
while ((answer = rd.readLine()).length() == 0) ;
return answer;
}
private void addSourceFiles (String name) { // furthur modification needed private MsaHeaderDocument.MsaHeader msaheader = msa.addNewMsaHeader();
List<Enum> arch = new ArrayList<Enum>();
FilenameDocument.Filename filename;
filename = sourcefiles.addNewFilename();
filename.setStringValue(name);
if (name.contains("x64" + File.separator)) { // filename ??? private ModuleDefinitionsDocument.ModuleDefinitions md = msa
arch.add(SupportedArchitectures.X_64); .addNewModuleDefinitions();
System.out.println("x64" + File.separator);
filename.setSupArchList(arch);
} else if (name.contains("Ia32" + File.separator)) { // filename ???
arch.add(SupportedArchitectures.IA_32);
System.out.println("Ia32" + File.separator);
filename.setSupArchList(arch);
} else if (name.contains("Ipf" + File.separator)) { // filename ???
arch.add(SupportedArchitectures.IPF);
System.out.println("Ipf" + File.separator);
filename.setSupArchList(arch);
} else if (name.contains("Ebc" + File.separator)) { // filename ???
arch.add(SupportedArchitectures.EBC);
System.out.println("Ebc" + File.separator);
filename.setSupArchList(arch);
}
}
private void addWrapper() {
XmlCursor cursor = msa.newCursor();
String uri = "http://www.TianoCore.org/2006/Edk2.0";
cursor.push();
cursor.toNextToken();
cursor.insertNamespace("", uri);
cursor.insertNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
cursor.pop();
msa = (ModuleSurfaceAreaDocument.ModuleSurfaceArea)cursor.getObject();
}
private ModuleSurfaceAreaDocument fulfillMsadoc() throws Exception {
Iterator<String> it;
String temp;
if (mi.modulename != null) { private SourceFilesDocument.SourceFiles sourcefiles = msa
msaheader.setModuleName(mi.modulename); .addNewSourceFiles(); // found local .h files are not written
} else {
msaheader.setModuleName(mi.modulename = Query("Module Name Not Found! Please Input ModuleName"));
}
if (mi.guidvalue == null) {
mi.guidvalue = UUID.randomUUID().toString();
MigrationTool.ui.println ("Guid value can not be retrieved from inf file. Generate " + mi.guidvalue + " at random!");
}
msaheader.setGuidValue(mi.guidvalue);
if (mi.moduletype != null) {
msaheader.setModuleType(ModuleTypeDef.Enum.forString(mi.getModuleType()));
} else {
msaheader.setModuleType(ModuleTypeDef.Enum.forString(mi.moduletype = Query("Guid Value Not Found! Please Input Guid Value")));
}
msaheader.setCopyright("Copyright (c) 2006, Intel Corporation. All right reserved."); private GuidsDocument.Guids guids;
msaheader.setVersion("1.0");
msaheader.setAbstract("Component name for module " + mi.modulename);
msaheader.setDescription("FIX ME!");
if (mi.license == null) { private ProtocolsDocument.Protocols protocols;
mi.license = "FIX ME!";
MigrationTool.ui.println ("Fail to extract license info in inf file");
}
msaheader.addNewLicense().setStringValue(mi.license);
msaheader.setSpecification("FRAMEWORK_BUILD_PACKAGING_SPECIFICATION 0x00000052");
List<Enum> arch = new ArrayList<Enum>(); private PPIsDocument.PPIs ppis;
arch.add(SupportedArchitectures.IA_32);
arch.add(SupportedArchitectures.X_64);
arch.add(SupportedArchitectures.IPF);
arch.add(SupportedArchitectures.EBC);
md.setSupportedArchitectures(arch);
md.setBinaryModule(false);
md.setOutputFileBasename(mi.modulename);
//
// For now, simply add all package guids in the database.
//
it = MigrationTool.db.dumpAllPkgGuid();
while (it.hasNext()) {
pd.addNewPackage().setPackageGuid(it.next());
}
externs.addNewSpecification().setStringValue("EFI_SPECIFICATION_VERSION 0x00020000");
externs.addNewSpecification().setStringValue("EDK_RELEASE_VERSION 0x00020000");
if (mi.entrypoint != null) {
externs.addNewExtern().setModuleEntryPoint(mi.entrypoint);
org.tianocore.ModuleTypeDef.Enum moduleType = msaheader.getModuleType();
if (moduleType == ModuleTypeDef.PEIM) {
mi.hashrequiredr9libs.add("PeimEntryPoint");
} else {
mi.hashrequiredr9libs.add("UefiDriverEntryPoint");
}
}
it = mi.localmodulesources.iterator(); private PackageDependenciesDocument.PackageDependencies pd = msa
while (it.hasNext()) { .addNewPackageDependencies();
addSourceFiles(it.next());
}
if (!mi.protocols.isEmpty()) {
protocols = msa.addNewProtocols();
it = mi.protocols.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null) {
ProtocolsDocument.Protocols.Protocol pr = protocols.addNewProtocol();
pr.setProtocolCName(temp);
pr.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
}
if (!mi.ppis.isEmpty()) {
ppis = msa.addNewPPIs();
it = mi.ppis.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null) {
PPIsDocument.PPIs.Ppi pp = ppis.addNewPpi();
pp.setPpiCName(temp);
pp.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
}
if (!mi.guids.isEmpty()) {
guids = msa.addNewGuids();
it = mi.guids.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null) {
GuidsDocument.Guids.GuidCNames gcn = guids.addNewGuidCNames();
gcn.setGuidCName(temp);
gcn.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
}
it = mi.hashrequiredr9libs.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null && !temp.matches("%") && !temp.matches("n/a")) {
LibraryClassDocument.LibraryClass lc = libclassdefs.addNewLibraryClass();
lc.setKeyword(temp);
lc.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
addWrapper();
msadoc.setModuleSurfaceArea(msa);
return msadoc;
}
public void flush() throws Exception { private LibraryClassDefinitionsDocument.LibraryClassDefinitions libclassdefs = msa
XmlOptions options = new XmlOptions(); .addNewLibraryClassDefinitions();
options.setCharacterEncoding("UTF-8"); private ExternsDocument.Externs externs = msa.addNewExterns();
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(2);
options.setUseDefaultNamespace();
BufferedWriter bw = new BufferedWriter(new FileWriter(MigrationTool.ModuleInfoMap.get(mi) + File.separator + "Migration_" + mi.modulename + File.separator + mi.modulename + ".msa")); private String Query(String requirement) throws Exception {
fulfillMsadoc().save(bw, options); String answer;
//MsaTreeEditor.init(mi, ui, msadoc); BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
bw.flush(); System.out.println(requirement);
bw.close(); while ((answer = rd.readLine()).length() == 0)
} ;
return answer;
}
private static void flush(String path, ModuleSurfaceAreaDocument msadoc) throws Exception { private void addSourceFiles(String name) { // furthur modification needed
XmlOptions options = new XmlOptions(); List<Enum> arch = new ArrayList<Enum>();
FilenameDocument.Filename filename;
filename = sourcefiles.addNewFilename();
filename.setStringValue(name);
options.setCharacterEncoding("UTF-8"); if (name.contains("x64" + File.separator)) { // filename ???
options.setSavePrettyPrint(); arch.add(SupportedArchitectures.X_64);
options.setSavePrettyPrintIndent(2); System.out.println("x64" + File.separator);
options.setUseDefaultNamespace(); filename.setSupArchList(arch);
} else if (name.contains("Ia32" + File.separator)) { // filename ???
arch.add(SupportedArchitectures.IA_32);
System.out.println("Ia32" + File.separator);
filename.setSupArchList(arch);
} else if (name.contains("Ipf" + File.separator)) { // filename ???
arch.add(SupportedArchitectures.IPF);
System.out.println("Ipf" + File.separator);
filename.setSupArchList(arch);
} else if (name.contains("Ebc" + File.separator)) { // filename ???
arch.add(SupportedArchitectures.EBC);
System.out.println("Ebc" + File.separator);
filename.setSupArchList(arch);
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter(path)); private void addWrapper() {
msadoc.save(bw, options); XmlCursor cursor = msa.newCursor();
bw.flush(); String uri = "http://www.TianoCore.org/2006/Edk2.0";
bw.close(); cursor.push();
} cursor.toNextToken();
cursor.insertNamespace("", uri);
cursor.insertNamespace("xsi",
"http://www.w3.org/2001/XMLSchema-instance");
cursor.pop();
msa = (ModuleSurfaceAreaDocument.ModuleSurfaceArea) cursor.getObject();
}
public static final void parse(String msafile) throws Exception { private ModuleSurfaceAreaDocument fulfillMsadoc() throws Exception {
ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory.parse(msafile); Iterator<String> it;
flush("c:\\temp.msa", msadoc); String temp;
}
if (mi.modulename != null) {
msaheader.setModuleName(mi.modulename);
} else {
msaheader
.setModuleName(mi.modulename = Query("Module Name Not Found! Please Input ModuleName"));
}
if (mi.guidvalue == null) {
mi.guidvalue = UUID.randomUUID().toString();
MigrationTool.ui
.println("Guid value can not be retrieved from inf file. Generate "
+ mi.guidvalue + " at random!");
}
msaheader.setGuidValue(mi.guidvalue);
if (mi.moduletype != null) {
msaheader.setModuleType(ModuleTypeDef.Enum.forString(mi
.getModuleType()));
} else {
msaheader
.setModuleType(ModuleTypeDef.Enum
.forString(mi.moduletype = Query("Guid Value Not Found! Please Input Guid Value")));
}
msaheader
.setCopyright("Copyright (c) 2006, Intel Corporation. All right reserved.");
msaheader.setVersion("1.0");
msaheader.setAbstract("Component name for module " + mi.modulename);
msaheader.setDescription("FIX ME!");
if (mi.license == null) {
mi.license = "FIX ME!";
MigrationTool.ui
.println("Fail to extract license info in inf file");
}
msaheader.addNewLicense().setStringValue(mi.license);
msaheader
.setSpecification("FRAMEWORK_BUILD_PACKAGING_SPECIFICATION 0x00000052");
List<Enum> arch = new ArrayList<Enum>();
arch.add(SupportedArchitectures.IA_32);
arch.add(SupportedArchitectures.X_64);
arch.add(SupportedArchitectures.IPF);
arch.add(SupportedArchitectures.EBC);
md.setSupportedArchitectures(arch);
md.setBinaryModule(false);
md.setOutputFileBasename(mi.modulename);
//
// For now, simply add all package guids in the database.
//
it = MigrationTool.db.dumpAllPkgGuid();
while (it.hasNext()) {
pd.addNewPackage().setPackageGuid(it.next());
}
externs.addNewSpecification().setStringValue(
"EFI_SPECIFICATION_VERSION 0x00020000");
externs.addNewSpecification().setStringValue(
"EDK_RELEASE_VERSION 0x00020000");
if (mi.entrypoint != null) {
externs.addNewExtern().setModuleEntryPoint(mi.entrypoint);
org.tianocore.ModuleTypeDef.Enum moduleType = msaheader
.getModuleType();
if (moduleType == ModuleTypeDef.PEIM) {
mi.hashrequiredr9libs.add("PeimEntryPoint");
} else {
mi.hashrequiredr9libs.add("UefiDriverEntryPoint");
}
}
it = mi.localmodulesources.iterator();
while (it.hasNext()) {
addSourceFiles(it.next());
}
if (!mi.protocols.isEmpty()) {
protocols = msa.addNewProtocols();
it = mi.protocols.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null) {
ProtocolsDocument.Protocols.Protocol pr = protocols
.addNewProtocol();
pr.setProtocolCName(temp);
pr.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
}
if (!mi.ppis.isEmpty()) {
ppis = msa.addNewPPIs();
it = mi.ppis.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null) {
PPIsDocument.PPIs.Ppi pp = ppis.addNewPpi();
pp.setPpiCName(temp);
pp.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
}
if (!mi.guids.isEmpty()) {
guids = msa.addNewGuids();
it = mi.guids.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null) {
GuidsDocument.Guids.GuidCNames gcn = guids
.addNewGuidCNames();
gcn.setGuidCName(temp);
gcn.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
}
it = mi.hashrequiredr9libs.iterator();
while (it.hasNext()) {
if ((temp = it.next()) != null && !temp.matches("%")
&& !temp.matches("n/a")) {
LibraryClassDocument.LibraryClass lc = libclassdefs
.addNewLibraryClass();
lc.setKeyword(temp);
lc.setUsage(UsageTypes.ALWAYS_CONSUMED);
}
}
addWrapper();
msadoc.setModuleSurfaceArea(msa);
return msadoc;
}
public void flush() throws Exception {
XmlOptions options = new XmlOptions();
options.setCharacterEncoding("UTF-8");
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(2);
options.setUseDefaultNamespace();
BufferedWriter bw = new BufferedWriter(new FileWriter(
MigrationTool.ModuleInfoMap.get(mi) + File.separator
+ "Migration_" + mi.modulename + File.separator
+ mi.modulename + ".msa"));
fulfillMsadoc().save(bw, options);
// MsaTreeEditor.init(mi, ui, msadoc);
bw.flush();
bw.close();
}
private static void flush(String path, ModuleSurfaceAreaDocument msadoc)
throws Exception {
XmlOptions options = new XmlOptions();
options.setCharacterEncoding("UTF-8");
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(2);
options.setUseDefaultNamespace();
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
msadoc.save(bw, options);
bw.flush();
bw.close();
}
public static final void parse(String msafile) throws Exception {
ModuleSurfaceAreaDocument msadoc = ModuleSurfaceAreaDocument.Factory
.parse(msafile);
flush("c:\\temp.msa", msadoc);
}
} }

View File

@ -13,38 +13,44 @@
package org.tianocore.migration; package org.tianocore.migration;
import java.io.File; import java.io.File;
import java.util.*; import java.util.HashSet;
import java.util.Iterator;
public final class PathIterator implements Common.ForDoAll { public final class PathIterator implements Common.ForDoAll {
// this PathIterator is based on HashSet, an thread implementation is required. // this PathIterator is based on HashSet, an thread implementation is
PathIterator(String path, int md) throws Exception { // required.
startpath = path; PathIterator(String path, int md) throws Exception {
mode = md; startpath = path;
Common.toDoAll(startpath, this, mode); mode = md;
it = pathlist.iterator(); Common.toDoAll(startpath, this, mode);
} it = pathlist.iterator();
private String startpath = null; }
private int mode;
private HashSet<String> pathlist = new HashSet<String>();
private Iterator<String> it = null;
public final void run(String path) throws Exception { private String startpath = null;
pathlist.add(path);
}
public boolean filter(File dir) { private int mode;
return true;
}
public final String next() { private HashSet<String> pathlist = new HashSet<String>();
return it.next();
}
public final boolean hasNext() { private Iterator<String> it = null;
return it.hasNext();
}
public final String toString() { public final void run(String path) throws Exception {
return pathlist.toString(); pathlist.add(path);
} }
public boolean filter(File dir) {
return true;
}
public final String next() {
return it.next();
}
public final boolean hasNext() {
return it.hasNext();
}
public final String toString() {
return pathlist.toString();
}
} }

View File

@ -12,437 +12,493 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.io.*; import java.io.BufferedWriter;
import java.util.*; import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.tianocore.UsageTypes; import org.tianocore.UsageTypes;
public final class SourceFileReplacer implements Common.ForDoAll { public final class SourceFileReplacer implements Common.ForDoAll {
private static final SourceFileReplacer SFReplacer = new SourceFileReplacer(); private static final SourceFileReplacer SFReplacer = new SourceFileReplacer();
private ModuleInfo mi;
private static final Set<Common.Laplace> Laplaces = new HashSet<Common.Laplace>();
// these sets are used only for printing log of the changes in current file private ModuleInfo mi;
private static final Set<r8tor9> filefunc = new HashSet<r8tor9>();
private static final Set<r8tor9> filemacro = new HashSet<r8tor9>();
private static final Set<r8tor9> fileguid = new HashSet<r8tor9>();
private static final Set<r8tor9> fileppi = new HashSet<r8tor9>();
private static final Set<r8tor9> fileprotocol = new HashSet<r8tor9>();
private static final Set<String> filer8only = new HashSet<String>();
private static final String[] specialhoblibfunc = { private static final Set<Common.Laplace> Laplaces = new HashSet<Common.Laplace>();
"BuildModuleHob",
"BuildResourceDescriptorHob",
"BuildFvHob",
"BuildCpuHob",
"BuildGuidDataHob",
"BuildStackHob",
"BuildBspStoreHob",
"BuildMemoryAllocationHob"
};
private static final String[] peiserviceslibfunc = {
"InstallPpi",
"ReInstallPpi",
"LocatePpi",
"NotifyPpi",
"GetBootMode",
"SetBootMode",
"GetHobList",
"CreateHob",
"FfsFindNextVolume",
"FfsFindNextFile",
"FfsFindSectionData",
"InstallPeiMemory",
"AllocatePages",
"AllocatePool",
"PeiResetSystem"
};
//---------------------------------------inner classes---------------------------------------//
private static class r8tor9 {
r8tor9(String r8, String r9) {
r8thing = r8;
r9thing = r9;
}
public String r8thing;
public String r9thing;
}
private class IdleLaplace extends Common.Laplace { // these sets are used only for printing log of the changes in current file
public String operation(String wholeline) { private static final Set<r8tor9> filefunc = new HashSet<r8tor9>();
return replaceLibrary (wholeline, mi.hashmacro);
}
public boolean recognize(String filename) { private static final Set<r8tor9> filemacro = new HashSet<r8tor9>();
return filename.contains(".h") || filename.contains(".H") || filename.contains(".uni") ||
filename.contains(".s") || filename.contains(".S") || filename.contains(".asm") ||
(!filename.contains(".inf") && filename.contains(".i"));
}
public String namechange(String oldname) { private static final Set<r8tor9> fileguid = new HashSet<r8tor9>();
if (oldname.contains(".H")) {
return oldname.replaceFirst(".H", ".h");
} else {
return oldname;
}
}
}
private class DxsLaplace extends Common.Laplace {
public String operation(String wholeline) {
wholeline = replaceMacro(wholeline, mi.hashnonlocalmacro);
if (mi.getModuleType().equals("PEIM")) {
return addincludefile(wholeline, "\\<PeimDepex.h\\>");
} else {
return addincludefile(wholeline, "\\<DxeDepex.h\\>");
}
}
public boolean recognize(String filename) { private static final Set<r8tor9> fileppi = new HashSet<r8tor9>();
return filename.contains(".dxs");
}
public String namechange(String oldname) { private static final Set<r8tor9> fileprotocol = new HashSet<r8tor9>();
return oldname;
}
}
private class CLaplace extends Common.Laplace { private static final Set<String> filer8only = new HashSet<String>();
public String operation(String wholeline) {
// remove EFI_DRIVER_ENTRY_POINT
wholeline = wholeline.replaceAll("(EFI_[A-Z]+_ENTRY_POINT\\s*\\(\\s*\\w(\\w|\\d)*\\s*\\))", MigrationTool.MIGRATIONCOMMENT + " $1");
// redefine module entry point for some self-relocated modules
wholeline = wholeline.replaceAll (mi.entrypoint + "([^{]*?})", "_ModuleEntryPoint" + "$1");
// remove R8 library contractor
wholeline = wholeline.replaceAll ("(\\b(?:Efi|Dxe)InitializeDriverLib\\b)", MigrationTool.MIGRATIONCOMMENT + " $1");
// Add Library Class for potential reference of gBS, gRT & gDS.
if (Common.find (wholeline, "\\bg?BS\\b")) {
mi.hashrequiredr9libs.add("UefiBootServicesTableLib");
}
if (Common.find (wholeline, "\\bg?RT\\b")) {
mi.hashrequiredr9libs.add ("UefiRuntimeServicesTableLib");
}
if (Common.find (wholeline, "\\bgDS\\b")) {
mi.hashrequiredr9libs.add ("DxeServicesTableLib");
}
wholeline = replaceLibrary (wholeline, mi.hashnonlocalfunc); private static final String[] specialhoblibfunc = { "BuildModuleHob",
wholeline = replaceLibrary (wholeline, mi.hashmacro); "BuildResourceDescriptorHob", "BuildFvHob", "BuildCpuHob",
// Converting macro "BuildGuidDataHob", "BuildStackHob", "BuildBspStoreHob",
wholeline = replaceMacro (wholeline, mi.hashnonlocalmacro); "BuildMemoryAllocationHob" };
// Converting guid private static final String[] peiserviceslibfunc = { "InstallPpi",
replaceGuid(wholeline, mi.guids, "guid", fileguid); "ReInstallPpi", "LocatePpi", "NotifyPpi", "GetBootMode",
replaceGuid(wholeline, mi.ppis, "ppi", fileppi); "SetBootMode", "GetHobList", "CreateHob", "FfsFindNextVolume",
replaceGuid(wholeline, mi.protocols, "protocol", fileprotocol); "FfsFindNextFile", "FfsFindSectionData", "InstallPeiMemory",
"AllocatePages", "AllocatePool", "PeiResetSystem" };
// Converting Pei // ---------------------------------------inner
if (mi.getModuleType().matches("PEIM")) { // classes---------------------------------------//
// private static class r8tor9 {
// Try to remove PeiServicesTablePointer; r8tor9(String r8, String r9) {
// r8thing = r8;
wholeline = dropPeiServicesPointer (wholeline); r9thing = r9;
// }
// Drop the possible return Status of Hob building function.
//
wholeline = drophobLibReturnStatus (wholeline);
}
//
// Expand obsolete R8 macro.
//
wholeline = replaceObsoleteMacro (wholeline);
show(filefunc, "function"); public String r8thing;
show(filemacro, "macro");
show(fileguid, "guid");
show(fileppi, "ppi");
show(fileprotocol, "protocol");
if (!filer8only.isEmpty()) {
MigrationTool.ui.println("Converting r8only : " + filer8only);
}
filefunc.clear(); public String r9thing;
filemacro.clear(); }
fileguid.clear();
fileppi.clear();
fileprotocol.clear();
filer8only.clear();
return wholeline; private class IdleLaplace extends Common.Laplace {
} public String operation(String wholeline) {
return replaceLibrary(wholeline, mi.hashmacro);
}
public boolean recognize(String filename) { public boolean recognize(String filename) {
return filename.contains(".c") || filename.contains(".C"); return filename.contains(".h") || filename.contains(".H")
} || filename.contains(".uni") || filename.contains(".s")
|| filename.contains(".S") || filename.contains(".asm")
|| (!filename.contains(".inf") && filename.contains(".i"));
}
public String namechange(String oldname) { public String namechange(String oldname) {
if (oldname.contains(".C")) { if (oldname.contains(".H")) {
return oldname.replaceFirst(".C", ".c"); return oldname.replaceFirst(".H", ".h");
} else { } else {
return oldname; return oldname;
} }
} }
} }
//---------------------------------------inner classes---------------------------------------//
//-------------------------------------process functions-------------------------------------// private class DxsLaplace extends Common.Laplace {
private static final String addincludefile(String wholeline, String hfile) { public String operation(String wholeline) {
return wholeline.replaceFirst("(\\*/\\s)", "$1\n#include " + hfile + "\n"); wholeline = replaceMacro(wholeline, mi.hashnonlocalmacro);
} if (mi.getModuleType().equals("PEIM")) {
return addincludefile(wholeline, "\\<PeimDepex.h\\>");
} else {
return addincludefile(wholeline, "\\<DxeDepex.h\\>");
}
}
private static final void show(Set<r8tor9> hash, String sh) { public boolean recognize(String filename) {
Iterator<r8tor9> it = hash.iterator(); return filename.contains(".dxs");
r8tor9 temp; }
if (!hash.isEmpty()) {
MigrationTool.ui.print("Converting " + sh + " : ");
while (it.hasNext()) {
temp = it.next();
MigrationTool.ui.print("[" + temp.r8thing + "->" + temp.r9thing + "] ");
}
MigrationTool.ui.println("");
}
}
private static final void replaceGuid(String line, Set<String> hash, String kind, Set<r8tor9> filehash) { public String namechange(String oldname) {
Iterator<String> it; return oldname;
String r8thing; }
String r9thing; }
it = hash.iterator();
while (it.hasNext()) {
r8thing = it.next();
if ((r9thing = MigrationTool.db.getR9Guidname(r8thing)) != null) {
if (!r8thing.equals(r9thing)) {
if (line.contains(r8thing)) {
line = line.replaceAll(r8thing, r9thing);
filehash.add(new r8tor9(r8thing, r9thing));
}
}
}
}
}
private final String dropPeiServicesPointer (String wholeline) { private class CLaplace extends Common.Laplace {
String peiServicesTablePointer; public String operation(String wholeline) {
String peiServicesTableCaller; // remove EFI_DRIVER_ENTRY_POINT
String regPeiServices; wholeline = wholeline.replaceAll(
Pattern ptnPei; "(EFI_[A-Z]+_ENTRY_POINT\\s*\\(\\s*\\w(\\w|\\d)*\\s*\\))",
Matcher mtrPei; MigrationTool.MIGRATIONCOMMENT + " $1");
// redefine module entry point for some self-relocated modules
wholeline = wholeline.replaceAll(mi.entrypoint + "([^{]*?})",
"_ModuleEntryPoint" + "$1");
// remove R8 library contractor
wholeline = wholeline.replaceAll(
"(\\b(?:Efi|Dxe)InitializeDriverLib\\b)",
MigrationTool.MIGRATIONCOMMENT + " $1");
// Add Library Class for potential reference of gBS, gRT & gDS.
if (Common.find(wholeline, "\\bg?BS\\b")) {
mi.hashrequiredr9libs.add("UefiBootServicesTableLib");
}
if (Common.find(wholeline, "\\bg?RT\\b")) {
mi.hashrequiredr9libs.add("UefiRuntimeServicesTableLib");
}
if (Common.find(wholeline, "\\bgDS\\b")) {
mi.hashrequiredr9libs.add("DxeServicesTableLib");
}
peiServicesTablePointer = "\\w(?:\\w|[0-9]|->)*"; wholeline = replaceLibrary(wholeline, mi.hashnonlocalfunc);
peiServicesTableCaller = "\\(\\*\\*?\\s*(" + peiServicesTablePointer + ")\\s*\\)[.-]>?\\s*"; wholeline = replaceLibrary(wholeline, mi.hashmacro);
for (int i = 0; i < peiserviceslibfunc.length; i++) { // Converting macro
regPeiServices = peiServicesTableCaller + peiserviceslibfunc[i] + "\\s*\\(\\s*\\1\\s*,(\\t| )*"; wholeline = replaceMacro(wholeline, mi.hashnonlocalmacro);
ptnPei = Pattern.compile (regPeiServices);
mtrPei = ptnPei.matcher (wholeline);
if (mtrPei.find()) {
wholeline = mtrPei.replaceAll("PeiServices" + peiserviceslibfunc[i] + " (");
mi.hashrequiredr9libs.add("PeiServicesLib");
}
}
regPeiServices = peiServicesTableCaller + "(CopyMem|SetMem)" + "\\s*\\((\\t| )*";
ptnPei = Pattern.compile (regPeiServices);
mtrPei = ptnPei.matcher (wholeline);
if (mtrPei.find()) {
wholeline = mtrPei.replaceAll("$2 (");
mi.hashrequiredr9libs.add("BaseMemoryLib");
}
ptnPei = Pattern.compile("#%+(\\s*\\(+\\s*)" + peiServicesTablePointer + "\\s*,\\s*", Pattern.MULTILINE); // Converting guid
mtrPei = ptnPei.matcher(wholeline); replaceGuid(wholeline, mi.guids, "guid", fileguid);
while (mtrPei.find()) { replaceGuid(wholeline, mi.ppis, "ppi", fileppi);
wholeline = mtrPei.replaceAll("$1"); replaceGuid(wholeline, mi.protocols, "protocol", fileprotocol);
}
return wholeline; // Converting Pei
} if (mi.getModuleType().matches("PEIM")) {
//
// Try to remove PeiServicesTablePointer;
//
wholeline = dropPeiServicesPointer(wholeline);
//
// Drop the possible return Status of Hob building function.
//
wholeline = drophobLibReturnStatus(wholeline);
}
//
// Expand obsolete R8 macro.
//
wholeline = replaceObsoleteMacro(wholeline);
private final String drophobLibReturnStatus (String wholeline) { // or use regex to find pattern "Status = ..." show(filefunc, "function");
Pattern ptnhobstatus; show(filemacro, "macro");
Matcher mtrhobstatus; show(fileguid, "guid");
String templine = wholeline; show(fileppi, "ppi");
for (int i = 0; i < specialhoblibfunc.length; i++) { show(fileprotocol, "protocol");
do { if (!filer8only.isEmpty()) {
ptnhobstatus = Pattern.compile("((?:\t| )*)(\\w(?:\\w|\\d)*)\\s*=\\s*" + specialhoblibfunc[i] + "(.*?;)", Pattern.DOTALL); MigrationTool.ui.println("Converting r8only : " + filer8only);
mtrhobstatus = ptnhobstatus.matcher(templine); }
if (!mtrhobstatus.find()) {
break;
}
String captureIndent = mtrhobstatus.group(1);
String captureStatus = mtrhobstatus.group(2);
String replaceString = captureIndent + specialhoblibfunc[i] + mtrhobstatus.group(3) + "\n";
replaceString += captureIndent + MigrationTool.MIGRATIONCOMMENT + "R9 Hob-building library functions will assert if build failure.\n";
replaceString += captureIndent + captureStatus + " = EFI_SUCCESS;";
templine = mtrhobstatus.replaceFirst(replaceString);
} while (true);
}
return templine;
}
private final String replaceMacro (String wholeline, Set<String> symbolSet) { filefunc.clear();
String r8thing; filemacro.clear();
String r9thing; fileguid.clear();
Iterator<String> it; fileppi.clear();
fileprotocol.clear();
filer8only.clear();
it = symbolSet.iterator(); return wholeline;
while (it.hasNext()) { //macros are all assumed MdePkg currently }
r8thing = it.next();
//mi.hashrequiredr9libs.add(MigrationTool.db.getR9Lib(r8thing));
if ((r9thing = MigrationTool.db.getR9Macro(r8thing)) != null) {
if (wholeline.contains(r8thing)) {
String findString = "(?<!(?:\\d|\\w))" + r8thing + "(?!(?:\\d|\\w))";
wholeline = wholeline.replaceAll(findString, r9thing);
filemacro.add(new r8tor9(r8thing, r9thing));
}
}
}
return wholeline;
}
private final String replaceLibrary (String wholeline, Set<String> symbolSet) { public boolean recognize(String filename) {
boolean addr8 = false; return filename.contains(".c") || filename.contains(".C");
// start replacing names }
String r8thing;
String r9thing;
Iterator<String> it;
// Converting non-locla function
it = symbolSet.iterator();
while (it.hasNext()) {
r8thing = it.next();
mi.addLibraryClass(MigrationTool.db.getR9Lib(r8thing), UsageTypes.ALWAYS_CONSUMED);
//mi.hashrequiredr9libs.add(MigrationTool.db.getR9Lib(r8thing)); // add a library here
r8tor9 temp; public String namechange(String oldname) {
if ((r9thing = MigrationTool.db.getR9Func(r8thing)) != null) { if (oldname.contains(".C")) {
if (!r8thing.equals(r9thing)) { return oldname.replaceFirst(".C", ".c");
if (wholeline.contains(r8thing)) { } else {
String findString = "(?<!(?:\\d|\\w))" + r8thing + "(?!(?:\\d|\\w))"; return oldname;
wholeline = wholeline.replaceAll(findString, r9thing); }
filefunc.add(new r8tor9(r8thing, r9thing)); }
Iterator<r8tor9> rt = filefunc.iterator(); }
while (rt.hasNext()) {
temp = rt.next();
if (MigrationTool.db.r8only.contains(temp.r8thing)) {
filer8only.add(r8thing);
mi.hashr8only.add(r8thing);
addr8 = true;
}
}
}
}
}
} //is any of the guids changed?
if (addr8 == true) {
wholeline = addincludefile(wholeline, "\"R8Lib.h\"");
}
return wholeline;
}
private final String replaceObsoleteMacro (String wholeline) { // ---------------------------------------inner
Matcher mtrmac; // classes---------------------------------------//
mtrmac = Pattern.compile("EFI_IDIV_ROUND\\((.*), (.*)\\)").matcher(wholeline);
if (mtrmac.find()) {
wholeline = mtrmac.replaceAll("\\($1 \\/ $2 \\+ \\(\\(\\(2 \\* \\($1 \\% $2\\)\\) \\< $2\\) \\? 0 \\: 1\\)\\)");
}
mtrmac = Pattern.compile("EFI_MIN\\((.*), (.*)\\)").matcher(wholeline);
if (mtrmac.find()) {
wholeline = mtrmac.replaceAll("\\(\\($1 \\< $2\\) \\? $1 \\: $2\\)");
}
mtrmac = Pattern.compile("EFI_MAX\\((.*), (.*)\\)").matcher(wholeline);
if (mtrmac.find()) {
wholeline = mtrmac.replaceAll("\\(\\($1 \\> $2\\) \\? $1 \\: $2\\)");
}
mtrmac = Pattern.compile("EFI_UINTN_ALIGNED\\((.*)\\)").matcher(wholeline);
if (mtrmac.find()) {
wholeline = mtrmac.replaceAll("\\(\\(\\(UINTN\\) $1\\) \\& \\(sizeof \\(UINTN\\) \\- 1\\)\\)");
}
if (wholeline.contains("EFI_UINTN_ALIGN_MASK")) {
wholeline = wholeline.replaceAll("EFI_UINTN_ALIGN_MASK", "(sizeof (UINTN) - 1)");
}
return wholeline;
}
private final void addr8only() throws Exception { // -------------------------------------process
String paragraph = null; // functions-------------------------------------//
String line = Common.file2string(MigrationTool.db.DatabasePath + File.separator + "R8Lib.c"); private static final String addincludefile(String wholeline, String hfile) {
PrintWriter outfile1 = new PrintWriter(new BufferedWriter(new FileWriter(MigrationTool.ModuleInfoMap.get(mi) + File.separator + "Migration_" + mi.modulename + File.separator + "R8Lib.c"))); return wholeline.replaceFirst("(\\*/\\s)", "$1\n#include " + hfile
PrintWriter outfile2 = new PrintWriter(new BufferedWriter(new FileWriter(MigrationTool.ModuleInfoMap.get(mi) + File.separator + "Migration_" + mi.modulename + File.separator + "R8Lib.h"))); + "\n");
Pattern ptnr8only = Pattern.compile("////#?(\\w*)?(.*?R8_(\\w*).*?)////~", Pattern.DOTALL); }
Matcher mtrr8only = ptnr8only.matcher(line);
Matcher mtrr8onlyhead;
//add head comment private static final void show(Set<r8tor9> hash, String sh) {
Matcher mtrr8onlyheadcomment = Critic.PTN_NEW_HEAD_COMMENT.matcher(line); Iterator<r8tor9> it = hash.iterator();
if (mtrr8onlyheadcomment.find()) { r8tor9 temp;
outfile1.append(mtrr8onlyheadcomment.group() + "\n\n"); if (!hash.isEmpty()) {
outfile2.append(mtrr8onlyheadcomment.group() + "\n\n"); MigrationTool.ui.print("Converting " + sh + " : ");
} while (it.hasNext()) {
temp = it.next();
MigrationTool.ui.print("[" + temp.r8thing + "->" + temp.r9thing
+ "] ");
}
MigrationTool.ui.println("");
}
}
//add functions body private static final void replaceGuid(String line, Set<String> hash,
while (mtrr8only.find()) { String kind, Set<r8tor9> filehash) {
if (mi.hashr8only.contains(mtrr8only.group(3))) { Iterator<String> it;
paragraph = mtrr8only.group(2); String r8thing;
outfile1.append(paragraph + "\n\n"); String r9thing;
if (mtrr8only.group(1).length() != 0) { it = hash.iterator();
mi.hashrequiredr9libs.add(mtrr8only.group(1)); while (it.hasNext()) {
} r8thing = it.next();
//generate R8lib.h if ((r9thing = MigrationTool.db.getR9Guidname(r8thing)) != null) {
while ((mtrr8onlyhead = Func.ptnbrace.matcher(paragraph)).find()) { if (!r8thing.equals(r9thing)) {
paragraph = mtrr8onlyhead.replaceAll(";"); if (line.contains(r8thing)) {
} line = line.replaceAll(r8thing, r9thing);
outfile2.append(paragraph + "\n\n"); filehash.add(new r8tor9(r8thing, r9thing));
} }
} }
outfile1.flush(); }
outfile1.close(); }
outfile2.flush(); }
outfile2.close();
mi.localmodulesources.add("R8Lib.h"); private final String dropPeiServicesPointer(String wholeline) {
mi.localmodulesources.add("R8Lib.c"); String peiServicesTablePointer;
} String peiServicesTableCaller;
//-------------------------------------process functions-------------------------------------// String regPeiServices;
Pattern ptnPei;
Matcher mtrPei;
//-----------------------------------ForDoAll-----------------------------------// peiServicesTablePointer = "\\w(?:\\w|[0-9]|->)*";
public void run(String filepath) throws Exception { peiServicesTableCaller = "\\(\\*\\*?\\s*(" + peiServicesTablePointer
String inname = filepath.replace(mi.temppath + File.separator, ""); + ")\\s*\\)[.-]>?\\s*";
String tempinpath = mi.temppath + File.separator; for (int i = 0; i < peiserviceslibfunc.length; i++) {
String tempoutpath = MigrationTool.ModuleInfoMap.get(mi) + File.separator + "Migration_" + mi.modulename + File.separator; regPeiServices = peiServicesTableCaller + peiserviceslibfunc[i]
+ "\\s*\\(\\s*\\1\\s*,(\\t| )*";
ptnPei = Pattern.compile(regPeiServices);
mtrPei = ptnPei.matcher(wholeline);
if (mtrPei.find()) {
wholeline = mtrPei.replaceAll("PeiServices"
+ peiserviceslibfunc[i] + " (");
mi.hashrequiredr9libs.add("PeiServicesLib");
}
}
regPeiServices = peiServicesTableCaller + "(CopyMem|SetMem)"
+ "\\s*\\((\\t| )*";
ptnPei = Pattern.compile(regPeiServices);
mtrPei = ptnPei.matcher(wholeline);
if (mtrPei.find()) {
wholeline = mtrPei.replaceAll("$2 (");
mi.hashrequiredr9libs.add("BaseMemoryLib");
}
Iterator<Common.Laplace> itLaplace = Laplaces.iterator(); ptnPei = Pattern.compile("#%+(\\s*\\(+\\s*)" + peiServicesTablePointer
while (itLaplace.hasNext()) { + "\\s*,\\s*", Pattern.MULTILINE);
Common.Laplace lap = itLaplace.next(); mtrPei = ptnPei.matcher(wholeline);
if (lap.recognize(inname)) { while (mtrPei.find()) {
MigrationTool.ui.println("\nHandling file: " + inname); wholeline = mtrPei.replaceAll("$1");
lap.transform(tempinpath + inname, tempoutpath + lap.namechange(inname)); }
}
}
}
public boolean filter(File dir) { return wholeline;
return true; }
}
//-----------------------------------ForDoAll-----------------------------------//
private final void setModuleInfo(ModuleInfo moduleinfo) { private final String drophobLibReturnStatus(String wholeline) { // or use
mi = moduleinfo; // regex to
} // find
// pattern
// "Status =
// ..."
Pattern ptnhobstatus;
Matcher mtrhobstatus;
String templine = wholeline;
for (int i = 0; i < specialhoblibfunc.length; i++) {
do {
ptnhobstatus = Pattern.compile(
"((?:\t| )*)(\\w(?:\\w|\\d)*)\\s*=\\s*"
+ specialhoblibfunc[i] + "(.*?;)",
Pattern.DOTALL);
mtrhobstatus = ptnhobstatus.matcher(templine);
if (!mtrhobstatus.find()) {
break;
}
String captureIndent = mtrhobstatus.group(1);
String captureStatus = mtrhobstatus.group(2);
String replaceString = captureIndent + specialhoblibfunc[i]
+ mtrhobstatus.group(3) + "\n";
replaceString += captureIndent
+ MigrationTool.MIGRATIONCOMMENT
+ "R9 Hob-building library functions will assert if build failure.\n";
replaceString += captureIndent + captureStatus
+ " = EFI_SUCCESS;";
templine = mtrhobstatus.replaceFirst(replaceString);
} while (true);
}
return templine;
}
private final void start() throws Exception { private final String replaceMacro(String wholeline, Set<String> symbolSet) {
Laplaces.add(new DxsLaplace()); String r8thing;
Laplaces.add(new CLaplace()); String r9thing;
Laplaces.add(new IdleLaplace()); Iterator<String> it;
Common.toDoAll(mi.temppath, this, Common.FILE); it = symbolSet.iterator();
while (it.hasNext()) { // macros are all assumed MdePkg currently
r8thing = it.next();
// mi.hashrequiredr9libs.add(MigrationTool.db.getR9Lib(r8thing));
if ((r9thing = MigrationTool.db.getR9Macro(r8thing)) != null) {
if (wholeline.contains(r8thing)) {
String findString = "(?<!(?:\\d|\\w))" + r8thing
+ "(?!(?:\\d|\\w))";
wholeline = wholeline.replaceAll(findString, r9thing);
filemacro.add(new r8tor9(r8thing, r9thing));
}
}
}
return wholeline;
}
if (!mi.hashr8only.isEmpty()) { private final String replaceLibrary(String wholeline, Set<String> symbolSet) {
addr8only(); boolean addr8 = false;
} // start replacing names
String r8thing;
String r9thing;
Iterator<String> it;
// Converting non-locla function
it = symbolSet.iterator();
while (it.hasNext()) {
r8thing = it.next();
mi.addLibraryClass(MigrationTool.db.getR9Lib(r8thing),
UsageTypes.ALWAYS_CONSUMED);
// mi.hashrequiredr9libs.add(MigrationTool.db.getR9Lib(r8thing)); //
// add a library here
Laplaces.clear(); r8tor9 temp;
} if ((r9thing = MigrationTool.db.getR9Func(r8thing)) != null) {
if (!r8thing.equals(r9thing)) {
if (wholeline.contains(r8thing)) {
String findString = "(?<!(?:\\d|\\w))" + r8thing
+ "(?!(?:\\d|\\w))";
wholeline = wholeline.replaceAll(findString, r9thing);
filefunc.add(new r8tor9(r8thing, r9thing));
Iterator<r8tor9> rt = filefunc.iterator();
while (rt.hasNext()) {
temp = rt.next();
if (MigrationTool.db.r8only.contains(temp.r8thing)) {
filer8only.add(r8thing);
mi.hashr8only.add(r8thing);
addr8 = true;
}
}
}
}
}
} // is any of the guids changed?
if (addr8 == true) {
wholeline = addincludefile(wholeline, "\"R8Lib.h\"");
}
return wholeline;
}
public static final void fireAt(ModuleInfo moduleinfo) throws Exception { private final String replaceObsoleteMacro(String wholeline) {
SFReplacer.setModuleInfo(moduleinfo); Matcher mtrmac;
SFReplacer.start(); mtrmac = Pattern.compile("EFI_IDIV_ROUND\\((.*), (.*)\\)").matcher(
} wholeline);
if (mtrmac.find()) {
wholeline = mtrmac
.replaceAll("\\($1 \\/ $2 \\+ \\(\\(\\(2 \\* \\($1 \\% $2\\)\\) \\< $2\\) \\? 0 \\: 1\\)\\)");
}
mtrmac = Pattern.compile("EFI_MIN\\((.*), (.*)\\)").matcher(wholeline);
if (mtrmac.find()) {
wholeline = mtrmac
.replaceAll("\\(\\($1 \\< $2\\) \\? $1 \\: $2\\)");
}
mtrmac = Pattern.compile("EFI_MAX\\((.*), (.*)\\)").matcher(wholeline);
if (mtrmac.find()) {
wholeline = mtrmac
.replaceAll("\\(\\($1 \\> $2\\) \\? $1 \\: $2\\)");
}
mtrmac = Pattern.compile("EFI_UINTN_ALIGNED\\((.*)\\)").matcher(
wholeline);
if (mtrmac.find()) {
wholeline = mtrmac
.replaceAll("\\(\\(\\(UINTN\\) $1\\) \\& \\(sizeof \\(UINTN\\) \\- 1\\)\\)");
}
if (wholeline.contains("EFI_UINTN_ALIGN_MASK")) {
wholeline = wholeline.replaceAll("EFI_UINTN_ALIGN_MASK",
"(sizeof (UINTN) - 1)");
}
return wholeline;
}
private final void addr8only() throws Exception {
String paragraph = null;
String line = Common.file2string(MigrationTool.db.DatabasePath
+ File.separator + "R8Lib.c");
PrintWriter outfile1 = new PrintWriter(new BufferedWriter(
new FileWriter(MigrationTool.ModuleInfoMap.get(mi)
+ File.separator + "Migration_" + mi.modulename
+ File.separator + "R8Lib.c")));
PrintWriter outfile2 = new PrintWriter(new BufferedWriter(
new FileWriter(MigrationTool.ModuleInfoMap.get(mi)
+ File.separator + "Migration_" + mi.modulename
+ File.separator + "R8Lib.h")));
Pattern ptnr8only = Pattern.compile(
"////#?(\\w*)?(.*?R8_(\\w*).*?)////~", Pattern.DOTALL);
Matcher mtrr8only = ptnr8only.matcher(line);
Matcher mtrr8onlyhead;
// add head comment
Matcher mtrr8onlyheadcomment = Critic.PTN_NEW_HEAD_COMMENT
.matcher(line);
if (mtrr8onlyheadcomment.find()) {
outfile1.append(mtrr8onlyheadcomment.group() + "\n\n");
outfile2.append(mtrr8onlyheadcomment.group() + "\n\n");
}
// add functions body
while (mtrr8only.find()) {
if (mi.hashr8only.contains(mtrr8only.group(3))) {
paragraph = mtrr8only.group(2);
outfile1.append(paragraph + "\n\n");
if (mtrr8only.group(1).length() != 0) {
mi.hashrequiredr9libs.add(mtrr8only.group(1));
}
// generate R8lib.h
while ((mtrr8onlyhead = Func.ptnbrace.matcher(paragraph))
.find()) {
paragraph = mtrr8onlyhead.replaceAll(";");
}
outfile2.append(paragraph + "\n\n");
}
}
outfile1.flush();
outfile1.close();
outfile2.flush();
outfile2.close();
mi.localmodulesources.add("R8Lib.h");
mi.localmodulesources.add("R8Lib.c");
}
// -------------------------------------process
// functions-------------------------------------//
// -----------------------------------ForDoAll-----------------------------------//
public void run(String filepath) throws Exception {
String inname = filepath.replace(mi.temppath + File.separator, "");
String tempinpath = mi.temppath + File.separator;
String tempoutpath = MigrationTool.ModuleInfoMap.get(mi)
+ File.separator + "Migration_" + mi.modulename
+ File.separator;
Iterator<Common.Laplace> itLaplace = Laplaces.iterator();
while (itLaplace.hasNext()) {
Common.Laplace lap = itLaplace.next();
if (lap.recognize(inname)) {
MigrationTool.ui.println("\nHandling file: " + inname);
lap.transform(tempinpath + inname, tempoutpath
+ lap.namechange(inname));
}
}
}
public boolean filter(File dir) {
return true;
}
// -----------------------------------ForDoAll-----------------------------------//
private final void setModuleInfo(ModuleInfo moduleinfo) {
mi = moduleinfo;
}
private final void start() throws Exception {
Laplaces.add(new DxsLaplace());
Laplaces.add(new CLaplace());
Laplaces.add(new IdleLaplace());
Common.toDoAll(mi.temppath, this, Common.FILE);
if (!mi.hashr8only.isEmpty()) {
addr8only();
}
Laplaces.clear();
}
public static final void fireAt(ModuleInfo moduleinfo) throws Exception {
SFReplacer.setModuleInfo(moduleinfo);
SFReplacer.start();
}
} }

View File

@ -12,21 +12,21 @@
**/ **/
package org.tianocore.migration; package org.tianocore.migration;
import java.util.*; import java.util.Set;
public interface UI { public interface UI {
public boolean yesOrNo(String question); public boolean yesOrNo(String question);
public void print(String message); public void print(String message);
public void println(String message); public void println(String message);
public void println(Set<String> hash); public void println(Set<String> hash);
public String choose(String message, Object[] choicelist); public String choose(String message, Object[] choicelist);
public String getInput(String message); public String getInput(String message);
public String getFilepath(String title, int mode); // necessary ? public String getFilepath(String title, int mode); // necessary ?
} }