ExpressRunner.java 27.2 KB
Newer Older
T
update  
tianqiao 已提交
1 2
package com.ql.util.express;

3
import java.util.*;
T
tianqiao 已提交
4 5
import java.util.regex.Matcher;
import java.util.regex.Pattern;
T
update  
tianqiao 已提交
6

T
tianqiao 已提交
7
import com.ql.util.express.instruction.op.*;
T
update  
tianqiao 已提交
8
import com.ql.util.express.parse.*;
T
tianqiao 已提交
9 10 11 12
import com.ql.util.express.rule.Condition;
import com.ql.util.express.rule.Rule;
import com.ql.util.express.rule.RuleManager;
import com.ql.util.express.rule.RuleResult;
T
update  
tianqiao 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ql.util.express.instruction.ForRelBreakContinue;
import com.ql.util.express.instruction.IOperateDataCache;
import com.ql.util.express.instruction.InstructionFactory;
import com.ql.util.express.instruction.OperateDataCacheImpl;

/**
 * 语法分析和计算的入口类
 * @author xuannan
 *
 */
public class ExpressRunner {

	private static final Log log = LogFactory.getLog(ExpressRunner.class);
	private static final String GLOBAL_DEFINE_NAME="全局定义";
	/**
	 * 是否输出所有的跟踪信息,同时还需要log级别是DEBUG级别
	 */
	private boolean isTrace = false;
T
tianqiao 已提交
34

T
update  
tianqiao 已提交
35 36 37 38
	/**
	 * 是否使用逻辑短路特性增强质量的效率
	 */
	private boolean isShortCircuit = true;
T
tianqiao 已提交
39

T
update  
tianqiao 已提交
40 41 42 43
	/**
	 * 是否需要高精度计算
	 */
	private boolean isPrecise = false;
T
tianqiao 已提交
44

T
update  
tianqiao 已提交
45 46 47 48
	/**
	 * 一段文本对应的指令集的缓存
	 */
    private Map<String,InstructionSet> expressInstructionSetCache = new HashMap<String, InstructionSet>();
T
tianqiao 已提交
49 50 51 52 53 54

	/**
	 * 一段文本对应的规则的缓存
	 */
	private Map<String,Rule> ruleCache = new HashMap<String, Rule>();

T
update  
tianqiao 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67
    private ExpressLoader loader;
    private IExpressResourceLoader expressResourceLoader;
    /**
     * 语法定义的管理器
     */
	private NodeTypeManager manager;
	/**
	 * 操作符的管理器
	 */
	private OperatorFactory operatorManager;
	/**
	 * 语法分析器
	 */
T
tianqiao 已提交
68 69
	private ExpressParse parse ;

T
update  
tianqiao 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	/**
	 * 缺省的Class查找的包管理器
	 */
	ExpressPackage rootExpressPackage = new ExpressPackage(null);

	public AppendingClassMethodManager getAppendingClassMethodManager() {
		return appendingClassMethodManager;
	}

	private AppendingClassMethodManager appendingClassMethodManager;

	public AppendingClassFieldManager getAppendingClassFieldManager() {
		return appendingClassFieldManager;
	}

