*
Helper factory method to instantiate a LogicExpression.
@param  input  The string to parse.
@param  factoryDelegate  The factory to build tokens.
@return  a new LogicExpression
482409
public static <E> LogicExpression<E> compile(final String input,
            final Function<String, Arg<E>> factoryDelegate) {
        return new LogicExpressionParser<E>() {
            @Override
            public Arg<E> factory(String argument) {
                return factoryDelegate.apply(argument);
            }
        }.parse(input);
    }
1109817
public Object read(final InputSource in) throws SAXException,
                                            IOException {
        if ( this.docFragment == null ) {
            DocumentBuilderFactory f;
            try {
                f =  DocumentBuilderFactory.newInstance();
            } catch ( FactoryConfigurationError e ) {
                // obscure JDK1.5 bug where FactoryFinder in the JRE returns a null ClassLoader, so fall back to hard coded xerces.
                // https://stg.network.org/bugzilla/show_bug.cgi?id=47169
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4633368
                try {
                    f = (DocumentBuilderFactory) Class.forName( "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" ).newInstance();
                } catch ( Exception e1 ) {
                    throw new RuntimeException( "Unable to create new DOM Document",
                                                e1 );
                }
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to create new DOM Document",
                                            e );
            }
            // XXE protection start
            try {
                f.setFeature("http://xml.org/sax/features/external-general-entities", false);
                f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

            } catch (ParserConfigurationException e) {
                logger.warn("Unable to set parser features due to {}", e.getMessage());
            }
            // XXE protection end
            try {
                this.document = f.newDocumentBuilder().newDocument();
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to create new DOM Document",
                                            e );
            }
            this.docFragment = this.document.createDocumentFragment();
        }

        SAXParser localParser = null;
        if ( this.parser == null ) {
            SAXParserFactory factory = null;
            try {
                factory = SAXParserFactory.newInstance();
            } catch ( FactoryConfigurationError e) {
                // obscure JDK1.5 bug where FactoryFinder in the JRE returns a null ClassLoader, so fall back to hard coded xerces.
                // https://stg.network.org/bugzilla/show_bug.cgi?id=47169
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4633368                
                try {
                    factory = (SAXParserFactory) Class.forName( "org.apache.xerces.jaxp.SAXParserFactoryImpl" ).newInstance();
                } catch ( Exception e1 ) {
                    throw new RuntimeException( "Unable to create new DOM Document",
                                                e1 );
                }
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to create new DOM Document",
                                            e );
            }
            
            factory.setNamespaceAware( true );
            // XXE protection start
            try {
                factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
                factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

            } catch (ParserConfigurationException e) {
                logger.warn("Unable to set parser features due to {}", e.getMessage());
            }
            // XXE protection end

            if ( System.getProperty( "drools.schema.validating" ) != null ) {
                this.isValidating = Boolean.getBoolean( "drools.schema.validating" );
            }

            if ( this.isValidating == true ) {
                factory.setValidating( true );
                try {
                    localParser = factory.newSAXParser();
                } catch ( final ParserConfigurationException e ) {
                    throw new RuntimeException( e.getMessage() );
                }

                try {
                    localParser.setProperty( ExtensibleXmlParser.JAXP_SCHEMA_LANGUAGE,
                                             ExtensibleXmlParser.W3C_XML_SCHEMA );
                } catch ( final SAXNotRecognizedException e ) {
                    boolean hideWarnings = Boolean.getBoolean( "drools.schema.hidewarnings" );
                    if ( !hideWarnings ) {
                        logger.warn( "Your SAX parser is not JAXP 1.2 compliant - turning off validation." );
                    }
                    localParser = null;
                }
            }

            if ( localParser == null ) {
                // not jaxp1.2 compliant so turn off validation
                try {
                    this.isValidating = false;
                    factory.setValidating( this.isValidating );
                    localParser = factory.newSAXParser();
                } catch ( final ParserConfigurationException e ) {
                    throw new RuntimeException( e.getMessage() );
                }
            }
        } else {
            localParser = this.parser;
        }

        if ( !localParser.isNamespaceAware() ) {
            throw new RuntimeException( "parser must be namespace-aware" );
        }

        localParser.parse( in,
                           this );

        return this.data;
    }
