idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
30,700 | public static SanitizedContent serializeElement ( JsonElement element ) { Preconditions . checkArgument ( element instanceof JsonArray || element instanceof JsonObject || element instanceof JsonNull || element instanceof JsonPrimitive ) ; return ordainJson ( new Gson ( ) . toJson ( element ) ) ; } | Serializes a JsonElement to string . |
30,701 | public boolean isJustBefore ( SourceLocation that ) { if ( ! this . filePath . equals ( that . filePath ) ) { return false ; } return this . getEndLine ( ) == that . getBeginLine ( ) && this . getEndColumn ( ) + 1 == that . getBeginColumn ( ) ; } | Returns true if this location ends one character before the other location starts . |
30,702 | public final String getStatementsForInsertingIntoForeignCodeAtIndent ( int startingIndent ) { String code = getCode ( startingIndent ) ; return code . endsWith ( "\n" ) ? code : code + "\n" ; } | Returns a sequence of JavaScript statements suitable for inserting into JS code that is not managed by the CodeChunk DSL . The string is guaranteed to end in a newline . |
30,703 | public void addNode ( HtmlMatcherGraphNode node ) { checkNotNull ( node ) ; if ( graphCursor . isPresent ( ) ) { graphCursor . get ( ) . linkActiveEdgeToNode ( node ) ; } setGraphCursorNode ( node ) ; } | Attaches a new HTML tag node to the graph at the current cursor position . |
30,704 | public static void main ( String [ ] args ) { SoyFileSet sfs = SoyFileSet . builder ( ) . add ( Resources . getResource ( "simple.soy" ) ) . build ( ) ; SoyTofu tofu = sfs . compileToTofu ( ) ; writeExampleHeader ( ) ; System . out . println ( tofu . newRenderer ( "soy.examples.simple.helloWorld" ) . render ( ) ) ; SoyTofu simpleTofu = tofu . forNamespace ( "soy.examples.simple" ) ; writeExampleHeader ( ) ; System . out . println ( simpleTofu . newRenderer ( ".helloName" ) . setData ( ImmutableMap . of ( "name" , "Ana" ) ) . render ( ) ) ; writeExampleHeader ( ) ; System . out . println ( simpleTofu . newRenderer ( ".helloNames" ) . setData ( ImmutableMap . of ( "names" , ImmutableList . of ( "Bob" , "Cid" , "Dee" ) ) ) . render ( ) ) ; } | Prints the generated HTML to stdout . |
30,705 | private DelTemplateKey resolveVariantExpression ( ) { if ( delTemplateVariantExpr == null ) { delTemplateKey = DelTemplateKey . create ( delTemplateName , "" ) ; return delTemplateKey ; } ExprNode exprNode = delTemplateVariantExpr . getRoot ( ) ; if ( exprNode instanceof GlobalNode ) { GlobalNode globalNode = ( GlobalNode ) exprNode ; if ( globalNode . isResolved ( ) ) { exprNode = globalNode . getValue ( ) ; } else { return DelTemplateKey . create ( delTemplateName , globalNode . getName ( ) ) ; } } if ( exprNode instanceof IntegerNode ) { long variantValue = ( ( IntegerNode ) exprNode ) . getValue ( ) ; delTemplateKey = DelTemplateKey . create ( delTemplateName , String . valueOf ( variantValue ) ) ; } else if ( exprNode instanceof StringNode ) { delTemplateKey = DelTemplateKey . create ( delTemplateName , ( ( StringNode ) exprNode ) . getValue ( ) ) ; } else { delTemplateKey = DelTemplateKey . create ( delTemplateName , exprNode . toSourceString ( ) ) ; } return delTemplateKey ; } | Calculate a DeltemplateKey for the variant . |
30,706 | public String toSourceString ( ) { return "{namespace " + namespace . identifier ( ) + ( attrs . isEmpty ( ) ? "" : " " + Joiner . on ( ' ' ) . join ( attrs ) ) + "}\n" ; } | Returns an approximation of what the original source for this namespace looked like . |
30,707 | public static String toJsUnpackFunction ( Descriptor protoDescriptor ) { return Preconditions . checkNotNull ( PROTO_TO_JS_UNPACK_FN . get ( protoDescriptor . getFullName ( ) ) ) ; } | Returns the unpack function for converting safe protos to JS SanitizedContent . |
30,708 | private static String getFullTagText ( HtmlTagNode openTagNode ) { class Visitor implements NodeVisitor < Node , VisitDirective > { boolean isConstantContent = true ; public VisitDirective exec ( Node node ) { if ( node instanceof RawTextNode || node instanceof HtmlAttributeNode || node instanceof HtmlAttributeValueNode || node instanceof HtmlOpenTagNode || node instanceof HtmlCloseTagNode ) { return VisitDirective . CONTINUE ; } isConstantContent = false ; return VisitDirective . ABORT ; } } Visitor visitor = new Visitor ( ) ; SoyTreeUtils . visitAllNodes ( openTagNode , visitor ) ; if ( visitor . isConstantContent ) { return openTagNode . toSourceString ( ) ; } return null ; } | This method calculates a string that can be used to tell if two tags that were turned into placeholders are equivalent and thus could be turned into identical placeholders . |
30,709 | public static JsExpr genJsExprUsingSoySyntax ( Operator op , List < JsExpr > operandJsExprs ) { List < Expression > operands = Lists . transform ( operandJsExprs , input -> fromExpr ( input , ImmutableList . < GoogRequire > of ( ) ) ) ; return Expression . operation ( op , operands ) . assertExpr ( ) ; } | Generates a JS expression for the given operator and operands . |
30,710 | public static Type protoType ( Descriptor descriptor ) { return Type . getType ( 'L' + JavaQualifiedNames . getClassName ( descriptor ) . replace ( '.' , '/' ) + ';' ) ; } | Returns the runtime type for the message correspdoning to the given descriptor .. |
30,711 | public static List < SoyValueProvider > concatLists ( List < SoyList > args ) { ImmutableList . Builder < SoyValueProvider > flattened = ImmutableList . builder ( ) ; for ( SoyList soyList : args ) { flattened . addAll ( soyList . asJavaList ( ) ) ; } return flattened . build ( ) ; } | Concatenates its arguments . |
30,712 | public static String join ( SoyList list , String separator ) { List < String > stringList = new ArrayList < > ( ) ; for ( SoyValue value : list . asResolvedJavaList ( ) ) { stringList . add ( value . coerceToString ( ) ) ; } return Joiner . on ( separator ) . join ( stringList ) ; } | Joins the list elements by a separator . |
30,713 | public static List < SoyValue > keys ( SoyValue sv ) { SoyLegacyObjectMap map = ( SoyLegacyObjectMap ) sv ; List < SoyValue > list = new ArrayList < > ( map . getItemCnt ( ) ) ; Iterables . addAll ( list , map . getItemKeys ( ) ) ; return list ; } | Returns a list of all the keys in the given map . For the JavaSource variant while the function signature is ? instead of legacy_object_map . |
30,714 | public static NumberData max ( SoyValue arg0 , SoyValue arg1 ) { if ( arg0 instanceof IntegerData && arg1 instanceof IntegerData ) { return IntegerData . forValue ( Math . max ( arg0 . longValue ( ) , arg1 . longValue ( ) ) ) ; } else { return FloatData . forValue ( Math . max ( arg0 . numberValue ( ) , arg1 . numberValue ( ) ) ) ; } } | Returns the numeric maximum of the two arguments . |
30,715 | public static long round ( SoyValue value ) { if ( value instanceof IntegerData ) { return value . longValue ( ) ; } else { return Math . round ( value . numberValue ( ) ) ; } } | Rounds the given value to the closest integer . |
30,716 | public void setParamsToRuntimeCheck ( ImmutableMap < String , Predicate < String > > paramsToRuntimeCheck ) { checkState ( this . paramsToRuntimeCheckByDelegate == null ) ; this . paramsToRuntimeCheckByDelegate = checkNotNull ( paramsToRuntimeCheck ) ; } | Sets the params that require runtime type checking for each possible delegate target . |
30,717 | static BasicExpressionCompiler createBasicCompiler ( TemplateParameterLookup parameters , TemplateVariableManager varManager , ErrorReporter reporter , SoyTypeRegistry registry ) { return new BasicExpressionCompiler ( parameters , varManager , reporter , registry ) ; } | Create a basic compiler with trivial detaching logic . |
30,718 | SoyExpression compile ( ExprNode node , Label reattachPoint ) { return asBasicCompiler ( reattachPoint ) . compile ( node ) ; } | Compiles the given expression tree to a sequence of bytecode . |
30,719 | Optional < SoyExpression > compileWithNoDetaches ( ExprNode node ) { checkNotNull ( node ) ; if ( RequiresDetachVisitor . INSTANCE . exec ( node ) ) { return Optional . absent ( ) ; } Supplier < ExpressionDetacher > throwingSupplier = ( ) -> { throw new AssertionError ( ) ; } ; return Optional . of ( new CompilerVisitor ( parameters , varManager , throwingSupplier , reporter , registry ) . exec ( node ) ) ; } | Compiles the given expression tree to a sequence of bytecode if it can be done without generating any detach operations . |
30,720 | protected void visitPrintNode ( PrintNode node ) { TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor ( localVarExprs , pluginValueFactory , errorReporter ) ; PyExpr pyExpr = translator . exec ( node . getExpr ( ) ) ; for ( PrintDirectiveNode directiveNode : node . getChildren ( ) ) { SoyPrintDirective directive = directiveNode . getPrintDirective ( ) ; if ( ! ( directive instanceof SoyPySrcPrintDirective ) ) { errorReporter . report ( directiveNode . getSourceLocation ( ) , UNKNOWN_SOY_PY_SRC_PRINT_DIRECTIVE , directiveNode . getName ( ) ) ; continue ; } List < ExprRootNode > args = directiveNode . getArgs ( ) ; List < PyExpr > argsPyExprs = new ArrayList < > ( args . size ( ) ) ; for ( ExprRootNode arg : args ) { argsPyExprs . add ( translator . exec ( arg ) ) ; } pyExpr = ( ( SoyPySrcPrintDirective ) directive ) . applyForPySrc ( pyExpr , argsPyExprs ) ; } pyExprs . add ( pyExpr ) ; } | Visiting a print node accomplishes 3 basic tasks . It loads data it performs any operations needed and it executes the appropriate print directives . |
30,721 | protected void visitIfNode ( IfNode node ) { GenPyExprsVisitor genPyExprsVisitor = genPyExprsVisitorFactory . create ( localVarExprs , errorReporter ) ; TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor ( localVarExprs , pluginValueFactory , errorReporter ) ; StringBuilder pyExprTextSb = new StringBuilder ( ) ; boolean hasElse = false ; int pendingParens = 0 ; for ( SoyNode child : node . getChildren ( ) ) { if ( child instanceof IfCondNode ) { IfCondNode icn = ( IfCondNode ) child ; PyExpr condBlock = PyExprUtils . concatPyExprs ( genPyExprsVisitor . exec ( icn ) ) . toPyString ( ) ; condBlock = PyExprUtils . maybeProtect ( condBlock , PyExprUtils . pyPrecedenceForOperator ( Operator . CONDITIONAL ) ) ; pyExprTextSb . append ( "(" ) . append ( condBlock . getText ( ) ) ; PyExpr condPyExpr = translator . exec ( icn . getExpr ( ) ) ; pyExprTextSb . append ( ") if (" ) . append ( condPyExpr . getText ( ) ) . append ( ") else (" ) ; pendingParens ++ ; } else if ( child instanceof IfElseNode ) { hasElse = true ; IfElseNode ien = ( IfElseNode ) child ; PyExpr elseBlock = PyExprUtils . concatPyExprs ( genPyExprsVisitor . exec ( ien ) ) . toPyString ( ) ; pyExprTextSb . append ( elseBlock . getText ( ) ) . append ( ")" ) ; pendingParens -- ; } else { throw new AssertionError ( "Unexpected if child node type. Child: " + child ) ; } } if ( ! hasElse ) { pyExprTextSb . append ( "''" ) ; } for ( int i = 0 ; i < pendingParens ; i ++ ) { pyExprTextSb . append ( ")" ) ; } pyExprs . add ( new PyStringExpr ( pyExprTextSb . toString ( ) , PyExprUtils . pyPrecedenceForOperator ( Operator . CONDITIONAL ) ) ) ; } | If all the children are computable as expressions the IfNode can be written as a ternary conditional expression . |
30,722 | public HtmlAttributeNode getDirectAttributeNamed ( String attrName ) { for ( int i = 1 ; i < numChildren ( ) ; i ++ ) { StandaloneNode child = getChild ( i ) ; if ( child instanceof HtmlAttributeNode ) { HtmlAttributeNode attr = ( HtmlAttributeNode ) child ; if ( attr . definitelyMatchesAttributeName ( attrName ) ) { return attr ; } } } return null ; } | Returns an attribute with the given static name if it is a direct child . |
30,723 | private SoyList newListFromIterable ( Iterable < ? > items ) { ImmutableList . Builder < SoyValueProvider > builder = ImmutableList . builder ( ) ; for ( Object item : items ) { builder . add ( convertLazy ( item ) ) ; } return ListImpl . forProviderList ( builder . build ( ) ) ; } | Creates a SoyList from a Java Iterable . |
30,724 | public static MsgPartsAndIds buildMsgPartsAndComputeMsgIdForDualFormat ( MsgNode msgNode ) { if ( msgNode . isPlrselMsg ( ) ) { MsgPartsAndIds mpai = buildMsgPartsAndComputeMsgIds ( msgNode , true ) ; return new MsgPartsAndIds ( mpai . parts , mpai . idUsingBracedPhs , - 1L ) ; } else { return buildMsgPartsAndComputeMsgIds ( msgNode , false ) ; } } | Builds the list of SoyMsgParts and computes the unique message id for the given MsgNode assuming a specific dual format . |
30,725 | private static long computeMsgId ( MsgNode msgNode ) { return SoyMsgIdComputer . computeMsgId ( buildMsgParts ( msgNode ) , msgNode . getMeaning ( ) , msgNode . getContentType ( ) ) ; } | Computes the unique message id for the given MsgNode . |
30,726 | private static long computeMsgIdUsingBracedPhs ( MsgNode msgNode ) { return SoyMsgIdComputer . computeMsgIdUsingBracedPhs ( buildMsgParts ( msgNode ) , msgNode . getMeaning ( ) , msgNode . getContentType ( ) ) ; } | Computes the alternate unique id for this message . Only use this if you use braced placeholders . |
30,727 | private static ImmutableList < SoyMsgPart > buildMsgPartsForChildren ( MsgBlockNode parent , MsgNode msgNode ) { ImmutableList . Builder < SoyMsgPart > msgParts = ImmutableList . builder ( ) ; doBuildMsgPartsForChildren ( parent , msgNode , msgParts ) ; return msgParts . build ( ) ; } | Builds the list of SoyMsgParts for all the children of a given parent node . |
30,728 | private static SoyMsgPluralPart buildMsgPartForPlural ( MsgPluralNode msgPluralNode , MsgNode msgNode ) { ImmutableList . Builder < SoyMsgPart . Case < SoyMsgPluralCaseSpec > > pluralCases = ImmutableList . builder ( ) ; for ( CaseOrDefaultNode child : msgPluralNode . getChildren ( ) ) { ImmutableList < SoyMsgPart > caseMsgParts = buildMsgPartsForChildren ( ( MsgBlockNode ) child , msgNode ) ; SoyMsgPluralCaseSpec caseSpec ; if ( child instanceof MsgPluralCaseNode ) { caseSpec = new SoyMsgPluralCaseSpec ( ( ( MsgPluralCaseNode ) child ) . getCaseNumber ( ) ) ; } else if ( child instanceof MsgPluralDefaultNode ) { caseSpec = new SoyMsgPluralCaseSpec ( Type . OTHER ) ; } else { throw new AssertionError ( "Unidentified node under a plural node." ) ; } pluralCases . add ( SoyMsgPart . Case . create ( caseSpec , caseMsgParts ) ) ; } return new SoyMsgPluralPart ( msgNode . getPluralVarName ( msgPluralNode ) , msgPluralNode . getOffset ( ) , pluralCases . build ( ) ) ; } | Builds the list of SoyMsgParts for the given MsgPluralNode . |
30,729 | private static SoyMsgSelectPart buildMsgPartForSelect ( MsgSelectNode msgSelectNode , MsgNode msgNode ) { ImmutableList . Builder < SoyMsgPart . Case < String > > selectCases = ImmutableList . builder ( ) ; for ( CaseOrDefaultNode child : msgSelectNode . getChildren ( ) ) { ImmutableList < SoyMsgPart > caseMsgParts = buildMsgPartsForChildren ( ( MsgBlockNode ) child , msgNode ) ; String caseValue ; if ( child instanceof MsgSelectCaseNode ) { caseValue = ( ( MsgSelectCaseNode ) child ) . getCaseValue ( ) ; } else if ( child instanceof MsgSelectDefaultNode ) { caseValue = null ; } else { throw new AssertionError ( "Unidentified node under a select node." ) ; } selectCases . add ( SoyMsgPart . Case . create ( caseValue , caseMsgParts ) ) ; } return new SoyMsgSelectPart ( msgNode . getSelectVarName ( msgSelectNode ) , selectCases . build ( ) ) ; } | Builds the list of SoyMsgParts for the given MsgSelectNode . |
30,730 | public Expression gen ( CallNode callNode , TemplateAliases templateAliases , TranslationContext translationContext , ErrorReporter errorReporter , TranslateExprNodeVisitor exprTranslator ) { Expression callee = genCallee ( callNode , templateAliases , exprTranslator ) ; Expression objToPass = genObjToPass ( callNode , templateAliases , translationContext , errorReporter , exprTranslator ) ; Expression call = genMainCall ( callee , objToPass , callNode ) ; if ( callNode . getEscapingDirectives ( ) . isEmpty ( ) ) { return call ; } return applyEscapingDirectives ( call , callNode ) ; } | Generates the JS expression for a given call . |
30,731 | public Expression genObjToPass ( CallNode callNode , TemplateAliases templateAliases , TranslationContext translationContext , ErrorReporter errorReporter , TranslateExprNodeVisitor exprTranslator ) { Expression dataToPass ; if ( callNode . isPassingAllData ( ) ) { dataToPass = JsRuntime . OPT_DATA ; } else if ( callNode . isPassingData ( ) ) { dataToPass = exprTranslator . exec ( callNode . getDataExpr ( ) ) ; } else if ( callNode . numChildren ( ) == 0 ) { return LITERAL_NULL ; } else { dataToPass = LITERAL_NULL ; } Map < String , Expression > paramDefaults = getDefaultParams ( callNode , translationContext ) ; if ( callNode . numChildren ( ) == 0 ) { if ( ! paramDefaults . isEmpty ( ) ) { dataToPass = SOY_ASSIGN_DEFAULTS . call ( dataToPass , Expression . objectLiteral ( paramDefaults ) ) ; } return dataToPass . castAs ( "?" ) ; } Map < String , Expression > params = paramDefaults ; for ( CallParamNode child : callNode . getChildren ( ) ) { Expression value ; if ( child instanceof CallParamValueNode ) { CallParamValueNode cpvn = ( CallParamValueNode ) child ; value = exprTranslator . exec ( cpvn . getExpr ( ) ) ; } else { CallParamContentNode cpcn = ( CallParamContentNode ) child ; if ( isComputableAsJsExprsVisitor . exec ( cpcn ) ) { List < Expression > chunks = genJsExprsVisitorFactory . create ( translationContext , templateAliases , errorReporter ) . exec ( cpcn ) ; value = CodeChunkUtils . concatChunksForceString ( chunks ) ; } else { value = id ( "param" + cpcn . getId ( ) ) ; } value = maybeWrapContent ( translationContext . codeGenerator ( ) , cpcn , value ) ; } params . put ( child . getKey ( ) . identifier ( ) , value ) ; } Expression paramsExp = Expression . objectLiteral ( params ) ; if ( callNode . isPassingData ( ) ) { Expression allData = SOY_ASSIGN_DEFAULTS . call ( paramsExp , dataToPass ) ; return allData ; } else { return paramsExp . castAs ( "?" ) ; } } | Generates the JS expression for the object to pass in a given call . |
30,732 | protected Expression maybeWrapContent ( CodeChunk . Generator generator , CallParamContentNode node , Expression content ) { if ( node . getContentKind ( ) == null ) { return content ; } return sanitizedContentOrdainerFunctionForInternalBlocks ( node . getContentKind ( ) ) . call ( content ) ; } | If the param node had a content kind specified it was autoescaped in the corresponding context . Hence the result of evaluating the param block is wrapped in a SanitizedContent instance of the appropriate kind . |
30,733 | public SoyType getType ( String typeName ) { SoyType result = BUILTIN_TYPES . get ( typeName ) ; if ( result != null ) { return result ; } synchronized ( lock ) { result = protoTypeCache . get ( typeName ) ; if ( result == null ) { GenericDescriptor descriptor = descriptors . get ( typeName ) ; if ( descriptor == null ) { return null ; } if ( descriptor instanceof EnumDescriptor ) { result = new SoyProtoEnumType ( ( EnumDescriptor ) descriptor ) ; } else { result = new SoyProtoType ( this , ( Descriptor ) descriptor , extensions . get ( typeName ) ) ; } protoTypeCache . put ( typeName , result ) ; } } return result ; } | Look up a type by name . Returns null if there is no such type . |
30,734 | public String findTypeWithMatchingNamespace ( String prefix ) { prefix = prefix + "." ; for ( String name : getAllSortedTypeNames ( ) ) { if ( name . startsWith ( prefix ) ) { return name ; } } return null ; } | Finds a type whose top - level namespace is a specified prefix or null if there are none . |
30,735 | public Iterable < String > getAllSortedTypeNames ( ) { synchronized ( lock ) { if ( lazyAllSortedTypeNames == null ) { lazyAllSortedTypeNames = Stream . concat ( BUILTIN_TYPES . keySet ( ) . stream ( ) , descriptors . keySet ( ) . stream ( ) ) . sorted ( ) . collect ( toImmutableList ( ) ) ; } return lazyAllSortedTypeNames ; } } | Gets all known types sorted alphabetically . |
30,736 | public SoyType getOrCreateUnionType ( Collection < SoyType > members ) { SoyType type = UnionType . of ( members ) ; if ( type . getKind ( ) == SoyType . Kind . UNION ) { type = unionTypes . intern ( ( UnionType ) type ) ; } return type ; } | Factory function which creates a union type given the member types . This folds identical union types together . |
30,737 | public static SoyMsgRawTextPart of ( String rawText ) { int utf8Length = Utf8 . encodedLength ( rawText ) ; if ( utf8Length < rawText . length ( ) * BYTES_PER_CHAR ) { return new Utf8SoyMsgRawTextPart ( rawText ) ; } else { return new CharArraySoyMsgRawTextPart ( rawText ) ; } } | Returns a SoyMsgRawTextPart representing the specified raw text string . |
30,738 | public boolean isPure ( ) { if ( soyFunction instanceof BuiltinFunction ) { return ( ( BuiltinFunction ) soyFunction ) . isPure ( ) ; } return soyFunction . getClass ( ) . isAnnotationPresent ( SoyPureFunction . class ) ; } | Whether or not this function is pure . |
30,739 | void addToOutputVar ( PyExpr pyExpr ) { boolean isList = pyExpr instanceof PyListExpr ; if ( isList && ! getOutputVarIsInited ( ) ) { appendLine ( getOutputVarName ( ) , " = " , pyExpr . getText ( ) ) ; } else { initOutputVarIfNecessary ( ) ; String function = isList ? ".extend(" : ".append(" ; appendLine ( getOutputVarName ( ) , function , pyExpr . getText ( ) , ")" ) ; } setOutputVarInited ( ) ; } | Add a single PyExpr object to the output variable . |
30,740 | PyStringExpr getOutputAsString ( ) { Preconditions . checkState ( getOutputVarName ( ) != null ) ; initOutputVarIfNecessary ( ) ; return new PyListExpr ( getOutputVarName ( ) , Integer . MAX_VALUE ) . toPyString ( ) ; } | Provide the output object as a string . Since we store all data in the output variables as a list for concatenation performance this step does the joining to convert the output into a String . |
30,741 | public List < ExprRootNode > getAndRemoveGenderExprs ( ) { List < ExprRootNode > genderExprs = this . genderExprs ; this . genderExprs = null ; return genderExprs ; } | Returns the list of expressions for gender values and sets that field to null . |
30,742 | public static ErrorReporter create ( Map < String , SoyFileSupplier > filePathsToSuppliers ) { return new ErrorReporterImpl ( ImmutableMap . copyOf ( filePathsToSuppliers ) ) ; } | Creates a new ErrorReporter which can create source snippets from the given files . |
30,743 | public static boolean equal ( SoyValue operand0 , SoyValue operand1 ) { if ( operand0 instanceof StringData || operand0 instanceof UnsanitizedString ) { return compareString ( operand0 . stringValue ( ) , operand1 ) ; } if ( operand1 instanceof StringData || operand1 instanceof UnsanitizedString ) { return compareString ( operand1 . stringValue ( ) , operand0 ) ; } return Objects . equals ( operand0 , operand1 ) ; } | Custom equality operator that smooths out differences between different Soy runtimes . |
30,744 | public Expression reference ( ) { if ( chunk ( ) instanceof VariableDeclaration ) { return id ( ( ( VariableDeclaration ) chunk ( ) ) . varName ( ) , ImmutableSet . of ( this ) ) ; } else { return dottedIdWithRequires ( symbol ( ) , ImmutableSet . of ( this ) ) ; } } | Returns a code chunk that can act as a reference to the required symbol . |
30,745 | public GoogRequire merge ( GoogRequire other ) { checkArgument ( other . symbol ( ) . equals ( symbol ( ) ) ) ; if ( other . equals ( this ) ) { return this ; } if ( ( other . chunk ( ) instanceof VariableDeclaration && chunk ( ) instanceof VariableDeclaration && ( ( VariableDeclaration ) chunk ( ) ) . varName ( ) . equals ( ( ( VariableDeclaration ) other . chunk ( ) ) . varName ( ) ) ) || ( ! ( chunk ( ) instanceof VariableReference ) && ! ( other . chunk ( ) instanceof VariableDeclaration ) ) ) { if ( other . isTypeRequire ( ) ) { return this ; } return other ; } throw new IllegalArgumentException ( "Found the same namespace added as a require in multiple incompatible ways: " + other + " vs. " + this ) ; } | For 2 goog requires with the same symbol . Return the perfered one . |
30,746 | private Expression incrementKeyForTemplate ( TemplateNode template ) { Holder < Integer > keyCounter = keyCounterStack . peek ( ) ; return JsRuntime . XID . call ( Expression . stringLiteral ( template . getTemplateName ( ) + "-" + keyCounter . value ++ ) ) ; } | Returns a unique key for the template . This has the side - effect of incrementing the current keyCounter at the top of the stack . |
30,747 | public void runWholeFilesetPasses ( SoyFileSetNode soyTree , TemplateRegistry templateRegistry ) { ImmutableList < SoyFileNode > sourceFiles = ImmutableList . copyOf ( soyTree . getChildren ( ) ) ; IdGenerator idGenerator = soyTree . getNodeIdGenerator ( ) ; for ( CompilerFileSetPass pass : crossTemplateCheckingPasses ) { CompilerFileSetPass . Result result = pass . run ( sourceFiles , idGenerator , templateRegistry ) ; if ( result == CompilerFileSetPass . Result . STOP ) { break ; } } } | Runs all the fileset passes including the autoescaper and optimization passes if configured . |
30,748 | protected void appendHeaderVarDecl ( ImmutableList < ? extends TemplateHeaderVarDefn > headerVars , StringBuilder sb ) { for ( TemplateHeaderVarDefn headerVar : headerVars ) { sb . append ( " {" ) . append ( getDeclName ( headerVar ) ) ; if ( ! headerVar . isRequired ( ) ) { sb . append ( "?" ) ; } sb . append ( " " ) . append ( headerVar . name ( ) ) . append ( ": " ) . append ( headerVar . hasType ( ) ? headerVar . type ( ) : headerVar . getTypeNode ( ) ) . append ( "}" ) ; if ( headerVar . desc ( ) != null ) { sb . append ( " /** " ) . append ( headerVar . desc ( ) ) . append ( " */" ) ; } sb . append ( "\n" ) ; } } | Add the Soy template syntax that declares headerVar to the string builder . |
30,749 | public StackTraceElement createStackTraceElement ( SourceLocation srcLocation ) { return new StackTraceElement ( soyFileHeaderInfo . namespace , partialTemplateName . substring ( 1 ) , srcLocation . getFileName ( ) , srcLocation . getBeginLine ( ) ) ; } | Construct a StackTraceElement that will point to the given source location of the current template . |
30,750 | protected void configure ( String [ ] args ) throws IOException { for ( String arg : args ) { if ( arg . startsWith ( "--input=" ) ) { FileRef ref = createInput ( ) ; ref . setPath ( arg . substring ( arg . indexOf ( '=' ) + 1 ) ) ; } else if ( arg . startsWith ( "--output=" ) ) { FileRef ref = createOutput ( ) ; ref . setPath ( arg . substring ( arg . indexOf ( '=' ) + 1 ) ) ; } else if ( arg . startsWith ( "--libdefined=" ) ) { FunctionNamePredicate libdefined = new FunctionNamePredicate ( ) ; libdefined . setPattern ( arg . substring ( arg . indexOf ( '=' ) + 1 ) ) ; addConfiguredLibdefined ( libdefined ) ; } else { throw new IllegalArgumentException ( arg ) ; } } } | Setup method to read arguments and setup initial configuration . |
30,751 | public void execute ( ) { super . execute ( ) ; if ( output == null ) { System . err . println ( "Please add an <output> for the <" + getTaskName ( ) + "> at " + this . getLocation ( ) ) ; return ; } StringBuilder sb = new StringBuilder ( ) ; for ( FileRef input : inputs ) { try { boolean inGeneratedCode = false ; for ( String line : Files . readLines ( input . file , Charsets . UTF_8 ) ) { if ( inGeneratedCode ) { if ( GENERATED_CODE_END_MARKER . equals ( line . trim ( ) ) ) { inGeneratedCode = false ; } } else if ( GENERATED_CODE_START_MARKER . equals ( line . trim ( ) ) ) { inGeneratedCode = true ; } else { sb . append ( line ) . append ( '\n' ) ; } } } catch ( IOException ex ) { System . err . println ( "Failed to read " + input . file ) ; ex . printStackTrace ( ) ; return ; } } generateCode ( availableIdentifiers , sb ) ; try { Files . asCharSink ( output . file , Charsets . UTF_8 ) . write ( sb ) ; } catch ( IOException ex ) { output . file . delete ( ) ; } } | Called to actually build the output by Ant . |
30,752 | protected void writeStringLiteral ( String value , StringBuilder out ) { out . append ( '\'' ) . append ( escapeOutputString ( value ) ) . append ( '\'' ) ; } | Appends a string literal with the given value onto the given buffer . |
30,753 | private void writeUnsafeStringLiteral ( char value , StringBuilder out ) { if ( ! isPrintable ( value ) ) { out . append ( String . format ( value >= 0x100 ? "'\\u%04x'" : "'\\x%02x'" , ( int ) value ) ) ; } else { out . append ( '\'' ) . append ( escapeOutputString ( String . valueOf ( value ) ) ) . append ( '\'' ) ; } } | Appends a string literal which may not be printable with the given value onto the given buffer . |
30,754 | public static Expression extensionField ( FieldDescriptor desc ) { String jsExtensionImport = ProtoUtils . getJsExtensionImport ( desc ) ; String jsExtensionName = ProtoUtils . getJsExtensionName ( desc ) ; return symbolWithNamespace ( jsExtensionImport , jsExtensionName ) ; } | Returns the field containing the extension object for the given field descriptor . |
30,755 | public static Expression protoToSanitizedContentConverterFunction ( Descriptor messageType ) { return GoogRequire . create ( NodeContentKinds . toJsUnpackFunction ( messageType ) ) . reference ( ) ; } | Returns a function that can unpack safe proto types into sanitized content types .. |
30,756 | public static Expression protoConstructor ( SoyProtoType type ) { return GoogRequire . create ( type . getNameForBackend ( SoyBackendKind . JS_SRC ) ) . reference ( ) ; } | Returns the constructor for the proto . |
30,757 | public static Expression sanitizedContentType ( SanitizedContentKind kind ) { return GoogRequire . create ( NodeContentKinds . toJsSanitizedContentCtorName ( kind ) ) . reference ( ) ; } | Returns the js type for the sanitized content object corresponding to the given ContentKind . |
30,758 | private static Expression symbolWithNamespace ( String requireSymbol , String fullyQualifiedSymbol ) { GoogRequire require = GoogRequire . create ( requireSymbol ) ; if ( fullyQualifiedSymbol . equals ( require . symbol ( ) ) ) { return require . reference ( ) ; } String ident = fullyQualifiedSymbol . substring ( require . symbol ( ) . length ( ) + 1 ) ; return require . dotAccess ( ident ) ; } | Returns a code chunk that accesses the given symbol . |
30,759 | private boolean areChildrenComputableAsJsExprs ( ParentSoyNode < ? > node ) { for ( SoyNode child : node . getChildren ( ) ) { if ( canSkipChild ( child ) ) { continue ; } if ( ! visit ( child ) ) { return false ; } } return true ; } | Private helper to check whether all children of a given parent node satisfy IsComputableAsJsExprsVisitor . |
30,760 | private ParseResult parseWithVersions ( ) throws IOException { List < TemplateMetadata > templateMetadatas = new ArrayList < > ( ) ; for ( CompilationUnitAndKind unit : compilationUnits ( ) ) { templateMetadatas . addAll ( TemplateMetadataSerializer . templatesFromCompilationUnit ( unit . compilationUnit ( ) , unit . fileKind ( ) , typeRegistry ( ) , unit . filePath ( ) , errorReporter ( ) ) ) ; } IdGenerator nodeIdGen = ( cache ( ) != null ) ? cache ( ) . getNodeIdGenerator ( ) : new IncrementingIdGenerator ( ) ; SoyFileSetNode soyTree = new SoyFileSetNode ( nodeIdGen . genId ( ) , nodeIdGen ) ; boolean filesWereSkipped = false ; synchronized ( nodeIdGen ) { for ( SoyFileSupplier fileSupplier : soyFileSuppliers ( ) . values ( ) ) { SoyFileSupplier . Version version = fileSupplier . getVersion ( ) ; VersionedFile cachedFile = cache ( ) != null ? cache ( ) . get ( fileSupplier . getFilePath ( ) , version ) : null ; SoyFileNode node ; if ( cachedFile == null ) { node = parseSoyFileHelper ( fileSupplier , nodeIdGen ) ; if ( node == null ) { filesWereSkipped = true ; continue ; } passManager ( ) . runSingleFilePasses ( node , nodeIdGen ) ; if ( cache ( ) != null ) { cache ( ) . put ( fileSupplier . getFilePath ( ) , VersionedFile . of ( node , version ) ) ; } } else { node = cachedFile . file ( ) ; } for ( TemplateNode template : node . getChildren ( ) ) { templateMetadatas . add ( TemplateMetadata . fromTemplate ( template ) ) ; } soyTree . addChild ( node ) ; } TemplateRegistry registry = new TemplateRegistry ( templateMetadatas , errorReporter ( ) ) ; if ( ! filesWereSkipped ) { passManager ( ) . runWholeFilesetPasses ( soyTree , registry ) ; } return ParseResult . create ( soyTree , registry ) ; } } | Parses a set of Soy files returning a structure containing the parse tree and template registry . |
30,761 | private boolean areChildrenComputableAsPyExprs ( ParentSoyNode < ? > node ) { for ( SoyNode child : node . getChildren ( ) ) { if ( ! ( child instanceof RawTextNode ) && ! ( child instanceof PrintNode ) ) { if ( ! visit ( child ) ) { return false ; } } } return true ; } | Private helper to check whether all SoyNode children of a given parent node satisfy IsComputableAsPyExprVisitor . ExprNode children are assumed to be computable as PyExprs . |
30,762 | public TypeInfo registerInnerClass ( String simpleName , int accessModifiers ) { classNames . claimName ( simpleName ) ; TypeInfo innerClass = outer . innerClass ( simpleName ) ; innerClassesAccessModifiers . put ( innerClass , accessModifiers ) ; return innerClass ; } | Register the given name as an inner class with the given access modifiers . |
30,763 | public void add ( ClassData classData ) { checkRegistered ( classData . type ( ) ) ; innerClasses . put ( classData . type ( ) , classData ) ; } | Adds the data for an inner class . |
30,764 | public void registerAsInnerClass ( ClassVisitor visitor , TypeInfo innerClass ) { checkRegistered ( innerClass ) ; doRegister ( visitor , innerClass ) ; } | Registers this factory as an inner class on the given class writer . |
30,765 | public void registerAllInnerClasses ( ClassVisitor visitor ) { for ( Map . Entry < TypeInfo , Integer > entry : innerClassesAccessModifiers . entrySet ( ) ) { TypeInfo innerClass = entry . getKey ( ) ; doRegister ( visitor , innerClass ) ; } } | Registers all inner classes to the given outer class . |
30,766 | public SoyMsgBundle compact ( SoyMsgBundle input ) { ImmutableList . Builder < SoyMsg > builder = ImmutableList . builder ( ) ; for ( SoyMsg msg : input ) { ImmutableList < SoyMsgPart > parts = compactParts ( msg . getParts ( ) ) ; builder . add ( SoyMsg . builder ( ) . setId ( msg . getId ( ) ) . setLocaleString ( msg . getLocaleString ( ) ) . setIsPlrselMsg ( MsgPartUtils . hasPlrselPart ( parts ) ) . setParts ( parts ) . build ( ) ) ; } return new RenderOnlySoyMsgBundleImpl ( input . getLocaleString ( ) , builder . build ( ) ) ; } | Returns a more memory - efficient version of the internal message bundle . |
30,767 | private ImmutableList < SoyMsgPart > compactParts ( ImmutableList < SoyMsgPart > parts ) { ImmutableList . Builder < SoyMsgPart > builder = ImmutableList . builder ( ) ; for ( SoyMsgPart part : parts ) { builder . add ( compactPart ( part ) ) ; } return builder . build ( ) ; } | Compacts a set of message parts . |
30,768 | private SoyMsgPart compactPart ( SoyMsgPart part ) { if ( part instanceof SoyMsgPluralPart ) { part = compactPlural ( ( SoyMsgPluralPart ) part ) ; } else if ( part instanceof SoyMsgSelectPart ) { part = compactSelect ( ( SoyMsgSelectPart ) part ) ; } else if ( part instanceof SoyMsgPlaceholderPart ) { part = compactPlaceholder ( ( SoyMsgPlaceholderPart ) part ) ; } return intern ( part ) ; } | Compacts a single message part . |
30,769 | public void claimName ( String name ) { checkName ( name ) ; if ( names . add ( name , 1 ) != 0 ) { names . remove ( name ) ; if ( reserved . contains ( name ) ) { throw new IllegalArgumentException ( "Tried to claim a reserved name: " + name ) ; } throw new IllegalArgumentException ( "Name: " + name + " was already claimed!" ) ; } } | Registers the name throwing an IllegalArgumentException if it has already been registered . |
30,770 | public void reserve ( String name ) { checkName ( name ) ; if ( reserved . add ( name ) ) { if ( ! names . add ( name ) ) { names . remove ( name ) ; throw new IllegalArgumentException ( "newly reserved name: " + name + " was already used!" ) ; } } } | Reserves the name useful for keywords . |
30,771 | public String generateName ( String name ) { checkName ( name ) ; names . add ( name ) ; int count = names . count ( name ) ; if ( count == 1 ) { return name ; } return name + collisionSeparator + ( count - 1 ) ; } | Returns a name based on the supplied one that is guaranteed to be unique among the names that have been returned by this method . |
30,772 | private static void addCodeToRequireCss ( JsDoc . Builder header , SoyFileNode soyFile ) { SortedSet < String > requiredCssNamespaces = new TreeSet < > ( ) ; requiredCssNamespaces . addAll ( soyFile . getRequiredCssNamespaces ( ) ) ; for ( TemplateNode template : soyFile . getChildren ( ) ) { requiredCssNamespaces . addAll ( template . getRequiredCssNamespaces ( ) ) ; } for ( String requiredCssNamespace : requiredCssNamespaces ) { header . addParameterizedAnnotation ( "requirecss" , requiredCssNamespace ) ; } } | Appends requirecss jsdoc tags in the file header section . |
30,773 | protected Statement generateFunctionBody ( TemplateNode node , String alias ) { ImmutableList . Builder < Statement > bodyStatements = ImmutableList . builder ( ) ; bodyStatements . add ( Statement . assign ( JsRuntime . OPT_IJ_DATA , id ( "opt_ijData_deprecated" ) . or ( JsRuntime . OPT_IJ_DATA , templateTranslationContext . codeGenerator ( ) ) . castAs ( "!soy.IjData" ) ) ) ; if ( node instanceof TemplateElementNode ) { TemplateElementNode elementNode = ( TemplateElementNode ) node ; for ( TemplateStateVar stateVar : elementNode . getStateVars ( ) ) { Expression expr = getExprTranslator ( ) . exec ( stateVar . defaultValue ( ) ) ; if ( ! stateVar . type ( ) . equals ( stateVar . defaultValue ( ) . getType ( ) ) ) { expr = expr . castAs ( JsType . forJsSrc ( stateVar . type ( ) ) . typeExpr ( ) ) ; } bodyStatements . add ( VariableDeclaration . builder ( stateVar . name ( ) ) . setRhs ( expr ) . build ( ) ) ; } } if ( new ShouldEnsureDataIsDefinedVisitor ( ) . exec ( node ) ) { bodyStatements . add ( assign ( OPT_DATA , OPT_DATA . or ( EMPTY_OBJECT_LITERAL , templateTranslationContext . codeGenerator ( ) ) ) ) ; } bodyStatements . add ( genParamTypeChecks ( node , alias ) ) ; SanitizedContentKind kind = node . getContentKind ( ) ; if ( isComputableAsJsExprsVisitor . exec ( node ) ) { List < Expression > templateBodyChunks = genJsExprsVisitor . exec ( node ) ; if ( kind == null ) { bodyStatements . add ( returnValue ( CodeChunkUtils . concatChunksForceString ( templateBodyChunks ) ) ) ; } else { bodyStatements . add ( returnValue ( sanitize ( CodeChunkUtils . concatChunks ( templateBodyChunks ) , kind ) ) ) ; } } else { jsCodeBuilder . pushOutputVar ( "output" ) ; Statement codeChunk = visitChildrenReturningCodeChunk ( node ) ; jsCodeBuilder . popOutputVar ( ) ; bodyStatements . add ( Statement . of ( codeChunk , returnValue ( sanitize ( id ( "output" ) , kind ) ) ) ) ; } return Statement . of ( bodyStatements . build ( ) ) ; } | Generates the function body . |
30,774 | private Expression coerceTypeForSwitchComparison ( ExprRootNode expr ) { Expression switchOn = translateExpr ( expr ) ; SoyType type = expr . getType ( ) ; if ( SoyTypes . makeNullable ( StringType . getInstance ( ) ) . isAssignableFrom ( type ) || type . equals ( AnyType . getInstance ( ) ) || type . equals ( UnknownType . getInstance ( ) ) ) { CodeChunk . Generator codeGenerator = templateTranslationContext . codeGenerator ( ) ; Expression tmp = codeGenerator . declarationBuilder ( ) . setRhs ( switchOn ) . build ( ) . ref ( ) ; return Expression . ifExpression ( GOOG_IS_OBJECT . call ( tmp ) , tmp . dotAccess ( "toString" ) . call ( ) ) . setElse ( tmp ) . build ( codeGenerator ) ; } return switchOn ; } | to strings . |
30,775 | private String genParamsRecordType ( TemplateNode node ) { Set < String > paramNames = new HashSet < > ( ) ; Map < String , String > record = new LinkedHashMap < > ( ) ; for ( TemplateParam param : node . getParams ( ) ) { JsType jsType = getJsTypeForParamForDeclaration ( param . type ( ) ) ; record . put ( param . name ( ) , jsType . typeExprForRecordMember ( ! param . isRequired ( ) ) ) ; for ( GoogRequire require : jsType . getGoogRequires ( ) ) { jsCodeBuilder . addGoogRequire ( require ) ; } paramNames . add ( param . name ( ) ) ; } IndirectParamsInfo ipi = new IndirectParamsCalculator ( templateRegistry ) . calculateIndirectParams ( templateRegistry . getMetadata ( node ) ) ; if ( ! ipi . mayHaveIndirectParamsInExternalCalls && ! ipi . mayHaveIndirectParamsInExternalDelCalls ) { for ( String indirectParamName : ipi . indirectParamTypes . keySet ( ) ) { if ( paramNames . contains ( indirectParamName ) ) { continue ; } Collection < SoyType > paramTypes = ipi . indirectParamTypes . get ( indirectParamName ) ; SoyType combinedType = SoyTypes . computeLowestCommonType ( typeRegistry , paramTypes ) ; SoyType indirectParamType = typeRegistry . getOrCreateUnionType ( combinedType , NullType . getInstance ( ) ) ; JsType jsType = getJsTypeForParamForDeclaration ( indirectParamType ) ; record . put ( indirectParamName , jsType . typeExprForRecordMember ( true ) ) ; } } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "{\n * " ) ; Joiner . on ( ",\n * " ) . withKeyValueSeparator ( ": " ) . appendTo ( sb , record ) ; sb . append ( ",\n * }" ) ; return sb . toString ( ) ; } | Generate the JSDoc for the opt_data parameter . |
30,776 | protected Statement genParamTypeChecks ( TemplateNode node , String alias ) { ImmutableList . Builder < Statement > declarations = ImmutableList . builder ( ) ; for ( TemplateParam param : node . getAllParams ( ) ) { String paramName = param . name ( ) ; SoyType paramType = param . type ( ) ; CodeChunk . Generator generator = templateTranslationContext . codeGenerator ( ) ; Expression paramChunk = genCodeForParamAccess ( paramName , param ) ; JsType jsType = getJsTypeForParamTypeCheck ( paramType ) ; String paramAlias = genParamAlias ( paramName ) ; Expression coerced = jsType . getValueCoercion ( paramChunk , generator ) ; if ( coerced != null ) { paramChunk = generator . declarationBuilder ( ) . setRhs ( coerced ) . build ( ) . ref ( ) ; } if ( param . hasDefault ( ) ) { if ( coerced == null ) { paramChunk = generator . declarationBuilder ( ) . setRhs ( paramChunk ) . build ( ) . ref ( ) ; } declarations . add ( genParamDefault ( param , paramChunk , alias , jsType , true ) ) ; } Expression value ; Optional < Expression > soyTypeAssertion = jsType . getSoyTypeAssertion ( paramChunk , paramName , generator ) ; if ( soyTypeAssertion . isPresent ( ) ) { value = soyTypeAssertion . get ( ) ; } else { value = paramChunk ; } VariableDeclaration . Builder declarationBuilder = VariableDeclaration . builder ( paramAlias ) . setRhs ( value ) . setGoogRequires ( jsType . getGoogRequires ( ) ) ; declarationBuilder . setJsDoc ( JsDoc . builder ( ) . addParameterizedAnnotation ( "type" , getJsTypeForParamForDeclaration ( paramType ) . typeExpr ( ) ) . build ( ) ) ; VariableDeclaration declaration = declarationBuilder . build ( ) ; declarations . add ( declaration ) ; templateTranslationContext . soyToJsVariableMappings ( ) . put ( paramName , id ( paramAlias ) ) ; } return Statement . of ( declarations . build ( ) ) ; } | Generate code to verify the runtime types of the input params . Also typecasts the input parameters and assigns them to local variables for use in the template . |
30,777 | public static PluginResolver nullResolver ( Mode mode , ErrorReporter reporter ) { return new PluginResolver ( mode , ImmutableMap . of ( ) , ImmutableMap . of ( ) , ImmutableMap . of ( ) , reporter ) ; } | Returns an empty resolver . Useful for tests or situations where it is known that no plugins will be needed . |
30,778 | public SoyPrintDirective lookupPrintDirective ( String name , int numArgs , SourceLocation location ) { SoyPrintDirective soyPrintDirective = printDirectives . get ( name ) ; if ( soyPrintDirective == null ) { reportMissing ( location , "print directive" , name , printDirectives . keySet ( ) ) ; soyPrintDirective = createPlaceholderPrintDirective ( name , numArgs ) ; } checkNumArgs ( "print directive" , soyPrintDirective . getValidArgsSizes ( ) , numArgs , location ) ; warnIfDeprecated ( name , soyPrintDirective , location ) ; return soyPrintDirective ; } | Returns a print directive with the given name and arity . |
30,779 | public Object lookupSoyFunction ( String name , int numArgs , SourceLocation location ) { Object soyFunction = functions . get ( name ) ; if ( soyFunction == null ) { reportMissing ( location , "function" , name , functions . keySet ( ) ) ; return ERROR_PLACEHOLDER_FUNCTION ; } Set < Integer > validArgsSize ; if ( soyFunction instanceof SoyFunction ) { validArgsSize = ( ( SoyFunction ) soyFunction ) . getValidArgsSizes ( ) ; } else { validArgsSize = getValidArgsSizes ( soyFunction . getClass ( ) . getAnnotation ( SoyFunctionSignature . class ) . value ( ) ) ; } checkNumArgs ( "function" , validArgsSize , numArgs , location ) ; warnIfDeprecated ( name , soyFunction , location ) ; return soyFunction ; } | Returns a function with the given name and arity . |
30,780 | public void setPrintDirective ( SoyPrintDirective printDirective ) { checkState ( this . printDirective == null , "setPrintDirective has already been called" ) ; checkArgument ( name . identifier ( ) . equals ( printDirective . getName ( ) ) ) ; this . printDirective = checkNotNull ( printDirective ) ; } | Sets the print directive . |
30,781 | LocalVariableStack addVariable ( String name , PyExpr varExpression ) { Preconditions . checkState ( ! localVarExprs . isEmpty ( ) ) ; localVarExprs . peek ( ) . put ( name , varExpression ) ; return this ; } | Adds a variable to the current reference frame . |
30,782 | public Context derive ( HtmlContext state ) { return state == this . state ? this : toBuilder ( ) . withState ( state ) . build ( ) ; } | Returns a context that differs only in the state . |
30,783 | public Context derive ( JsFollowingSlash slashType ) { return slashType == this . slashType ? this : toBuilder ( ) . withSlashType ( slashType ) . build ( ) ; } | Returns a context that differs only in the following slash . |
30,784 | public Context derive ( UriPart uriPart ) { return uriPart == this . uriPart ? this : toBuilder ( ) . withUriPart ( uriPart ) . build ( ) ; } | Returns a context that differs only in the uri part . |
30,785 | public Context derive ( HtmlHtmlAttributePosition htmlHtmlAttributePosition ) { return htmlHtmlAttributePosition == this . htmlHtmlAttributePosition ? this : toBuilder ( ) . withHtmlHtmlAttributePosition ( htmlHtmlAttributePosition ) . build ( ) ; } | Returns a context that differs only in the HTML attribute containing HTML position . |
30,786 | public Context getContextAfterDynamicValue ( ) { if ( state == HtmlContext . JS ) { switch ( slashType ) { case DIV_OP : case UNKNOWN : return this ; case REGEX : return derive ( JsFollowingSlash . DIV_OP ) ; case NONE : throw new IllegalStateException ( slashType . name ( ) ) ; } } else if ( state == HtmlContext . HTML_BEFORE_OPEN_TAG_NAME || state == HtmlContext . HTML_BEFORE_CLOSE_TAG_NAME ) { return toBuilder ( ) . withState ( HtmlContext . HTML_TAG_NAME ) . withElType ( ElementType . NORMAL ) . build ( ) ; } else if ( state == HtmlContext . HTML_TAG ) { return toBuilder ( ) . withState ( HtmlContext . HTML_ATTRIBUTE_NAME ) . withAttrType ( AttributeType . PLAIN_TEXT ) . build ( ) ; } else if ( uriPart == UriPart . START ) { if ( uriType == UriType . TRUSTED_RESOURCE ) { return derive ( UriPart . AUTHORITY_OR_PATH ) ; } return derive ( UriPart . MAYBE_VARIABLE_SCHEME ) ; } return this ; } | The context after printing a correctly - escaped dynamic value in this context . |
30,787 | static Context computeContextAfterAttributeDelimiter ( ElementType elType , AttributeType attrType , AttributeEndDelimiter delim , UriType uriType , int templateNestDepth ) { HtmlContext state ; JsFollowingSlash slash = JsFollowingSlash . NONE ; UriPart uriPart = UriPart . NONE ; switch ( attrType ) { case PLAIN_TEXT : state = HtmlContext . HTML_NORMAL_ATTR_VALUE ; break ; case SCRIPT : state = HtmlContext . JS ; slash = JsFollowingSlash . REGEX ; break ; case STYLE : state = HtmlContext . CSS ; break ; case HTML : state = HtmlContext . HTML_HTML_ATTR_VALUE ; break ; case META_REFRESH_CONTENT : state = HtmlContext . HTML_META_REFRESH_CONTENT ; break ; case URI : state = HtmlContext . URI ; uriPart = UriPart . START ; break ; default : throw new AssertionError ( "Unexpected attribute type " + attrType ) ; } Preconditions . checkArgument ( ( uriType != UriType . NONE ) == ( attrType == AttributeType . URI ) , "uriType=%s but attrType=%s" , uriType , attrType ) ; return new Context ( state , elType , attrType , delim , slash , uriPart , uriType , HtmlHtmlAttributePosition . NONE , templateNestDepth , 0 ) ; } | Computes the context after an attribute delimiter is seen . |
30,788 | Optional < MsgEscapingStrategy > getMsgEscapingStrategy ( SoyNode node ) { switch ( state ) { case HTML_PCDATA : return Optional . of ( new MsgEscapingStrategy ( this , ImmutableList . of ( ) ) ) ; case CSS_DQ_STRING : case CSS_SQ_STRING : case JS_DQ_STRING : case JS_SQ_STRING : case TEXT : case URI : if ( state == HtmlContext . URI && uriPart != UriPart . QUERY ) { return Optional . absent ( ) ; } return Optional . of ( new MsgEscapingStrategy ( new Context ( HtmlContext . TEXT ) , getEscapingModes ( node , ImmutableList . of ( ) ) ) ) ; case HTML_RCDATA : case HTML_NORMAL_ATTR_VALUE : case HTML_COMMENT : return Optional . of ( new MsgEscapingStrategy ( this , ImmutableList . of ( EscapingMode . NORMALIZE_HTML ) ) ) ; default : return Optional . absent ( ) ; } } | Determines the strategy to escape Soy msg tags . |
30,789 | public boolean isCompatibleWith ( EscapingMode mode ) { if ( mode == EscapingMode . ESCAPE_JS_VALUE ) { switch ( state ) { case JS_SQ_STRING : case JS_DQ_STRING : case CSS_SQ_STRING : case CSS_DQ_STRING : return false ; default : return true ; } } else if ( mode == EscapingMode . TEXT ) { return state == HtmlContext . TEXT ; } else if ( delimType == AttributeEndDelimiter . SPACE_OR_TAG_END ) { if ( mode == EscapingMode . ESCAPE_HTML || mode == EscapingMode . ESCAPE_HTML_ATTRIBUTE || mode == EscapingMode . ESCAPE_HTML_RCDATA ) { return false ; } } return true ; } | True if the given escaping mode could make sense in this context . |
30,790 | public int packedBits ( ) { int bits = templateNestDepth ; bits = ( bits << N_URI_TYPE_BITS ) | uriType . ordinal ( ) ; bits = ( bits << N_URI_PART_BITS ) | uriPart . ordinal ( ) ; bits = ( bits << N_JS_SLASH_BITS ) | slashType . ordinal ( ) ; bits = ( bits << N_DELIM_BITS ) | delimType . ordinal ( ) ; bits = ( bits << N_ATTR_BITS ) | attrType . ordinal ( ) ; bits = ( bits << N_ELEMENT_BITS ) | elType . ordinal ( ) ; bits = ( bits << N_STATE_BITS ) | state . ordinal ( ) ; return bits ; } | An integer form that uniquely identifies this context . This form is not guaranteed to be stable across versions so do not use as a long - lived serialized form . |
30,791 | private static UriPart unionUriParts ( UriPart a , UriPart b ) { Preconditions . checkArgument ( a != b ) ; if ( a == UriPart . DANGEROUS_SCHEME || b == UriPart . DANGEROUS_SCHEME ) { return UriPart . DANGEROUS_SCHEME ; } else if ( a == UriPart . FRAGMENT || b == UriPart . FRAGMENT || a == UriPart . UNKNOWN || b == UriPart . UNKNOWN ) { return UriPart . UNKNOWN ; } else if ( ( a == UriPart . MAYBE_VARIABLE_SCHEME || b == UriPart . MAYBE_VARIABLE_SCHEME ) && a != UriPart . UNKNOWN_PRE_FRAGMENT && b != UriPart . UNKNOWN_PRE_FRAGMENT ) { return UriPart . MAYBE_VARIABLE_SCHEME ; } else { return UriPart . UNKNOWN_PRE_FRAGMENT ; } } | Determines the correct URI part if two branches are joined . |
30,792 | static Context parse ( String text ) { Queue < String > parts = Lists . newLinkedList ( Arrays . asList ( text . split ( " " ) ) ) ; Context . Builder builder = HTML_PCDATA . toBuilder ( ) ; builder . withState ( HtmlContext . valueOf ( parts . remove ( ) ) ) ; if ( ! parts . isEmpty ( ) ) { try { builder . withElType ( ElementType . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { } } if ( ! parts . isEmpty ( ) ) { try { builder . withAttrType ( AttributeType . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { } } if ( ! parts . isEmpty ( ) ) { try { builder . withDelimType ( AttributeEndDelimiter . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { } } if ( ! parts . isEmpty ( ) ) { try { builder . withSlashType ( JsFollowingSlash . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { } } if ( ! parts . isEmpty ( ) ) { try { builder . withUriPart ( UriPart . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { } } if ( ! parts . isEmpty ( ) ) { try { builder . withUriType ( UriType . valueOf ( parts . element ( ) ) ) ; parts . remove ( ) ; } catch ( IllegalArgumentException ex ) { } } if ( ! parts . isEmpty ( ) ) { String part = parts . element ( ) ; String prefix = "templateNestDepth=" ; if ( part . startsWith ( prefix ) ) { try { builder . withTemplateNestDepth ( Integer . parseInt ( part . substring ( prefix . length ( ) ) ) ) ; parts . remove ( ) ; } catch ( NumberFormatException ex ) { } } } if ( ! parts . isEmpty ( ) ) { String part = parts . element ( ) ; String prefix = "jsTemplateLiteralNestDepth=" ; if ( part . startsWith ( prefix ) ) { try { builder . withJsTemplateLiteralNestDepth ( Integer . parseInt ( part . substring ( prefix . length ( ) ) ) ) ; parts . remove ( ) ; } catch ( NumberFormatException ex ) { } } } if ( ! parts . isEmpty ( ) ) { throw new IllegalArgumentException ( "Unable to parse context \"" + text + "\". Unparsed portion: " + parts ) ; } Context result = builder . build ( ) ; return result ; } | Parses a condensed string version of a context for use in tests . |
30,793 | public boolean isValidStartContextForContentKind ( SanitizedContentKind contentKind ) { if ( templateNestDepth != 0 ) { return false ; } switch ( contentKind ) { case ATTRIBUTES : return state == HtmlContext . HTML_ATTRIBUTE_NAME || state == HtmlContext . HTML_TAG ; default : return this . equals ( getStartContextForContentKind ( contentKind ) ) ; } } | Determines whether a particular context is valid at the start of a block of a particular content kind . |
30,794 | public boolean isValidStartContextForContentKindLoose ( SanitizedContentKind contentKind ) { switch ( contentKind ) { case URI : return state == HtmlContext . URI ; default : return isValidStartContextForContentKind ( contentKind ) ; } } | Determines whether a particular context is allowed for contextual to strict calls . |
30,795 | public SanitizedContentKind getMostAppropriateContentKind ( ) { SanitizedContentKind kind = STATE_TO_CONTENT_KIND . get ( state ) ; if ( kind != null && isValidStartContextForContentKindLoose ( kind ) ) { return kind ; } return SanitizedContentKind . TEXT ; } | Returns the most sensible content kind for a context . |
30,796 | public final boolean isValidEndContextForContentKind ( SanitizedContentKind contentKind ) { if ( templateNestDepth != 0 ) { return false ; } switch ( contentKind ) { case CSS : return state == HtmlContext . CSS && elType == ElementType . NONE ; case HTML : return state == HtmlContext . HTML_PCDATA && elType == ElementType . NONE ; case ATTRIBUTES : return state == HtmlContext . HTML_ATTRIBUTE_NAME || state == HtmlContext . HTML_TAG ; case JS : return state == HtmlContext . JS && elType == ElementType . NONE ; case URI : return state == HtmlContext . URI && uriType == UriType . NORMAL && uriPart != UriPart . START ; case TEXT : return state == HtmlContext . TEXT ; case TRUSTED_RESOURCE_URI : return state == HtmlContext . URI && uriType == UriType . TRUSTED_RESOURCE && uriPart != UriPart . START ; } throw new IllegalArgumentException ( "Specified content kind " + contentKind + " has no associated end context." ) ; } | Determines whether a particular context is valid for the end of a block of a particular content kind . |
30,797 | public final String getLikelyEndContextMismatchCause ( SanitizedContentKind contentKind ) { Preconditions . checkArgument ( ! isValidEndContextForContentKind ( contentKind ) ) ; if ( contentKind == SanitizedContentKind . ATTRIBUTES ) { return "an unterminated attribute value, or ending with an unquoted attribute" ; } switch ( state ) { case HTML_TAG_NAME : case HTML_TAG : case HTML_ATTRIBUTE_NAME : case HTML_NORMAL_ATTR_VALUE : return "an unterminated HTML tag or attribute" ; case CSS : return "an unclosed style block or attribute" ; case JS : case JS_LINE_COMMENT : return "an unclosed script block or attribute" ; case CSS_COMMENT : case HTML_COMMENT : case JS_BLOCK_COMMENT : return "an unterminated comment" ; case CSS_DQ_STRING : case CSS_SQ_STRING : case JS_DQ_STRING : case JS_SQ_STRING : return "an unterminated string literal" ; case URI : case CSS_URI : case CSS_DQ_URI : case CSS_SQ_URI : return "an unterminated or empty URI" ; case JS_REGEX : return "an unterminated regular expression" ; default : if ( templateNestDepth != 0 ) { return "an unterminated <template> element" ; } else { return "unknown to compiler" ; } } } | Returns a plausible human - readable description of a context mismatch ; |
30,798 | public void increaseIndent ( int numStops ) { indentLen += numStops * indentIncrementLen ; Preconditions . checkState ( 0 <= indentLen && indentLen <= MAX_INDENT_LEN ) ; indent = SPACES . substring ( 0 , indentLen ) ; } | Increases the indent by the given number of stops . |
30,799 | public IndentedLinesBuilder appendParts ( Object ... parts ) { for ( Object part : parts ) { sb . append ( part ) ; } return this ; } | Appends some parts to the current line . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.