	private AppendingClassFieldManager appendingClassFieldManager;
T
tianqiao 已提交
86

T
update  
tianqiao 已提交
87 88 89 90 91 92 93 94
	private ThreadLocal<IOperateDataCache> m_OperateDataObjectCache = new ThreadLocal<IOperateDataCache>(){
		protected IOperateDataCache initialValue() {
	        return new OperateDataCacheImpl(30);
	    }
	};
	public IOperateDataCache getOperateDataCache(){
		return this.m_OperateDataObjectCache.get();
	}
T
tianqiao 已提交
95

T
update  
tianqiao 已提交
96 97 98 99
	public ExpressRunner(){
		this(false,false);
	}
	/**
T
tianqiao 已提交
100
	 *
T
update  
tianqiao 已提交
101 102 103 104 105 106 107 108 109 110
	 * @param aIsPrecise 是否需要高精度计算支持
	 * @param aIstrace 是否跟踪执行指令的过程
	 */
	public ExpressRunner(boolean aIsPrecise,boolean aIstrace){
		this(aIsPrecise,aIstrace,new DefaultExpressResourceLoader(),null);
	}
	public ExpressRunner(boolean aIsPrecise,boolean aIstrace,NodeTypeManager aManager){
		this(aIsPrecise,aIstrace,new DefaultExpressResourceLoader(),aManager);
	}
	/**
T
tianqiao 已提交
111
	 *
T
update  
tianqiao 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
	 * @param aIsPrecise 是否需要高精度计算支持
	 * @param aIstrace 是否跟踪执行指令的过程
	 * @param aExpressResourceLoader 表达式的资源装载器
	 */
	public ExpressRunner(boolean aIsPrecise,boolean aIstrace,IExpressResourceLoader aExpressResourceLoader,NodeTypeManager aManager){
		this.isTrace = aIstrace;
		this.isPrecise = aIsPrecise;
		this.expressResourceLoader = aExpressResourceLoader;
		if(aManager == null){
			manager = new NodeTypeManager();
		}else{
			manager = aManager;
		}
		this.operatorManager = new OperatorFactory(this.isPrecise);
		this.loader = new ExpressLoader(this);
		this.parse =  new ExpressParse(manager,this.expressResourceLoader,this.isPrecise);
		rootExpressPackage.addPackage("java.lang");
		rootExpressPackage.addPackage("java.util");
		this.addSystemFunctions();
T
tianqiao 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144
        this.addSystemOperators();
	}
    
    private void addSystemOperators() {
	    try {
            this.addOperator("instanceof", new OperatorInstanceOf("instanceof"));
        }catch (Exception e){
	        throw new RuntimeException(e);
        }
    }
    
    public void addSystemFunctions(){
		  this.addFunction("max", new OperatorMinMax("max"));
		  this.addFunction("min", new OperatorMinMax("min"));
T
update  
tianqiao 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
		  this.addFunction("round", new OperatorRound("round"));
		  this.addFunction("print", new OperatorPrint("print"));
		  this.addFunction("println", new OperatorPrintln("println"));
	}

	/**
	 * 获取语法定义的管理器
	 * @return
	 */
	public NodeTypeManager getNodeTypeManager(){
		return this.manager;
	}
	/**
	 * 获取操作符号管理器
	 * @return
	 */
	public OperatorFactory getOperatorFactory(){
		return this.operatorManager;
	}
	public IExpressResourceLoader getExpressResourceLoader(){
		return this.expressResourceLoader;
	}
	/**
	 * 添加宏定义 例如: macro 玄难 { abc(userinfo.userId);}
	 * @param macroName:玄难
	 * @param express :abc(userinfo.userId);
T
tianqiao 已提交
171
	 * @throws Exception
T
update  
tianqiao 已提交
172
	 */
T
tianqiao 已提交
173
	public void addMacro(String macroName,String express) throws Exception{
T
update  
tianqiao 已提交
174 175 176
		String macroExpress = "macro " + macroName  +" {" + express + "}";
		this.loader.parseInstructionSet(GLOBAL_DEFINE_NAME,macroExpress);
	}
T
tianqiao 已提交
177

T
update  
tianqiao 已提交
178 179 180 181 182 183
	/**
	 * 装载表达式,但不执行,例如一些宏定义,或者自定义函数
	 * @param groupName
	 * @param express
	 * @throws Exception
	 */
T
tianqiao 已提交
184
	public void loadMutilExpress(String groupName,String express) throws Exception{
T
update  
tianqiao 已提交
185 186
		if(groupName == null || groupName.trim().length() ==0){
			groupName = GLOBAL_DEFINE_NAME;
T
tianqiao 已提交
187
		}
T
update  
tianqiao 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
		this.loader.parseInstructionSet(groupName,express);
	}
    /**
     * 装载文件中定义的Express
     * @param expressName
     * @throws Exception
     */
	public void loadExpress(String expressName) throws Exception {
		this.loader.loadExpress(expressName);
	}
	/**
	 * 添加函数定义
	 * @param name 函数名称
	 * @param op 对应的操作实现类
	 */
	public void addFunction(String name, OperatorBase op) {
		this.operatorManager.addOperator(name, op);
		this.manager.addFunctionName(name);
	};