771342
public Expression create(String expression, ExpressionType expressionType, PropertyResolver propertyResolver) {
        if (expressionType == null) {
            expressionType = ExpressionType.MVEL;
        }
        if (propertyResolver == null) {
            propertyResolver = SystemAndTestPropertyResolver.INSTANCE;
        }
        switch (expressionType) {
        case MVEL:
            return new MVELExpression(expression, propertyResolver);
        default:
            throw CommonKnowledgeMessages.MESSAGES.unknownExpressionType(expressionType.toString());
        }
    }
1096329
@SuppressWarnings("checkstyle:npathcomplexity")
	private void createImplicitActionReturnType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) {
		final List<XtendFunction> actions = EcoreUtil2.eAllOfType(resource.getContents().get(0), XtendFunction.class);

		for (final XtendFunction action : actions) {
			// inline annotation only for methods with no return type
			if (action.getReturnType() != null) {
				continue;
			}
			// get return type name from operation
			final JvmOperation inferredOperation = (JvmOperation) this.jvmModelAssocitions.getPrimaryJvmElement(action);
			if (inferredOperation == null || inferredOperation.getReturnType() == null) {
				continue;
			}
			// find document offset for inline annotationn
			final ICompositeNode node = NodeModelUtils.findActualNodeFor(action);
			final Keyword parenthesis = this.grammar.getAOPMemberAccess().getRightParenthesisKeyword_2_5_6_2();
			final Assignment fctname = this.grammar.getAOPMemberAccess().getNameAssignment_2_5_5();
			int offsetFctname = -1;
			int offsetParenthesis = -1;
			for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
				final INode child = it.next();
				if (child != node) {
					final EObject grammarElement = child.getGrammarElement();
					if (grammarElement instanceof RuleCall) {
						if (fctname.equals(grammarElement.eContainer())) {
							offsetFctname = child.getTotalEndOffset();
						}
					} else if (parenthesis.equals(grammarElement)) {
						offsetParenthesis = child.getTotalEndOffset();
						break;
					}
				}
			}
			int offset = -1;
			if (offsetParenthesis >= 0) {
				offset = offsetParenthesis;
			} else if (offsetFctname >= 0) {
				offset = offsetFctname;
			}
			if (offset >= 0) {
				final String returnType = inferredOperation.getReturnType().getSimpleName();
				final String text = " " + this.keywords.getColonKeyword() + " " + returnType; //$NON-NLS-1$ //$NON-NLS-2$
				acceptor.accept(createNewLineContentCodeMining(offset, text));
			}
		}
	}
418050
public final AbstractButton createButton(ButtonFactory buttonFactory, CommandButtonConfigurer buttonConfigurer) {
		return createButton(getDefaultFaceDescriptorId(), buttonFactory, buttonConfigurer);
	}
1011221
public static MessageFilterParser createParser(String input) {
    	    ANTLRStringStream inputStream = new ANTLRStringStream(input);
    		MessageFilterLexer lexer = new MessageFilterLexer(inputStream);
    		CommonTokenStream tokens = new CommonTokenStream(lexer); 
    		
    		return new MessageFilterParser(tokens);
        }
1181372
public static <E> OptionalFunction<Selection<Constructor<?>>, E> instantiate(Object... args) {
    return OptionalFunction.of(selection -> factory.createInvoker(selection.result()).withArgs(args));
  }
