View Javadoc

1   /*
2    * Copyright 2007-2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.gwe.p2elv2.macro;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import org.gwe.p2elv2.model.PStatement;
23  import org.gwe.p2elv2.model.PVariable;
24  import org.gwe.utils.rex.REXException;
25  import org.gwe.utils.rex.REXParser;
26  
27  /**
28   * @author Marco Ruiz
29   * @since Feb 23, 2009
30   */
31  public class PMacroRepo extends ArrayList<PMacroLibrary> {
32  	
33  	public String applyMacros(String stmtStr) throws REXException {
34  		PStatement stmt = REXParser.createModel(PStatement.class, stmtStr);
35  		List<PVariable> stmtMacroVars = new ArrayList<PVariable>(); 
36  		List<PVariable> macroExpandedVars = new ArrayList<PVariable>(); 
37  		
38  		for (PVariable var : stmt.getVars()) {
39          	List<PVariable> macroVars = expandMacro(var);
40  	        if (macroVars != null) {
41  	        	stmtMacroVars.add(var);
42  				macroExpandedVars.addAll(macroVars);
43  	        }
44          }
45  		stmt.getVars().removeAll(stmtMacroVars);
46  		stmt.getVars().addAll(macroExpandedVars);
47  		String result = stmt.toString();
48  		return (stmtMacroVars.isEmpty()) ? result : applyMacros(result);
49  	}
50  
51  	private List<PVariable> expandMacro(PVariable var) throws REXException {
52  		PMacro macroObj = null;
53  		for (PMacroLibrary macroLib : this) {
54  	        macroObj = macroLib.getInvocationMacro(var);
55  	        if (macroObj != null) break;
56          }
57  
58          if (macroObj == null) return null;
59  	    String evalContent = macroObj.evaluateContent(var.getFullName(), var.getFunctionInvocation().getParams());
60  	    return REXParser.createModel(PStatement.class, evalContent).getVars();
61      }
62  }