	/**
	 * 添加函数定义扩展类的方法
	 * @param name
	 * @param bindingClass
     * @param op
     */
	public void addFunctionAndClassMethod(String name,Class<?>bindingClass, OperatorBase op) {
		this.addFunction(name,op);
		this.addClassMethod(name,bindingClass,op);

	};

	/**
	 * 添加类的方法
	 * @param field
	 * @param bindingClass
	 * @param op
	 */
	public void addClassField(String field,Class<?>bindingClass,Operator op)
	{
		this.addClassField(field,bindingClass,Object.class,op);
	}

	/**
	 * 添加类的方法
	 * @param field
	 * @param bindingClass
	 * @param returnType
	 * @param op
	 */
	public void addClassField(String field,Class<?>bindingClass,Class<?>returnType,Operator op)
	{
		if(this.appendingClassFieldManager==null){
			this.appendingClassFieldManager = new AppendingClassFieldManager();
		}
		this.appendingClassFieldManager.addAppendingField(field, bindingClass,returnType,op);
	}

	/**
	 * 添加类的方法
	 * @param name
	 * @param bindingClass
     * @param op
     */
	public void addClassMethod(String name,Class<?>bindingClass,OperatorBase op)
	{
		if(this.appendingClassMethodManager==null){
			this.appendingClassMethodManager = new AppendingClassMethodManager();
		}
		this.appendingClassMethodManager.addAppendingMethod(name, bindingClass, op);
	}
	/**
	 * 获取函数定义,通过函数定义可以拿到参数的说明信息
	 * @param name 函数名称
	 * @return
	 */
	public OperatorBase getFunciton(String name){
		return this.operatorManager.getOperator(name);
	}
    /**
     * 添加一个类的函数定义,例如:Math.abs(double) 映射为表达式中的 "取绝对值(-5.0)"
     * @param name 函数名称
     * @param aClassName 类名称
     * @param aFunctionName 类中的方法名称
     * @param aParameterClassTypes 方法的参数类型名称
     * @param errorInfo 如果函数执行的结果是false,需要输出的错误信息
     * @throws Exception
     */
	public void addFunctionOfClassMethod(String name, String aClassName,
			String aFunctionName, Class<?>[] aParameterClassTypes,
			String errorInfo) throws Exception {
		this.addFunction(name, new OperatorSelfDefineClassFunction(name,
				aClassName, aFunctionName, aParameterClassTypes,null,null, errorInfo));
T
tianqiao 已提交
281

T
update  
tianqiao 已提交
282
	}
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    
    /**
     * 添加一个类的函数定义,例如:Math.abs(double) 映射为表达式中的 "取绝对值(-5.0)"
     * @param name 函数名称
     * @param aClass 类
     * @param aFunctionName 类中的方法名称
     * @param aParameterClassTypes 方法的参数类型名称
     * @param errorInfo 如果函数执行的结果是false,需要输出的错误信息
     * @throws Exception
     */
    public void addFunctionOfClassMethod(String name, Class<?> aClass,
                                         String aFunctionName, Class<?>[] aParameterClassTypes,
                                         String errorInfo) throws Exception {
        this.addFunction(name, new OperatorSelfDefineClassFunction(name,
                aClass, aFunctionName, aParameterClassTypes,null,null, errorInfo));
        
    }
    
T
update  
tianqiao 已提交
301 302 303 304 305 306
    /**
     * 添加一个类的函数定义,例如:Math.abs(double) 映射为表达式中的 "取绝对值(-5.0)"
     * @param name 函数名称
     * @param aClassName 类名称
     * @param aFunctionName 类中的方法名称
     * @param aParameterClassTypes 方法的参数类型名称
T
tianqiao 已提交
307
     * @param aParameterDesc 方法的参数说明
T
update  
tianqiao 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
     * @param aParameterAnnotation 方法的参数注解
     * @param errorInfo 如果函数执行的结果是false,需要输出的错误信息
     * @throws Exception
     */
	public void addFunctionOfClassMethod(String name, String aClassName,
			String aFunctionName, Class<?>[] aParameterClassTypes,
			String[] aParameterDesc,String[] aParameterAnnotation,
			String errorInfo) throws Exception {
		this.addFunction(name, new OperatorSelfDefineClassFunction(name,
				aClassName, aFunctionName, aParameterClassTypes,aParameterDesc,aParameterAnnotation, errorInfo));

	}
    /**
     * 添加一个类的函数定义,例如:Math.abs(double) 映射为表达式中的 "取绝对值(-5.0)"
     * @param name 函数名称
     * @param aClassName 类名称
     * @param aFunctionName 类中的方法名称
     * @param aParameterTypes 方法的参数类型名称
     * @param errorInfo 如果函数执行的结果是false,需要输出的错误信息
     * @throws Exception
     */
	public void addFunctionOfClassMethod(String name, String aClassName,
			String aFunctionName, String[] aParameterTypes, String errorInfo)
			throws Exception {
		this.addFunction(name, new OperatorSelfDefineClassFunction(name,
T
tianqiao 已提交
333
				aClassName, aFunctionName, aParameterTypes, null,null,errorInfo));
T
update  
tianqiao 已提交
334 335 336 337 338 339 340
	}
    /**
     * 添加一个类的函数定义,例如:Math.abs(double) 映射为表达式中的 "取绝对值(-5.0)"
     * @param name 函数名称
     * @param aClassName 类名称
     * @param aFunctionName 类中的方法名称
     * @param aParameterTypes 方法的参数类型名称
T
tianqiao 已提交
341
     * @param aParameterDesc 方法的参数说明
T
update  
tianqiao 已提交
342 343 344 345 346 347 348 349 350 351
     * @param aParameterAnnotation 方法的参数注解
     * @param errorInfo 如果函数执行的结果是false,需要输出的错误信息
     * @throws Exception
     */
	public void addFunctionOfClassMethod(String name, String aClassName,
			String aFunctionName, String[] aParameterTypes,
			String[] aParameterDesc,String[] aParameterAnnotation,
			String errorInfo)
			throws Exception {
		this.addFunction(name, new OperatorSelfDefineClassFunction(name,
T
tianqiao 已提交
352 353
				aClassName, aFunctionName, aParameterTypes, aParameterDesc,aParameterAnnotation,errorInfo));

T
update  
tianqiao 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	}
    /**
     * 用于将一个用户自己定义的对象(例如Spring对象)方法转换为一个表达式计算的函数
     * @param name
     * @param aServiceObject
     * @param aFunctionName
     * @param aParameterClassTypes
     * @param errorInfo
     * @throws Exception
     */
	public void addFunctionOfServiceMethod(String name, Object aServiceObject,
			String aFunctionName, Class<?>[] aParameterClassTypes,
			String errorInfo) throws Exception {
		this.addFunction(name, new OperatorSelfDefineServiceFunction(name,
				aServiceObject, aFunctionName, aParameterClassTypes,null,null, errorInfo));
T
tianqiao 已提交
369

T
update  
tianqiao 已提交
370 371 372 373 374 375 376
	}
    /**
     * 用于将一个用户自己定义的对象(例如Spring对象)方法转换为一个表达式计算的函数
     * @param name
     * @param aServiceObject
     * @param aFunctionName
     * @param aParameterClassTypes
T
tianqiao 已提交
377
     * @param aParameterDesc 方法的参数说明
T
update  
tianqiao 已提交
378 379 380
     * @param aParameterAnnotation 方法的参数注解
     * @param errorInfo
     * @throws Exception
T
tianqiao 已提交
381
     */
T
update  
tianqiao 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	public void addFunctionOfServiceMethod(String name, Object aServiceObject,
			String aFunctionName, Class<?>[] aParameterClassTypes,
			String[] aParameterDesc,String[] aParameterAnnotation,
			String errorInfo) throws Exception {
		this.addFunction(name, new OperatorSelfDefineServiceFunction(name,
				aServiceObject, aFunctionName, aParameterClassTypes,aParameterDesc,aParameterAnnotation, errorInfo));

	}
    /**
     * 用于将一个用户自己定义的对象(例如Spring对象)方法转换为一个表达式计算的函数
     * @param name
     * @param aServiceObject
     * @param aFunctionName
     * @param aParameterTypes
     * @param errorInfo
     * @throws Exception
     */
	public void addFunctionOfServiceMethod(String name, Object aServiceObject,
			String aFunctionName, String[] aParameterTypes, String errorInfo)
T
tianqiao 已提交
401
			throws Exception {
T
update  
tianqiao 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
		this.addFunction(name, new OperatorSelfDefineServiceFunction(name,
				aServiceObject, aFunctionName, aParameterTypes,null,null, errorInfo));

	}
	public void addFunctionOfServiceMethod(String name, Object aServiceObject,
			String aFunctionName, String[] aParameterTypes,
			String[] aParameterDesc,String[] aParameterAnnotation,
			String errorInfo)
			throws Exception {
		this.addFunction(name, new OperatorSelfDefineServiceFunction(name,
				aServiceObject, aFunctionName, aParameterTypes,aParameterDesc,aParameterAnnotation, errorInfo));

	}
	/**
	 * 添加操作符号,此操作符号的优先级与 "*"相同,语法形式也是  data name data
	 * @param name
	 * @param op
T
tianqiao 已提交
419
	 * @throws Exception
T
update  
tianqiao 已提交
420 421 422 423 424 425 426 427 428
	 */
	public void addOperator(String name,Operator op) throws Exception {
		 this.addOperator(name, "*", op);
	}
	/**
	 * 添加操作符号,此操作符号与给定的参照操作符号在优先级别和语法形式上一致
	 * @param name 操作符号名称
	 * @param aRefOpername 参照的操作符号,例如 "+","--"等
	 * @param op
T
tianqiao 已提交
429
	 * @throws Exception
T
update  
tianqiao 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	 */
	public void addOperator(String name,String aRefOpername,Operator op) throws Exception {
		this.manager.addOperatorWithLevelOfReference(name, aRefOpername);
		this.operatorManager.addOperator(name, op);
	}