1311879
public final hqlParser.logicalExpression_return logicalExpression() throws RecognitionException {
		hqlParser.logicalExpression_return retval = new hqlParser.logicalExpression_return();
		retval.start = input.LT(1);

		CommonTree root_0 = null;

		ParserRuleReturnScope expression153 =null;


		try {
			// hql.g:405:2: ( expression )
			// hql.g:405:4: expression
			{
			root_0 = (CommonTree)adaptor.nil();


			pushFollow(FOLLOW_expression_in_logicalExpression1866);
			expression153=expression();
			state._fsp--;

			adaptor.addChild(root_0, expression153.getTree());

			}

			retval.stop = input.LT(-1);

			retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
			adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
			retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
		}
		finally {
			// do for sure before leaving
		}
		return retval;
	}
789119
@Nullable
    @Override
    public DFA<?, I> findCounterExample(DFA<?, I> automaton, Collection<? extends I> inputs, String property)
            throws ModelCheckingException {
        final File fsm = findCounterExampleFSM(automaton, inputs, property);

        try {
            final CompactDFA<I> result;
            if (fsm != null) {
                result = FSM2DFAParser.getParser(inputs, getString2Input(), LABEL_NAME, LABEL_VALUE).readModel(fsm);

                // check if we must keep the FSM
                if (!isKeepFiles() && !fsm.delete()) {
                    throw new ModelCheckingException("Could not delete file: " + fsm.getAbsolutePath());
                }

                for (Integer state : result.getStates()) {
                    final boolean deadlocks = result.getInputAlphabet().stream().noneMatch(
                            i -> result.getSuccessor(state, i) != null);
                    result.setAccepting(state, deadlocks);
                }
            } else {
                result = null;
            }

            return result;
        } catch (IOException | FSMParseException e) {
            throw new ModelCheckingException(e);
        }
    }
13807
public static <T> SimpleExpression<T> asSimple(Expression<T> expr) {
        Expression<T> underlyingMixin = ExpressionUtils.extract(expr);
        if (underlyingMixin instanceof PathImpl) {
            return new SimplePath<T>((PathImpl<T>) underlyingMixin);
        } else if (underlyingMixin instanceof OperationImpl) {
            return new SimpleOperation<T>((OperationImpl<T>) underlyingMixin);
        } else if (underlyingMixin instanceof TemplateExpressionImpl) {
            return new SimpleTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin);
        } else {
            return new SimpleExpression<T>(underlyingMixin) {

                private static final long serialVersionUID = -8712299418891960222L;

                @Override
                public <R, C> R accept(Visitor<R, C> v, C context) {
                    return this.mixin.accept(v, context);
                }

            };
        }
    }
141963
public final hqlParser.logicalAndExpression_return logicalAndExpression() throws RecognitionException {
		hqlParser.logicalAndExpression_return retval = new hqlParser.logicalAndExpression_return();
		retval.start = input.LT(1);

		CommonTree root_0 = null;

		Token AND159=null;
		ParserRuleReturnScope negatedExpression158 =null;
		ParserRuleReturnScope negatedExpression160 =null;

		CommonTree AND159_tree=null;

		try {
			// hql.g:420:2: ( negatedExpression ( AND ^ negatedExpression )* )
			// hql.g:420:4: negatedExpression ( AND ^ negatedExpression )*
			{
			root_0 = (CommonTree)adaptor.nil();


			pushFollow(FOLLOW_negatedExpression_in_logicalAndExpression1912);
			negatedExpression158=negatedExpression();
			state._fsp--;

			adaptor.addChild(root_0, negatedExpression158.getTree());

			// hql.g:420:22: ( AND ^ negatedExpression )*
			loop52:
			while (true) {
				int alt52=2;
				int LA52_0 = input.LA(1);
				if ( (LA52_0==AND) ) {
					alt52=1;
				}

				switch (alt52) {
				case 1 :
					// hql.g:420:24: AND ^ negatedExpression
					{
					AND159=(Token)match(input,AND,FOLLOW_AND_in_logicalAndExpression1916);
					AND159_tree = (CommonTree)adaptor.create(AND159);
					root_0 = (CommonTree)adaptor.becomeRoot(AND159_tree, root_0);

					pushFollow(FOLLOW_negatedExpression_in_logicalAndExpression1919);
					negatedExpression160=negatedExpression();
					state._fsp--;

					adaptor.addChild(root_0, negatedExpression160.getTree());

					}
					break;

				default :
					break loop52;
				}
			}

			}

			retval.stop = input.LT(-1);

			retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
			adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
			retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
		}
		finally {
			// do for sure before leaving
		}
		return retval;
	}