	/**
	 * 添加操作符和关键字的别名,同时对操作符可以指定错误信息。
	 * 例如:addOperatorWithAlias("加","+",null)
	 * @param keyWordName
	 * @param realKeyWordName
	 * @param errorInfo
	 * @throws Exception
	 */
	public void addOperatorWithAlias(String keyWordName, String realKeyWordName,
			String errorInfo) throws Exception {
		if(errorInfo != null && errorInfo.trim().length() == 0){
			errorInfo = null;
		}
		//添加函数别名
		if(this.manager.isFunction(realKeyWordName)){
			this.manager.addFunctionName(keyWordName);
			this.operatorManager.addOperatorWithAlias(keyWordName, realKeyWordName, errorInfo);
			return;
		}
		NodeType realNodeType = this.manager.findNodeType(realKeyWordName);
		if(realNodeType == null){
T
tianqiao 已提交
457
			throw new Exception("关键字:" + realKeyWordName +"不存在");
T
update  
tianqiao 已提交
458 459 460 461 462 463 464 465 466
		}
		boolean isExist = this.operatorManager.isExistOperator(realNodeType.getName());
		if(isExist == false &&  errorInfo != null){
			throw new Exception("关键字:" + realKeyWordName +"是通过指令来实现的,不能设置错误的提示信息,errorInfo 必须是 null");
		}
		if(isExist == false || errorInfo == null){
			//不需要新增操作符号,只需要建立一个关键子即可
			this.manager.addOperatorWithRealNodeType(keyWordName, realNodeType.getName());
		}else{
T
tianqiao 已提交
467
			this.manager.addOperatorWithLevelOfReference(keyWordName, realNodeType.getName());
T
update  
tianqiao 已提交
468 469 470 471 472 473 474 475 476 477
			this.operatorManager.addOperatorWithAlias(keyWordName, realNodeType.getName(), errorInfo);
		}
	}
	/**
	 * 替换操作符处理
	 * @param name
	 */
    public OperatorBase replaceOperator(String name,OperatorBase op){
    	return this.operatorManager.replaceOperator(name, op);
    }
T
tianqiao 已提交
478

T
update  
tianqiao 已提交
479 480 481 482 483 484 485
	public ExpressPackage getRootExpressPackage(){
		return this.rootExpressPackage;
	}
	  /**
	   * 清除缓存
	   */
	public void clearExpressCache() {
486 487 488
        synchronized (expressInstructionSetCache) {
            this.expressInstructionSetCache.clear();
        }
T
update  
tianqiao 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
	}
	/**
	 * 根据表达式的名称进行执行
	 * @param name
	 * @param context
	 * @param errorList
	 * @param isTrace
	 * @param isCatchException
	 * @param aLog
	 * @return
	 * @throws Exception
	 */
	public Object executeByExpressName(String name,IExpressContext<String,Object> context, List<String> errorList,
			boolean isTrace,boolean isCatchException, Log aLog) throws Exception {
		return  InstructionSetRunner.executeOuter(this,this.loader.getInstructionSet(name),this.loader,context, errorList,
			 	isTrace,isCatchException,aLog,false);

	}