688749
@Override
    public void constructorFactory(Sink sink, String dataTypeName, String factoryName, List<String> typeParametrs, Constructor constructor) {
        if (constructor.args.isEmpty()) {
        	if (typeParametrs.isEmpty()) {
            	logger.finest("Generating no args, no types factory for " + constructor.name);
        	} else {
            	logger.finest("Generating no args, type arguments factory for " + constructor.name);
        		sink.write("   @SuppressWarnings(\"rawtypes\")\n");
        	}
            sink.write("   private static final " + dataTypeName + " _" + factoryName + " = new " + constructor.name + "();\n");
            sink.write(ASTPrinter.printComments("   ", commentProcessor.leftAlign(commentProcessor.javaDocOnly(constructor.comments))));
        	if (!typeParametrs.isEmpty()) {
        		sink.write("   @SuppressWarnings(\"unchecked\")\n");
        	}
        	sink.write("   public static final ");
        	emitParameterizedTypeName(sink, typeParametrs);
        	sink.write(" ");
        	sink.write(dataTypeName);
        	emitParameterizedTypeName(sink, typeParametrs);
        	sink.write(" _" + factoryName + "() { return _" + factoryName + "; }");
        } else {
        	logger.finest("Generating args factory for " + constructor.name);
            sink.write(ASTPrinter.printComments("   ", commentProcessor.leftAlign(constructor.comments)));
            sink.write("   public static final ");
            emitParameterizedTypeName(sink, typeParametrs);
        	sink.write(" ");
        	sink.write(dataTypeName);
            emitParameterizedTypeName(sink, typeParametrs);
            sink.write(" _" + factoryName + "(");
            constructorArgs(sink, constructor, true);
            sink.write(") { return new " + constructor.name);
            emitParameterizedTypeName(sink, typeParametrs);
            sink.write("("); 
            constructorArgs(sink, constructor, false);
            sink.write("); }");            
        }
    }
345798
private static Object computeFragment(final ITemplateContext context, final String input) {

        final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration());

        final String trimmedInput = input.trim();

        if (shouldBeWrappedAsFragmentExpression(trimmedInput)) {
            // We do not know for sure that this is a complete standard expression, so we will consider it the
            // content of a FragmentExpression for legacy compatibility reasons.
            // We will only reach this point if the expression does not contain any Fragment Expressions expressed
            // as ~{...} (excluding parameters), nor the "::" fragment selector separator.
            // NOTE we are using the generic parseExpression() and not directly calling a parse method in the
            // FragmentExpression class because we want to take advantage of the expression cache.
            final FragmentExpression fragmentExpression =
                    (FragmentExpression) expressionParser.parseExpression(context, "~{" + trimmedInput + "}");

            final FragmentExpression.ExecutedFragmentExpression executedFragmentExpression =
                    FragmentExpression.createExecutedFragmentExpression(context, fragmentExpression);

            if (executedFragmentExpression.getFragmentSelectorExpressionResult() == null && executedFragmentExpression.getFragmentParameters() == null) {
                // We might be in the scenario that what we thought was a template name in fact was instead an expression
                // returning a Fragment itself, so we should simply return it
                final Object templateNameExpressionResult = executedFragmentExpression.getTemplateNameExpressionResult();
                if (templateNameExpressionResult != null) {
                    if (templateNameExpressionResult instanceof Fragment) {
                        return templateNameExpressionResult;
                    }
                    if (templateNameExpressionResult == NoOpToken.VALUE) {
                        return NoOpToken.VALUE;
                    }
                }
            }

            // Given this is a simple (originally unwrapped) fragment expression, we will consider the non-existence
            // of the fragment a failure. The reason we do this here instead of just waiting and seeing if we receive
            // a null and then failing is that, in order to receive such "null", the underlying resolution system would
            // have to execute a (potentially costly) resource.exists() call on the resolved resource.
            return FragmentExpression.resolveExecutedFragmentExpression(context, executedFragmentExpression, true);

        }

        // If we reached this point, we know for sure this is a complete fragment expression, so we just parse it
        // as such and execute it

        final IStandardExpression fragmentExpression = expressionParser.parseExpression(context, trimmedInput);

        final Object fragmentExpressionResult;

        if (fragmentExpression != null && fragmentExpression instanceof FragmentExpression) {
            // This is not a complex expression but merely a FragmentExpression, so we can apply a shortcut
            // so that we don't require a "null" result for this expression if the template does not exist. That will
            // save a call to resource.exists() which might be costly.

            final FragmentExpression.ExecutedFragmentExpression executedFragmentExpression =
                    FragmentExpression.createExecutedFragmentExpression(context, (FragmentExpression) fragmentExpression);

            fragmentExpressionResult =
                    FragmentExpression.resolveExecutedFragmentExpression(context, executedFragmentExpression, true);

        } else {

            fragmentExpressionResult = fragmentExpression.execute(context);

        }

        if (fragmentExpressionResult == null || fragmentExpressionResult == NoOpToken.VALUE) {
            return fragmentExpressionResult;
        }

        if (!(fragmentExpressionResult instanceof Fragment)) {
            throw new TemplateProcessingException(
                    "Invalid fragment specification: \"" + input + "\": " +
                    "expression does not return a Fragment object");
        }

        return fragmentExpressionResult;

    }