	/**
	 * 执行指令集(兼容老接口,请不要自己管理指令缓存,直接使用execute(InstructionSet instructionSets,....... )
	 * 清理缓存可以使用clearExpressCache()函数
	 * @param instructionSets
	 * @param context
	 * @param errorList
	 * @param isTrace
	 * @param isCatchException
	 * @param aLog
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public Object execute(InstructionSet[] instructionSets,IExpressContext<String,Object> context, List<String> errorList,
						  boolean isTrace,boolean isCatchException, Log aLog) throws Exception {
		return  InstructionSetRunner.executeOuter(this,instructionSets[0],this.loader,context, errorList,
				isTrace,isCatchException,aLog,false);
	}
T
tianqiao 已提交
526

T
update  
tianqiao 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	/**
	 * 执行指令集
	 * @param instructionSets
	 * @param context
	 * @param errorList
	 * @param isTrace
	 * @param isCatchException
	 * @param aLog
	 * @return
	 * @throws Exception
	 */
	public Object execute(InstructionSet instructionSets,IExpressContext<String,Object> context, List<String> errorList,
			boolean isTrace,boolean isCatchException, Log aLog) throws Exception {
		return  InstructionSetRunner.executeOuter(this,instructionSets,this.loader,context, errorList,
				 	isTrace,isCatchException,aLog,false);
	}
/**
 * 执行一段文本
 * @param expressString 程序文本
 * @param context 执行上下文
 * @param errorList 输出的错误信息List
 * @param isCache 是否使用Cache中的指令集
 * @param isTrace 是否输出详细的执行指令信息
 * @return
 * @throws Exception
 */
	public Object execute(String expressString, IExpressContext<String,Object> context,
			List<String> errorList, boolean isCache, boolean isTrace) throws Exception {
		return this.execute(expressString, context, errorList, isCache, isTrace, null);
	}
/**
 * 执行一段文本
 * @param expressString 程序文本
 * @param context 执行上下文
 * @param errorList 输出的错误信息List
 * @param isCache 是否使用Cache中的指令集
 * @param isTrace 是否输出详细的执行指令信息
 * @param aLog 输出的log
 * @return
 * @throws Exception
 */
	public Object execute(String expressString, IExpressContext<String,Object> context,
			List<String> errorList, boolean isCache, boolean isTrace, Log aLog)
			throws Exception {
		InstructionSet parseResult = null;
		if (isCache == true) {
			parseResult = expressInstructionSetCache.get(expressString);
			if (parseResult == null) {
				synchronized (expressInstructionSetCache) {
					parseResult = expressInstructionSetCache.get(expressString);
					if (parseResult == null) {
						parseResult = this.parseInstructionSet(expressString);
						expressInstructionSetCache.put(expressString,
								parseResult);
					}
				}
			}
		} else {
			parseResult = this.parseInstructionSet(expressString);
		}
		return  InstructionSetRunner.executeOuter(this,parseResult,this.loader,context, errorList,
			 	isTrace,false,aLog,false);
	}

T
tianqiao 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	public RuleResult executeRule(String expressString, IExpressContext<String,Object> context, boolean isCache, boolean isTrace)
			throws Exception {
		Rule rule = null;
		if (isCache == true) {
			rule = ruleCache.get(expressString);
			if (rule == null) {
				synchronized (ruleCache) {
					rule = ruleCache.get(expressString);
					if (rule == null) {
						rule = this.parseRule(expressString);
						ruleCache.put(expressString,
								rule);
					}
				}
			}
		} else {
			rule = this.parseRule(expressString);
		}
		return RuleManager.executeRule(this,rule,context,isCache,isTrace);
	}