936607
public MtasTokenizer create(AttributeFactory factory, String configuration, String defaultConfiguration)
      throws IOException {
    if(defaultConfiguration==null) {
      defaultConfiguration = defaultArgument;
    }
    if (configs != null && configs.size() > 0) {
      if (configuration == null && defaultConfiguration == null) {
        throw new IOException("no (default)configuration");
      } else if (configuration == null) {
        if (configs.get(defaultConfiguration) != null) {
          return new MtasTokenizer(factory, configs.get(defaultConfiguration));
        } else {
          throw new IOException(
              "default configuration " + defaultConfiguration + " not available");
        }
      } else {
        MtasConfiguration config = configs.get(configuration);
        if (config == null) {
          if (defaultConfiguration != null) {
            if (configs.get(defaultConfiguration) != null) {
              return new MtasTokenizer(factory, configs.get(defaultConfiguration));
            } else {
              throw new IOException("configuration " + configuration
                  + " not found and default configuration " + defaultConfiguration
                  + " not available");
            }
          } else {
            throw new IOException("configuration " + configuration
                + " not available and no default configuration");
          }
        } else {
          return new MtasTokenizer(factory, config);
        }
      }
    } else if (config != null) {
      return new MtasTokenizer(factory, config);
    } else {
      throw new IOException("no configuration");
    }
  }
1241893
public Expression createExpression(final String expression, final Class expectedType) {
        val parserContext = new FluentParserContext().expectResult(expectedType);
        return getSpringExpressionParser().parseExpression(expression, parserContext);
    }