	static Pattern patternRule = Pattern.compile("rule[\\s]+'([^']+)'[\\s]+name[\\s]+'([^']+)'[\\s]+");

	public Rule parseRule(String text)
			throws Exception {
		String ruleName = null;
		String ruleCode = null;
        Matcher matcher = patternRule.matcher(text);
        if(matcher.find()) {
            ruleCode = matcher.group(1);
            ruleName = matcher.group(2);
            text = text.substring(matcher.end());
        }

		Map<String,String> selfDefineClass = new HashMap<String,String> ();
		for(ExportItem  item : this.loader.getExportInfo()){
			if(item.getType().equals(InstructionSet.TYPE_CLASS)){
				selfDefineClass.put(item.getName(), item.getName());
			}
		}

//      分成两句话执行,用来保存中间的words结果
//		ExpressNode root = this.parse.parse(this.rootExpressPackage,text, isTrace,selfDefineClass);

		Word[] words = this.parse.splitWords(rootExpressPackage,text,isTrace,selfDefineClass);
		ExpressNode root =  this.parse.parse(rootExpressPackage,words,text,isTrace,selfDefineClass);
		Rule rule = RuleManager.createRule(root,words);
		rule.setCode(ruleCode);
		rule.setName(ruleName);
		return rule;
	}
    
    public Condition parseContition(String text)
            throws Exception {
        
        Map<String,String> selfDefineClass = new HashMap<String,String> ();
        for(ExportItem  item : this.loader.getExportInfo()){
            if(item.getType().equals(InstructionSet.TYPE_CLASS)){
                selfDefineClass.put(item.getName(), item.getName());
            }
        }
        
        Word[] words = this.parse.splitWords(rootExpressPackage,text,isTrace,selfDefineClass);
        ExpressNode root =  this.parse.parse(rootExpressPackage,words,text,isTrace,selfDefineClass);
        return RuleManager.createCondition(root,words);
    }

T
update  
tianqiao 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671
	/**
	 * 解析一段文本,生成指令集合
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public InstructionSet parseInstructionSet(String text)
			throws Exception {
		Map<String,String> selfDefineClass = new HashMap<String,String> ();
		for(ExportItem  item : this.loader.getExportInfo()){
			if(item.getType().equals(InstructionSet.TYPE_CLASS)){
				selfDefineClass.put(item.getName(), item.getName());
			}
		}
T
tianqiao 已提交
672

T
update  
tianqiao 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686
		ExpressNode root = this.parse.parse(this.rootExpressPackage,text, isTrace,selfDefineClass);
		InstructionSet result = createInstructionSet(root, "main");
		if (this.isTrace && log.isDebugEnabled()) {
			log.debug(result);
		}
		return result;
	}
	/**
	 * 输出全局定义信息
	 * @return
	 */
	public ExportItem[] getExportInfo(){
		return this.loader.getExportInfo();
	}
T
tianqiao 已提交
687

T
update  
tianqiao 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
	/**
	 * 优先从本地指令集缓存获取指令集,没有的话生成并且缓存在本地
	 * @param expressString
	 * @return
	 * @throws Exception
	 */
	public InstructionSet getInstructionSetFromLocalCache(String expressString)
			throws Exception {
		InstructionSet parseResult = expressInstructionSetCache.get(expressString);
		if (parseResult == null) {
			synchronized (expressInstructionSetCache) {
				parseResult = expressInstructionSetCache.get(expressString);
				if (parseResult == null) {
					parseResult = this.parseInstructionSet(expressString);
					expressInstructionSetCache.put(expressString,
							parseResult);
				}
			}
		}
		return parseResult;
	}