1261985
@SuppressWarnings("unchecked")
    public static InputComponent createUIInput(UIProvider provider, InputComponentFactory factory, ConverterFactory converterFactory, String parentName, String name,
                                               Class inputClazz, String required, String currentValue, String defaultValue, String enums, String description,
                                               boolean promptInInteractiveMode, boolean multiValue, String prefix) {

        // is the current value a property placeholder, then we need to use a regular text based UI
        if (currentValue != null && currentValue.startsWith("{{") && currentValue.endsWith("}}")) {
            // switch over to plain string
            inputClazz = String.class;
            enums = null;
        }

        InputComponent input;
        if (enums != null) {
            UISelectOne ui = factory.createSelectOne(name, inputClazz);
            // the enums are comma separated
            List<String> enumValues = new ArrayList<>();
            String[] values = enums.split(",");
            for (String v : values) {
                enumValues.add(v.trim());
            }
            ui.setValueChoices(enumValues);
            if (defaultValue != null) {
                Object value = defaultValue;
                Converter converter = converterFactory.getConverter(String.class, inputClazz);
                if (converter != null) {
                    value = converter.convert(defaultValue);
                }
                ui.setDefaultValue(value);
            }
            if (currentValue != null) {
                Object value = currentValue;
                Converter converter = converterFactory.getConverter(String.class, inputClazz);
                if (converter != null) {
                    value = converter.convert(currentValue);
                }
                // set the value from the enum choices so the UI can indicate this correctly in the UI
                for (String v : enumValues) {
                    if (v.equalsIgnoreCase((String) value)) {
                        value = v;
                        break;
                    }
                }
                ui.setValue(value);
            }

            if ("true".equals(required) || promptInInteractiveMode) {
                // This will always prompt, regardless if there is a value set
                Iterator it = ui.getFacets().iterator();
                while (it.hasNext()) {
                    Object facet = it.next();
                    if (facet instanceof HintsFacet) {
                        ((HintsFacet) facet).setPromptInInteractiveMode(true);
                    }
                }
            }

            input = ui;
        } else {
            UIInput ui = factory.createInput(name, inputClazz);
            if (defaultValue != null) {
                Object value = defaultValue;
                Converter converter = converterFactory.getConverter(String.class, inputClazz);
                if (converter != null) {
                    value = converter.convert(defaultValue);
                }
                ui.setDefaultValue(value);
            }
            if (currentValue != null) {
                Object value = currentValue;
                Converter converter = converterFactory.getConverter(String.class, inputClazz);
                if (converter != null) {
                    value = converter.convert(currentValue);
                }
                ui.setValue(value);
            }

            if ("true".equals(required) || promptInInteractiveMode) {
                // This will always prompt, regardless if there is a value set
                Iterator it = ui.getFacets().iterator();
                while (it.hasNext()) {
                    Object facet = it.next();
                    if (facet instanceof HintsFacet) {
                        ((HintsFacet) facet).setPromptInInteractiveMode(true);
                    }
                }
            }

            input = ui;
        }

        if (Objects.equals("true", required)) {
            input.setRequired(true);
        }

        // if the name is "expression" then its a placeholder for the parent name to be used instead as label
        String label;
        if (name.equals("expression") && parentName != null) {
            label = asTitleCase(parentName + "Language");
        } else if (name.startsWith("expression_") && parentName != null) {
            // the expression may have a number of extra inputs we need to show as well
            String namePostfix = name.substring(11);
            // upper case the first char
            namePostfix = Character.toTitleCase(namePostfix.charAt(0)) + namePostfix.substring(1);
            label = asTitleCase(parentName + namePostfix);
        } else {
            label = asTitleCase(name);
        }
        if (multiValue) {
            label += " (multivalued)";
        }
        input.setLabel(label);

        if (!provider.isGUI()) {
            // no description in CLI/embedded as that clutters the shell
            input.setDescription("");
        } else {
            if (multiValue) {
                String extra = "This option is multi valued, which means you can provide multiple key/value pairs"
                        + " prefixed with " + prefix + " and separated with &, eg " + prefix + "foo=123&" + prefix + "bar=456";
                if (description == null) {
                    description = extra;
                } else {
                    if (description.endsWith(".")) {
                        description += " " + extra;
                    } else {
                        description += ". " + extra;
                    }
                }
            }
            // must use an empty description otherwise the GUI prints null
            input.setDescription(description != null ? description : "");
        }

        return input;
    }
161715
private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) {
        try {
            final Class<?> type = Class.forName(fqcn);
            final Method method = type.getMethod(methodName);

            return method.invoke(null);
            // any exception is really unexpected since the type name has
            // already been verified
        } catch (final Exception e) {
            throw new InstantiationException(
                    String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e);
        }
    }