	public InstructionSet createInstructionSet(ExpressNode root, String type)
			throws Exception {
		InstructionSet result = new InstructionSet(type);
		createInstructionSet(root, result);
		return result;
	}

	public void createInstructionSet(ExpressNode root, InstructionSet result)
			throws Exception {
		Stack<ForRelBreakContinue> forStack = new Stack<ForRelBreakContinue>();
		createInstructionSetPrivate(result, forStack, root, true);
		if (forStack.size() > 0) {
			throw new Exception("For处理错误");
		}
	}

	public boolean createInstructionSetPrivate(InstructionSet result,
			Stack<ForRelBreakContinue> forStack, ExpressNode node,
			boolean isRoot) throws Exception {
		InstructionFactory factory = InstructionFactory
				.getInstructionFactory(node.getInstructionFactory());
		boolean hasLocalVar = factory.createInstruction(this,result, forStack, node, isRoot);
		return hasLocalVar;
	}
	/**
	 * 获取一个表达式需要的外部变量名称列表
	 * @param express
	 * @return
T
tianqiao 已提交
738
	 * @throws Exception
T
update  
tianqiao 已提交
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
	 */
	public String[] getOutVarNames(String express) throws Exception{
		return this.parseInstructionSet(express).getOutAttrNames();
	}

	public String[] getOutFunctionNames(String express) throws Exception{
		return this.parseInstructionSet(express).getOutFunctionNames();
	}


	public boolean isShortCircuit() {
		return isShortCircuit;
	}
	public void setShortCircuit(boolean isShortCircuit) {
		this.isShortCircuit = isShortCircuit;
	}
755 756
    
    /**
T
tianqiao 已提交
757
     * 是否忽略charset类型的数据,而识别为string,比如'a' -》 "a"
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
     * 默认为不忽略,正常识别为String
     */
    public boolean isIgnoreConstChar() {
        return this.parse.isIgnoreConstChar();
    }
    public void setIgnoreConstChar(boolean ignoreConstChar) {
        this.parse.setIgnoreConstChar(ignoreConstChar);
    }
    
    /**
     * 提供简答的语法检查,保证可以在运行期本地环境编译成指令
     * @param text
     * @return
     */
    public boolean checkSyntax(String text)
    {
        return checkSyntax(text,false,null);
    }
    
    /**
     * 提供复杂的语法检查,(比如检查自定义的java类),不保证运行期在本地环境可以编译成指令
     * @param text
     * @param mockRemoteJavaClass
     * @param remoteJavaClassNames
     * @return
     */
    public boolean checkSyntax(String text,boolean mockRemoteJavaClass,List<String> remoteJavaClassNames){

        try {
            Map<String, String> selfDefineClass = new HashMap<String, String>();
            for (ExportItem item : this.loader.getExportInfo()) {
                if (item.getType().equals(InstructionSet.TYPE_CLASS)) {
                    selfDefineClass.put(item.getName(), item.getName());
                }
            }
            Word[] words = this.parse.splitWords(rootExpressPackage,text,isTrace,selfDefineClass);
            ExpressNode root = this.parse.parse(this.rootExpressPackage, words,text, isTrace, selfDefineClass,mockRemoteJavaClass);
            InstructionSet result = createInstructionSet(root, "main");
            if (this.isTrace && log.isDebugEnabled()) {
                log.debug(result);
            }
            if(mockRemoteJavaClass && remoteJavaClassNames!=null) {
                remoteJavaClassNames.addAll(Arrays.asList(result.getVirClasses()));
            }
            return true;
        }catch (Exception e){
            log.error("checkSyntax has Exception",e);
            return false;
        }
    }
T
update  
tianqiao 已提交
808
}