idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
30,600 | public static Expression logicalNot ( final Expression baseExpr ) { baseExpr . checkAssignableTo ( Type . BOOLEAN_TYPE ) ; checkArgument ( baseExpr . resultType ( ) . equals ( Type . BOOLEAN_TYPE ) , "not a boolean expression" ) ; return new Expression ( Type . BOOLEAN_TYPE , baseExpr . features ( ) ) { @ Override protected void doGen ( CodeBuilder mv ) { baseExpr . gen ( mv ) ; // Surprisingly, java bytecode uses a branch (instead of 'xor 1' or something) to implement // this. This is most likely useful for allowing true to be represented by any non-zero // number. Label ifTrue = mv . newLabel ( ) ; Label end = mv . newLabel ( ) ; mv . ifZCmp ( Opcodes . IFNE , ifTrue ) ; // if not 0 goto ifTrue mv . pushBoolean ( true ) ; mv . goTo ( end ) ; mv . mark ( ifTrue ) ; mv . pushBoolean ( false ) ; mv . mark ( end ) ; } } ; } | Returns an expression that evaluates to the logical negation of the given boolean valued expression . | 254 | 17 |
30,601 | private static Expression doEqualsString ( SoyExpression stringExpr , SoyExpression other ) { // This is compatible with SharedRuntime.compareString, which interestingly makes == break // transitivity. See b/21461181 SoyRuntimeType otherRuntimeType = other . soyRuntimeType ( ) ; if ( otherRuntimeType . isKnownStringOrSanitizedContent ( ) ) { if ( stringExpr . isNonNullable ( ) ) { return stringExpr . invoke ( MethodRef . EQUALS , other . unboxAsString ( ) ) ; } else { return MethodRef . OBJECTS_EQUALS . invoke ( stringExpr , other . unboxAsString ( ) ) ; } } if ( otherRuntimeType . isKnownNumber ( ) && other . isNonNullable ( ) ) { // in this case, we actually try to convert stringExpr to a number return MethodRef . RUNTIME_STRING_EQUALS_AS_NUMBER . invoke ( stringExpr , other . coerceToDouble ( ) ) ; } // We don't know what other is, assume the worst and call out to our boxed implementation for // string comparisons. return MethodRef . RUNTIME_COMPARE_NULLABLE_STRING . invoke ( stringExpr , other . box ( ) ) ; } | Compare a string valued expression to another expression using soy == semantics . | 281 | 13 |
30,602 | public PyFunctionExprBuilder setUnpackedKwargs ( PyExpr mapping ) { if ( unpackedKwargs != null ) { throw new UnsupportedOperationException ( "Only one kwarg unpacking allowed per expression." ) ; } StringBuilder expr = new StringBuilder ( "**" ) ; if ( mapping . getPrecedence ( ) < Integer . MAX_VALUE ) { expr . append ( "(" ) . append ( mapping . getText ( ) ) . append ( ")" ) ; } else { expr . append ( mapping . getText ( ) ) ; } unpackedKwargs = expr . toString ( ) ; return this ; } | Unpacking keyword arguments will expand a dictionary into a series of keyword arguments . | 140 | 15 |
30,603 | public String build ( ) { StringBuilder sb = new StringBuilder ( funcName + "(" ) ; // Join args and kwargs into simple strings. String args = argList . stream ( ) . map ( PyExpr :: getText ) . filter ( Objects :: nonNull ) . collect ( Collectors . joining ( ", " ) ) ; String kwargs = kwargMap . entrySet ( ) . stream ( ) . map ( entry -> entry . getKey ( ) + "=" + entry . getValue ( ) . getText ( ) ) . filter ( Objects :: nonNull ) . collect ( Collectors . joining ( ", " ) ) ; // Strip empty strings. args = Strings . emptyToNull ( args ) ; kwargs = Strings . emptyToNull ( kwargs ) ; // Join all pieces together. Joiner . on ( ", " ) . skipNulls ( ) . appendTo ( sb , args , kwargs , unpackedKwargs ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } | Returns a valid Python function call as a String . | 231 | 10 |
30,604 | protected RenderVisitor createHelperInstance ( Appendable outputBuf , SoyRecord data ) { return new RenderVisitor ( evalVisitorFactory , outputBuf , basicTemplates , deltemplates , data , ijData , activeDelPackageSelector , msgBundle , xidRenamingMap , cssRenamingMap , debugSoyTemplateInfo , pluginInstances ) ; } | Creates a helper instance for rendering a subtemplate . | 83 | 11 |
30,605 | private void renderTemplate ( TemplateNode template , Predicate < String > paramsToTypeCheck ) { env = Environment . create ( template , data , ijData ) ; checkStrictParamTypes ( template , paramsToTypeCheck ) ; visitChildren ( template ) ; env = null ; // unpin for gc } | A private helper to render templates with optimized type checking . | 66 | 11 |
30,606 | private SoyValue eval ( ExprNode expr , SoyNode node ) { if ( expr == null ) { throw RenderException . create ( "Cannot evaluate expression in V1 syntax." ) . addStackTraceElement ( node ) ; } // Lazily initialize evalVisitor. if ( evalVisitor == null ) { evalVisitor = evalVisitorFactory . create ( env , cssRenamingMap , xidRenamingMap , msgBundle , debugSoyTemplateInfo , pluginInstances ) ; } try { return evalVisitor . exec ( expr ) ; } catch ( RenderException e ) { // RenderExceptions can be thrown when evaluating lazy transclusions. throw RenderException . createFromRenderException ( "When evaluating \"" + expr . toSourceString ( ) + "\": " + e . getMessage ( ) , e , node ) ; } catch ( Exception e ) { throw RenderException . createWithSource ( "When evaluating \"" + expr . toSourceString ( ) + "\": " + e . getMessage ( ) , e , node ) ; } } | Private helper to evaluate an expression . Always use this helper instead of using evalVisitor directly because this helper creates and throws a RenderException if there s an error . | 227 | 33 |
30,607 | static void append ( Appendable outputBuf , CharSequence cs ) { try { outputBuf . append ( cs ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Helper to append text to the output propagating any exceptions . | 46 | 12 |
30,608 | static void append ( Appendable outputBuf , SoyValue value , SoyNode node ) { try { value . render ( outputBuf ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( RenderException e ) { throw e . addStackTraceElement ( node ) ; } } | Helper to append a SoyValue to the output propagating any exceptions . | 69 | 14 |
30,609 | private SoyValue applyDirective ( SoyPrintDirective directive , SoyValue value , List < SoyValue > args , SoyNode node ) { // Get directive. if ( ! ( directive instanceof SoyJavaPrintDirective ) ) { throw RenderException . createWithSource ( "Failed to find Soy print directive with name '" + directive + "'" + " (tag " + node . toSourceString ( ) + ")" , node ) ; } // TODO: Add a pass to check num args at compile time. if ( ! directive . getValidArgsSizes ( ) . contains ( args . size ( ) ) ) { throw RenderException . createWithSource ( "Print directive '" + directive + "' used with the wrong number of arguments (tag " + node . toSourceString ( ) + ")." , node ) ; } try { return ( ( SoyJavaPrintDirective ) directive ) . applyForJava ( value , args ) ; } catch ( RuntimeException e ) { throw RenderException . createWithSource ( String . format ( "Failed in applying directive '%s' in tag \"%s\" due to exception: %s" , directive , node . toSourceString ( ) , e . getMessage ( ) ) , e , node ) ; } } | Protected helper to apply a print directive . | 267 | 9 |
30,610 | private void checkValueType ( TemplateParam param , SoyValue value , TemplateNode node ) { if ( ! TofuTypeChecks . isInstance ( param . type ( ) , value , node . getSourceLocation ( ) ) ) { // should this be a soydataexception? throw RenderException . createWithSource ( "Parameter type mismatch: attempt to bind value '" + ( value instanceof UndefinedData ? "(undefined)" : value ) + "' (a " + value . getClass ( ) . getSimpleName ( ) + ") to parameter '" + param . name ( ) + "' which has a declared type of '" + param . type ( ) + "'." , node ) ; } } | Check that the value matches the given param type . | 152 | 10 |
30,611 | public String getDescriptorExpression ( ) { // We only need to import the outermost descriptor. Descriptor descriptor = typeDescriptor ; while ( descriptor . getContainingType ( ) != null ) { descriptor = descriptor . getContainingType ( ) ; } return JavaQualifiedNames . getQualifiedName ( descriptor ) + ".getDescriptor()" ; } | For ParseInfo generation return a string that represents the Java source expression for the static descriptor constant . | 81 | 20 |
30,612 | public String getNameForBackend ( SoyBackendKind backend ) { switch ( backend ) { case JS_SRC : // The 'proto' prefix is JSPB-specific. If we ever support some other // JavaScript proto implementation, we'll need some way to determine which // proto implementation the user wants to use at this point. return ProtoUtils . calculateQualifiedJsName ( typeDescriptor ) ; case TOFU : case JBC_SRC : return JavaQualifiedNames . getClassName ( typeDescriptor ) ; case PYTHON_SRC : throw new UnsupportedOperationException ( ) ; } throw new AssertionError ( backend ) ; } | Returns this proto s type name for the given backend . | 145 | 11 |
30,613 | @ Override protected void visitHtmlAttributeNode ( HtmlAttributeNode node ) { // Skip attributes that do not have a value. if ( ! node . hasValue ( ) ) { return ; } SourceLocation insertionLocation = node . getSourceLocation ( ) ; for ( FunctionNode function : SoyTreeUtils . getAllNodesOfType ( node , FunctionNode . class ) ) { if ( ! ( function . getSoyFunction ( ) instanceof LoggingFunction ) ) { continue ; } FunctionNode funcNode = new FunctionNode ( Identifier . create ( VeLogJsSrcLoggingFunction . NAME , insertionLocation ) , VeLogJsSrcLoggingFunction . INSTANCE , insertionLocation ) ; funcNode . addChild ( new StringNode ( function . getFunctionName ( ) , QuoteStyle . SINGLE , insertionLocation ) ) ; funcNode . addChild ( new ListLiteralNode ( function . getChildren ( ) , insertionLocation ) ) ; StandaloneNode attributeName = node . getChild ( 0 ) ; if ( attributeName instanceof RawTextNode ) { // If attribute name is a plain text, directly pass it as a function argument. funcNode . addChild ( new StringNode ( ( ( RawTextNode ) attributeName ) . getRawText ( ) , QuoteStyle . SINGLE , insertionLocation ) ) ; } else { // Otherwise wrap the print node or call node into a let block, and use the let variable // as a function argument. String varName = "$soy_logging_function_attribute_" + node . getId ( ) ; LetContentNode letNode = LetContentNode . forVariable ( nodeIdGen . genId ( ) , attributeName . getSourceLocation ( ) , varName , attributeName . getSourceLocation ( ) , null ) ; // Adds a let var which references to the original attribute name, and move the name to // the let block. node . replaceChild ( attributeName , new PrintNode ( nodeIdGen . genId ( ) , insertionLocation , /* isImplicit= */ true , /* expr= */ new VarRefNode ( letNode . getVar ( ) . name ( ) , insertionLocation , letNode . getVar ( ) ) , /* attributes= */ ImmutableList . of ( ) , ErrorReporter . exploding ( ) ) ) ; letNode . addChild ( attributeName ) ; node . getParent ( ) . addChild ( node . getParent ( ) . getChildIndex ( node ) , letNode ) ; funcNode . addChild ( new VarRefNode ( letNode . getVar ( ) . name ( ) , insertionLocation , letNode . getVar ( ) ) ) ; } PrintNode loggingFunctionAttribute = new PrintNode ( nodeIdGen . genId ( ) , insertionLocation , /* isImplicit= */ true , /* expr= */ funcNode , /* attributes= */ ImmutableList . of ( ) , ErrorReporter . exploding ( ) ) ; // Append the logging function attribute to its parent int appendIndex = node . getParent ( ) . getChildIndex ( node ) + 1 ; node . getParent ( ) . addChild ( appendIndex , loggingFunctionAttribute ) ; // Replace the original attribute value to the placeholder. HtmlAttributeValueNode placeHolder = new HtmlAttributeValueNode ( nodeIdGen . genId ( ) , insertionLocation , Quotes . DOUBLE ) ; placeHolder . addChild ( new RawTextNode ( nodeIdGen . genId ( ) , ( ( LoggingFunction ) function . getSoyFunction ( ) ) . getPlaceholder ( ) , insertionLocation ) ) ; node . replaceChild ( node . getChild ( 1 ) , placeHolder ) ; // We can break here since VeLogValidationPass guarantees that there is exactly one // logging function in a html attribute value. break ; } visitChildrenAllowingConcurrentModification ( node ) ; } | For HtmlAttributeNode that has a logging function as its value replace the logging function with its place holder and append a new data attribute that contains all the desired information that are used later by the runtime library . | 828 | 42 |
30,614 | public static SanitizedContent ordainAsSafe ( String value , ContentKind kind ) { return ordainAsSafe ( value , kind , kind . getDefaultDir ( ) ) ; } | Faithfully assumes the provided value is safe and marks it not to be re - escaped . The value s direction is assumed to be LTR for JS URI ATTRIBUTES and CSS content and otherwise unknown . | 38 | 43 |
30,615 | private void findProtoTypesRecurse ( SoyType type , SortedSet < String > protoTypes ) { switch ( type . getKind ( ) ) { case PROTO : protoTypes . add ( ( ( SoyProtoType ) type ) . getDescriptorExpression ( ) ) ; break ; case PROTO_ENUM : protoTypes . add ( ( ( SoyProtoEnumType ) type ) . getDescriptorExpression ( ) ) ; break ; case UNION : for ( SoyType member : ( ( UnionType ) type ) . getMembers ( ) ) { findProtoTypesRecurse ( member , protoTypes ) ; } break ; case LIST : { ListType listType = ( ListType ) type ; findProtoTypesRecurse ( listType . getElementType ( ) , protoTypes ) ; break ; } case MAP : case LEGACY_OBJECT_MAP : { AbstractMapType mapType = ( AbstractMapType ) type ; findProtoTypesRecurse ( mapType . getKeyType ( ) , protoTypes ) ; findProtoTypesRecurse ( mapType . getValueType ( ) , protoTypes ) ; break ; } case RECORD : { RecordType recordType = ( RecordType ) type ; for ( SoyType fieldType : recordType . getMembers ( ) . values ( ) ) { findProtoTypesRecurse ( fieldType , protoTypes ) ; } break ; } case VE : { VeType veType = ( VeType ) type ; if ( veType . getDataType ( ) . isPresent ( ) ) { // Don't grab the proto type for ve<null> SoyType soyType = typeRegistry . getType ( veType . getDataType ( ) . get ( ) ) ; if ( soyType . getKind ( ) == Kind . PROTO ) { protoTypes . add ( ( ( SoyProtoType ) soyType ) . getDescriptorExpression ( ) ) ; } } break ; } case ANY : case UNKNOWN : case ERROR : case NULL : case BOOL : case INT : case FLOAT : case STRING : case HTML : case ATTRIBUTES : case JS : case CSS : case URI : case TRUSTED_RESOURCE_URI : case VE_DATA : // continue } } | Recursively search for protocol buffer types within the given type . | 487 | 13 |
30,616 | private static String buildTemplateNameForJavadoc ( SoyFileNode currSoyFile , TemplateMetadata template ) { StringBuilder resultSb = new StringBuilder ( ) ; if ( template . getSourceLocation ( ) . getFilePath ( ) . equals ( currSoyFile . getFilePath ( ) ) && template . getTemplateKind ( ) != TemplateMetadata . Kind . DELTEMPLATE ) { resultSb . append ( template . getTemplateName ( ) . substring ( template . getTemplateName ( ) . lastIndexOf ( ' ' ) ) ) ; } else { switch ( template . getTemplateKind ( ) ) { case BASIC : case ELEMENT : resultSb . append ( template . getTemplateName ( ) ) ; break ; case DELTEMPLATE : resultSb . append ( template . getDelTemplateName ( ) ) ; if ( ! template . getDelTemplateVariant ( ) . isEmpty ( ) ) { resultSb . append ( ' ' ) ; resultSb . append ( template . getDelTemplateVariant ( ) ) ; } break ; } } if ( template . getVisibility ( ) != Visibility . PUBLIC ) { resultSb . append ( " (private)" ) ; } if ( template . getTemplateKind ( ) == TemplateMetadata . Kind . DELTEMPLATE ) { resultSb . append ( " (delegate)" ) ; } return resultSb . toString ( ) ; } | Private helper to build the human - readable string for referring to a template in the generated code s javadoc . | 316 | 24 |
30,617 | private static void appendImmutableList ( IndentedLinesBuilder ilb , String typeParamSnippet , Collection < String > itemSnippets ) { appendListOrSetHelper ( ilb , "ImmutableList." + typeParamSnippet + "of" , itemSnippets ) ; } | Private helper to append an ImmutableList to the code . | 65 | 12 |
30,618 | private static void appendImmutableMap ( IndentedLinesBuilder ilb , String typeParamSnippet , Map < String , String > entrySnippetPairs ) { if ( entrySnippetPairs . isEmpty ( ) ) { ilb . appendLineStart ( "ImmutableMap." , typeParamSnippet , "of()" ) ; } else { ilb . appendLine ( "ImmutableMap." , typeParamSnippet , "builder()" ) ; for ( Map . Entry < String , String > entrySnippetPair : entrySnippetPairs . entrySet ( ) ) { ilb . appendLine ( " .put(" , entrySnippetPair . getKey ( ) , ", " , entrySnippetPair . getValue ( ) , ")" ) ; } ilb . appendLineStart ( " .build()" ) ; } } | Private helper to append an ImmutableMap to the code . | 193 | 12 |
30,619 | static Environment create ( TemplateNode template , SoyRecord data , SoyRecord ijData ) { return new Impl ( template , data , ijData ) ; } | The main way to create an environment . | 33 | 8 |
30,620 | public static Iterable < CrossLanguageStringXform > getAllEscapers ( ) { // This list is hard coded but is checked by unittests for the contextual auto-escaper. return ImmutableList . of ( EscapeHtml . INSTANCE , NormalizeHtml . INSTANCE , EscapeHtmlNospace . INSTANCE , NormalizeHtmlNospace . INSTANCE , EscapeJsString . INSTANCE , EscapeJsRegex . INSTANCE , EscapeCssString . INSTANCE , FilterCssValue . INSTANCE , EscapeUri . INSTANCE , NormalizeUri . INSTANCE , FilterNormalizeUri . INSTANCE , FilterNormalizeMediaUri . INSTANCE , FilterImageDataUri . INSTANCE , FilterSipUri . INSTANCE , FilterSmsUri . INSTANCE , FilterTelUri . INSTANCE , FilterHtmlAttributes . INSTANCE , FilterHtmlElementName . INSTANCE ) ; } | An accessor for all string transforms defined above . | 199 | 10 |
30,621 | public static Statement returnExpression ( final Expression expression ) { // TODO(lukes): it would be nice to do a checkType operation here to make sure that expression // is compatible with the return type of the method, but i don't know how to get that // information here (reasonably). So it is the caller's responsibility. return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { expression . gen ( adapter ) ; adapter . returnValue ( ) ; } } ; } | Generates a statement that returns the value produced by the given expression . | 107 | 14 |
30,622 | public static Statement throwExpression ( final Expression expression ) { expression . checkAssignableTo ( THROWABLE_TYPE ) ; return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { expression . gen ( adapter ) ; adapter . throwException ( ) ; } } ; } | Generates a statement that throws the throwable produced by the given expression . | 64 | 15 |
30,623 | public static Statement concat ( final Iterable < ? extends Statement > statements ) { checkNotNull ( statements ) ; return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { for ( Statement statement : statements ) { statement . gen ( adapter ) ; } } } ; } | Returns a statement that concatenates all the provided statements . | 63 | 12 |
30,624 | public final Statement labelStart ( final Label label ) { return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { adapter . mark ( label ) ; Statement . this . gen ( adapter ) ; } } ; } | Returns a new statement identical to this one but with the given label applied at the start of the statement . | 50 | 21 |
30,625 | final Expression then ( final Expression expression ) { return new Expression ( expression . resultType ( ) , expression . features ( ) ) { @ Override protected void doGen ( CodeBuilder adapter ) { Statement . this . gen ( adapter ) ; expression . gen ( adapter ) ; } } ; } | Returns an Expression that evaluates this statement followed by the given expression . | 60 | 13 |
30,626 | public Future < ? > future ( ) { Future < ? > f = future ; if ( f == null ) { throw new IllegalStateException ( "Result.future() can only be called if type() is DETACH, type was: " + type ) ; } return f ; } | Returns the future that soy is waiting for . | 59 | 9 |
30,627 | public void write ( T instance , ClassVisitor visitor ) { doWrite ( instance , visitor . visitAnnotation ( typeDescriptor , isRuntimeVisible ) ) ; } | Writes the given annotation to the visitor . | 37 | 9 |
30,628 | private static < T extends Annotation > FieldWriter annotationFieldWriter ( final String name , final AnnotationRef < T > ref ) { return new FieldWriter ( ) { @ Override public void write ( AnnotationVisitor visitor , Object value ) { ref . doWrite ( ref . annType . cast ( value ) , visitor . visitAnnotation ( name , ref . typeDescriptor ) ) ; } } ; } | Writes an annotation valued field to the writer . | 88 | 10 |
30,629 | private static FieldWriter simpleFieldWriter ( final String name ) { return new FieldWriter ( ) { @ Override public void write ( AnnotationVisitor visitor , Object value ) { visitor . visit ( name , value ) ; } } ; } | Writes an primitive valued field to the writer . | 50 | 10 |
30,630 | private static FieldWriter simpleArrayFieldWriter ( final String name ) { return new FieldWriter ( ) { @ Override public void write ( AnnotationVisitor visitor , Object value ) { int len = Array . getLength ( value ) ; AnnotationVisitor arrayVisitor = visitor . visitArray ( name ) ; for ( int i = 0 ; i < len ; i ++ ) { arrayVisitor . visit ( null , Array . get ( value , i ) ) ; } arrayVisitor . visitEnd ( ) ; } } ; } | Writes an simple array valued field to the annotation visitor . | 112 | 12 |
30,631 | private static < T extends Annotation > FieldWriter annotationArrayFieldWriter ( final String name , final AnnotationRef < T > ref ) { return new FieldWriter ( ) { @ Override public void write ( AnnotationVisitor visitor , Object value ) { int len = Array . getLength ( value ) ; AnnotationVisitor arrayVisitor = visitor . visitArray ( name ) ; for ( int i = 0 ; i < len ; i ++ ) { ref . doWrite ( ref . annType . cast ( Array . get ( value , i ) ) , arrayVisitor . visitAnnotation ( null , ref . typeDescriptor ) ) ; } arrayVisitor . visitEnd ( ) ; } } ; } | Writes an annotation array valued field to the annotation visitor . | 150 | 12 |
30,632 | public static LocalVariable createThisVar ( TypeInfo owner , Label start , Label end ) { return new LocalVariable ( "this" , owner . type ( ) , 0 , start , end , Feature . NON_NULLABLE ) ; } | parameters to tableEntry? | 49 | 6 |
30,633 | public void tableEntry ( CodeBuilder mv ) { mv . visitLocalVariable ( variableName ( ) , resultType ( ) . getDescriptor ( ) , null , // no generic signature start ( ) , end ( ) , index ( ) ) ; } | Write a local variable table entry for this variable . This informs debuggers about variable names types and lifetime . | 55 | 21 |
30,634 | private Statement store ( final Expression expr , final Optional < Label > firstVarInstruction ) { expr . checkAssignableTo ( resultType ( ) ) ; return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { expr . gen ( adapter ) ; if ( firstVarInstruction . isPresent ( ) ) { adapter . mark ( firstVarInstruction . get ( ) ) ; } adapter . visitVarInsn ( resultType ( ) . getOpcode ( Opcodes . ISTORE ) , index ( ) ) ; } } ; } | Writes the value at the top of the stack to the local variable . | 119 | 15 |
30,635 | public static SoyValue resolveSoyValueProvider ( SoyValueProvider provider ) { SoyValue value = provider . resolve ( ) ; return handleTofuNull ( value ) ; } | Helper function to translate NullData - > null when resolving a SoyValueProvider . | 37 | 16 |
30,636 | public static SoyString checkSoyString ( Object o ) { // if it isn't a sanitized content we don't want to warn and if it isn't a soystring we should // always fail. if ( o instanceof SoyString && o instanceof SanitizedContent && ( ( SanitizedContent ) o ) . getContentKind ( ) != ContentKind . TEXT && logger . isLoggable ( Level . WARNING ) ) { logger . log ( Level . WARNING , String . format ( "Passing in sanitized content into a template that accepts only string is forbidden. " + " Please modify the template to take in %s." , ( ( SanitizedContent ) o ) . getContentKind ( ) ) , new Exception ( ) ) ; } return ( SoyString ) o ; } | Casts the given type to SoyString or throws a ClassCastException . | 164 | 15 |
30,637 | public static SoyValue callLegacySoyFunction ( LegacyFunctionAdapter fnAdapter , List < SoyValue > args ) { for ( int i = 0 ; i < args . size ( ) ; i ++ ) { if ( args . get ( i ) == null ) { args . set ( i , NullData . INSTANCE ) ; } } return handleTofuNull ( fnAdapter . computeForJava ( args ) ) ; } | Helper function to translate null - > NullData when calling LegacyFunctionAdapters that may expect it . | 90 | 20 |
30,638 | public static SoyValue applyPrintDirective ( SoyJavaPrintDirective directive , SoyValue value , List < SoyValue > args ) { value = value == null ? NullData . INSTANCE : value ; for ( int i = 0 ; i < args . size ( ) ; i ++ ) { if ( args . get ( i ) == null ) { args . set ( i , NullData . INSTANCE ) ; } } return directive . applyForJava ( value , args ) ; } | Helper function to translate null - > NullData when calling SoyJavaPrintDirectives that may expect it . | 101 | 21 |
30,639 | public static CompiledTemplate applyEscapers ( CompiledTemplate delegate , ImmutableList < SoyJavaPrintDirective > directives ) { ContentKind kind = delegate . kind ( ) ; if ( canSkipEscaping ( directives , kind ) ) { return delegate ; } return new EscapedCompiledTemplate ( delegate , directives , kind ) ; } | Wraps a given template with a collection of escapers to apply . | 70 | 14 |
30,640 | PyStringExpr getPyExpr ( ) { if ( this . msgNode . isPlrselMsg ( ) ) { return this . msgNode . isPluralMsg ( ) ? pyFuncForPluralMsg ( ) : pyFuncForSelectMsg ( ) ; } else { return this . msgNode . isRawTextMsg ( ) ? pyFuncForRawTextMsg ( ) : pyFuncForGeneralMsg ( ) ; } } | Return the PyStringExpr for the render function call because we know render always return a string in Python runtime . | 96 | 23 |
30,641 | private Map < PyExpr , PyExpr > collectVarNameListAndToPyExprMap ( ) { Map < PyExpr , PyExpr > nodePyVarToPyExprMap = new LinkedHashMap <> ( ) ; for ( Map . Entry < String , MsgSubstUnitNode > entry : msgNode . getVarNameToRepNodeMap ( ) . entrySet ( ) ) { MsgSubstUnitNode substUnitNode = entry . getValue ( ) ; PyExpr substPyExpr = null ; if ( substUnitNode instanceof MsgPlaceholderNode ) { SoyNode phInitialNode = ( ( AbstractParentSoyNode < ? > ) substUnitNode ) . getChild ( 0 ) ; if ( phInitialNode instanceof PrintNode || phInitialNode instanceof CallNode || phInitialNode instanceof RawTextNode ) { substPyExpr = PyExprUtils . concatPyExprs ( genPyExprsVisitor . exec ( phInitialNode ) ) . toPyString ( ) ; } // when the placeholder is generated by HTML tags if ( phInitialNode instanceof MsgHtmlTagNode ) { substPyExpr = PyExprUtils . concatPyExprs ( genPyExprsVisitor . execOnChildren ( ( ParentSoyNode < ? > ) phInitialNode ) ) . toPyString ( ) ; } } else if ( substUnitNode instanceof MsgPluralNode ) { // Translates {@link MsgPluralNode#pluralExpr} into a Python lookup expression. // Note that {@code pluralExpr} represents the soy expression of the {@code plural} attr, // i.e. the {@code $numDrafts} in {@code {plural $numDrafts}...{/plural}}. substPyExpr = translateToPyExprVisitor . exec ( ( ( MsgPluralNode ) substUnitNode ) . getExpr ( ) ) ; } else if ( substUnitNode instanceof MsgSelectNode ) { substPyExpr = translateToPyExprVisitor . exec ( ( ( MsgSelectNode ) substUnitNode ) . getExpr ( ) ) ; } if ( substPyExpr != null ) { nodePyVarToPyExprMap . put ( new PyStringExpr ( "'" + entry . getKey ( ) + "'" ) , substPyExpr ) ; } } return nodePyVarToPyExprMap ; } | Private helper to process and collect all variables used within this msg node for code generation . | 545 | 17 |
30,642 | Expression genCodeForParamAccess ( String paramName , VarDefn varDefn ) { Expression source = OPT_DATA ; if ( varDefn . isInjected ( ) ) { // Special case for csp_nonce. It is created by the compiler itself, and users should not need // to set it. So, instead of generating opt_ij_data.csp_nonce, we generate opt_ij_data && // opt_ij_data.csp_nonce. // TODO(lukes): we only need to generate this logic if there aren't any other ij params if ( paramName . equals ( CSP_NONCE_VARIABLE_NAME ) ) { return OPT_IJ_DATA . and ( OPT_IJ_DATA . dotAccess ( paramName ) , codeGenerator ) ; } source = OPT_IJ_DATA ; } else if ( varDefn . kind ( ) == VarDefn . Kind . STATE ) { return genCodeForStateAccess ( paramName , ( TemplateStateVar ) varDefn ) ; } return source . dotAccess ( paramName ) ; } | Method that returns code to access a named parameter . | 241 | 10 |
30,643 | @ Override protected Expression visitVarRefNode ( VarRefNode node ) { Expression translation = variableMappings . maybeGet ( node . getName ( ) ) ; if ( translation != null ) { // Case 1: In-scope local var. return translation ; } else { // Case 2: Data reference. return genCodeForParamAccess ( node . getName ( ) , node . getDefnDecl ( ) ) ; } } | Implementations for data references . | 90 | 7 |
30,644 | NullSafeAccumulator dotAccess ( FieldAccess access , boolean nullSafe ) { if ( access instanceof ProtoCall ) { ProtoCall protoCall = ( ProtoCall ) access ; Expression maybeUnpack = protoCall . unpackFunction ( ) ; if ( maybeUnpack != null ) { Preconditions . checkState ( unpackFunction == null , "this chain will already unpack with %s" , unpackFunction ) ; unpackFunction = maybeUnpack ; accessType = protoCall . accessType ( ) ; } } chain . add ( access . toChainAccess ( nullSafe ) ) ; return this ; } | Extends the access chain with a dot access to the given value . | 130 | 14 |
30,645 | NullSafeAccumulator bracketAccess ( Expression arg , boolean nullSafe ) { chain . add ( new Bracket ( arg , nullSafe ) ) ; // With a bracket access we no longer need to unpack the entire list, just a singular object. accessType = AccessType . SINGULAR ; return this ; } | Extends the access chain with a bracket access to the given value . | 66 | 14 |
30,646 | Expression result ( CodeChunk . Generator codeGenerator ) { Expression accessChain = buildAccessChain ( base , codeGenerator , chain . iterator ( ) ) ; if ( unpackFunction == null ) { return accessChain ; } else { return accessType . unpackResult ( accessChain , unpackFunction ) ; } } | Returns a code chunk representing the entire access chain . Null - safe accesses in the chain generate code to make sure the chain is non - null before performing the access . | 69 | 34 |
30,647 | private static Expression buildAccessChain ( Expression base , CodeChunk . Generator generator , Iterator < ChainAccess > chain ) { if ( ! chain . hasNext ( ) ) { return base ; // base case } ChainAccess link = chain . next ( ) ; if ( link . nullSafe ) { if ( ! base . isCheap ( ) ) { base = generator . declarationBuilder ( ) . setRhs ( base ) . build ( ) . ref ( ) ; } return ifExpression ( base . doubleEqualsNull ( ) , LITERAL_NULL ) . setElse ( buildAccessChain ( link . extend ( base ) , generator , chain ) ) . build ( generator ) ; } return buildAccessChain ( link . extend ( base ) , generator , chain ) ; } | Builds the access chain . | 164 | 6 |
30,648 | public static boolean isRtlLanguage ( String locale ) { try { return UScript . isRightToLeft ( UCharacter . getPropertyValueEnum ( UProperty . SCRIPT , ULocale . addLikelySubtags ( new ULocale ( locale ) ) . getScript ( ) ) ) ; } catch ( IllegalArgumentException e ) { return false ; } } | Returns whether a locale given as a string in the ICU syntax is RTL . | 79 | 17 |
30,649 | public List < String > genJsSrc ( SoyFileSetNode soyTree , TemplateRegistry registry , SoyIncrementalDomSrcOptions options , ErrorReporter errorReporter ) { SoyJsSrcOptions incrementalJSSrcOptions = options . toJsSrcOptions ( ) ; BidiGlobalDir bidiGlobalDir = SoyBidiUtils . decodeBidiGlobalDirFromJsOptions ( incrementalJSSrcOptions . getBidiGlobalDir ( ) , incrementalJSSrcOptions . getUseGoogIsRtlForBidiGlobalDir ( ) ) ; try ( SoyScopedData . InScope inScope = apiCallScope . enter ( /* msgBundle= */ null , bidiGlobalDir ) ) { // Do the code generation. new HtmlContextVisitor ( ) . exec ( soyTree ) ; // If any errors are reported in {@code HtmlContextVisitor}, we should not continue. // Return an empty list here, {@code SoyFileSet} will throw an exception. if ( errorReporter . hasErrors ( ) ) { return Collections . emptyList ( ) ; } UnescapingVisitor . unescapeRawTextInHtml ( soyTree ) ; new RemoveUnnecessaryEscapingDirectives ( bidiGlobalDir ) . run ( soyTree ) ; // some of the above passes may slice up raw text nodes, recombine them. new CombineConsecutiveRawTextNodesPass ( ) . run ( soyTree ) ; return createVisitor ( incrementalJSSrcOptions , registry , typeRegistry , inScope . getBidiGlobalDir ( ) , errorReporter ) . gen ( soyTree , registry , errorReporter ) ; } } | Generates Incremental DOM JS source code given a Soy parse tree an options object and an optional bundle of translated messages . | 358 | 24 |
30,650 | public static SanitizedContent serializeObject ( Gson gson , Object obj ) { return ordainJson ( gson . toJson ( obj ) ) ; } | Generate sanitized js content with provided Gson serializer . | 36 | 13 |
30,651 | public static SanitizedContent serializeElement ( JsonElement element ) { // NOTE: Because JsonElement doesn't have any particular mechanism preventing random classes // from impersonating it, this low-tech check prevents at least obvious misuse. Preconditions . checkArgument ( element instanceof JsonArray || element instanceof JsonObject || element instanceof JsonNull || element instanceof JsonPrimitive ) ; // JsonPrimitive(String).toString() is broken, so use Gson which uses a consistent set of // flags to produce embeddable JSON. return ordainJson ( new Gson ( ) . toJson ( element ) ) ; } | Serializes a JsonElement to string . | 140 | 9 |
30,652 | 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 . | 68 | 14 |
30,653 | 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 . | 54 | 34 |
30,654 | 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 . | 61 | 16 |
30,655 | public static void main ( String [ ] args ) { // Compile the template. SoyFileSet sfs = SoyFileSet . builder ( ) . add ( Resources . getResource ( "simple.soy" ) ) . build ( ) ; SoyTofu tofu = sfs . compileToTofu ( ) ; // Example 1. writeExampleHeader ( ) ; System . out . println ( tofu . newRenderer ( "soy.examples.simple.helloWorld" ) . render ( ) ) ; // Create a namespaced tofu object to make calls more concise. SoyTofu simpleTofu = tofu . forNamespace ( "soy.examples.simple" ) ; // Example 2. writeExampleHeader ( ) ; System . out . println ( simpleTofu . newRenderer ( ".helloName" ) . setData ( ImmutableMap . of ( "name" , "Ana" ) ) . render ( ) ) ; // Example 3. writeExampleHeader ( ) ; System . out . println ( simpleTofu . newRenderer ( ".helloNames" ) . setData ( ImmutableMap . of ( "names" , ImmutableList . of ( "Bob" , "Cid" , "Dee" ) ) ) . render ( ) ) ; } | Prints the generated HTML to stdout . | 280 | 9 |
30,656 | 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 { // This global was not substituted. This happens when TemplateRegistries are built for // message extraction and parseinfo generation. To make this 'work' we just use the Global // name for the variant value. This is fine and will help catch some errors. // Because these nodes won't be used for code generation this should be safe. // For this reason we also don't store the key, instead we just return it. return DelTemplateKey . create ( delTemplateName , globalNode . getName ( ) ) ; } } if ( exprNode instanceof IntegerNode ) { // Globals were already substituted: We may now create the definitive variant and key fields // on this node. long variantValue = ( ( IntegerNode ) exprNode ) . getValue ( ) ; delTemplateKey = DelTemplateKey . create ( delTemplateName , String . valueOf ( variantValue ) ) ; } else if ( exprNode instanceof StringNode ) { // Globals were already substituted: We may now create the definitive variant and key fields // on this node. delTemplateKey = DelTemplateKey . create ( delTemplateName , ( ( StringNode ) exprNode ) . getValue ( ) ) ; } else { // We must have already reported an error, just create an arbitrary variant expr. delTemplateKey = DelTemplateKey . create ( delTemplateName , exprNode . toSourceString ( ) ) ; } return delTemplateKey ; } | Calculate a DeltemplateKey for the variant . | 408 | 13 |
30,657 | 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 . | 56 | 14 |
30,658 | 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 . | 56 | 16 |
30,659 | @ Nullable private static String getFullTagText ( HtmlTagNode openTagNode ) { class Visitor implements NodeVisitor < Node , VisitDirective > { boolean isConstantContent = true ; @ Override 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 ) { // toSourceString is lame, but how this worked before 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 . | 192 | 32 |
30,660 | 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 . | 94 | 13 |
30,661 | public static Type protoType ( Descriptor descriptor ) { return Type . getType ( ' ' + JavaQualifiedNames . getClassName ( descriptor ) . replace ( ' ' , ' ' ) + ' ' ) ; } | Returns the runtime type for the message correspdoning to the given descriptor .. | 47 | 16 |
30,662 | 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 . | 75 | 7 |
30,663 | 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 . | 79 | 10 |
30,664 | 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 . | 74 | 31 |
30,665 | 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 . | 97 | 9 |
30,666 | 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 . | 45 | 10 |
30,667 | 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 . | 64 | 15 |
30,668 | 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 . | 54 | 10 |
30,669 | SoyExpression compile ( ExprNode node , Label reattachPoint ) { return asBasicCompiler ( reattachPoint ) . compile ( node ) ; } | Compiles the given expression tree to a sequence of bytecode . | 34 | 13 |
30,670 | 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 . | 107 | 23 |
30,671 | @ Override protected void visitPrintNode ( PrintNode node ) { TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor ( localVarExprs , pluginValueFactory , errorReporter ) ; PyExpr pyExpr = translator . exec ( node . getExpr ( ) ) ; // Process directives. for ( PrintDirectiveNode directiveNode : node . getChildren ( ) ) { // Get directive. SoyPrintDirective directive = directiveNode . getPrintDirective ( ) ; if ( ! ( directive instanceof SoyPySrcPrintDirective ) ) { errorReporter . report ( directiveNode . getSourceLocation ( ) , UNKNOWN_SOY_PY_SRC_PRINT_DIRECTIVE , directiveNode . getName ( ) ) ; continue ; } // Get directive args. List < ExprRootNode > args = directiveNode . getArgs ( ) ; // Translate directive args. List < PyExpr > argsPyExprs = new ArrayList <> ( args . size ( ) ) ; for ( ExprRootNode arg : args ) { argsPyExprs . add ( translator . exec ( arg ) ) ; } // Apply directive. 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 . | 306 | 27 |
30,672 | @ Override protected void visitIfNode ( IfNode node ) { // Create another instance of this visitor for generating Python expressions from children. GenPyExprsVisitor genPyExprsVisitor = genPyExprsVisitorFactory . create ( localVarExprs , errorReporter ) ; TranslateToPyExprVisitor translator = new TranslateToPyExprVisitor ( localVarExprs , pluginValueFactory , errorReporter ) ; StringBuilder pyExprTextSb = new StringBuilder ( ) ; boolean hasElse = false ; // We need to be careful about parenthesizing the sub-expressions in a python ternary operator, // as nested ternary operators will right-associate. Due to the structure of the parse tree, // we accumulate open parens in the loop below, and pendingParens tracks how many closing parens // we need to add at the end. int pendingParens = 0 ; for ( SoyNode child : node . getChildren ( ) ) { if ( child instanceof IfCondNode ) { IfCondNode icn = ( IfCondNode ) child ; // Python ternary conditional expressions modify the order of the conditional from // <conditional> ? <true> : <false> to // <true> if <conditional> else <false> PyExpr condBlock = PyExprUtils . concatPyExprs ( genPyExprsVisitor . exec ( icn ) ) . toPyString ( ) ; condBlock = PyExprUtils . maybeProtect ( condBlock , PyExprUtils . pyPrecedenceForOperator ( Operator . CONDITIONAL ) ) ; pyExprTextSb . append ( "(" ) . append ( condBlock . getText ( ) ) ; // Append the conditional and if/else syntax. 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 ( ")" ) ; } // By their nature, inline'd conditionals can only contain output strings, so they can be // treated as a string type with a conditional precedence. 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 . | 723 | 23 |
30,673 | @ Nullable public HtmlAttributeNode getDirectAttributeNamed ( String attrName ) { // the child at index 0 is the tag name 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 . | 113 | 15 |
30,674 | private SoyList newListFromIterable ( Iterable < ? > items ) { // Create a list backed by a Java list which has eagerly converted each value into a lazy // value provider. Specifically, the list iteration is done eagerly so that the lazy value // provider can cache its value. 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 . | 116 | 11 |
30,675 | 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 . | 117 | 27 |
30,676 | private static long computeMsgId ( MsgNode msgNode ) { return SoyMsgIdComputer . computeMsgId ( buildMsgParts ( msgNode ) , msgNode . getMeaning ( ) , msgNode . getContentType ( ) ) ; } | Computes the unique message id for the given MsgNode . | 52 | 13 |
30,677 | 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 . | 62 | 21 |
30,678 | 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 . | 75 | 18 |
30,679 | private static SoyMsgPluralPart buildMsgPartForPlural ( MsgPluralNode msgPluralNode , MsgNode msgNode ) { // This is the list of the cases. 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 . | 292 | 17 |
30,680 | private static SoyMsgSelectPart buildMsgPartForSelect ( MsgSelectNode msgSelectNode , MsgNode msgNode ) { // This is the list of the cases. 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 . | 241 | 16 |
30,681 | public Expression gen ( CallNode callNode , TemplateAliases templateAliases , TranslationContext translationContext , ErrorReporter errorReporter , TranslateExprNodeVisitor exprTranslator ) { // Build the JS CodeChunk for the callee's name. Expression callee = genCallee ( callNode , templateAliases , exprTranslator ) ; // Generate the data object to pass to callee 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 . | 170 | 10 |
30,682 | public Expression genObjToPass ( CallNode callNode , TemplateAliases templateAliases , TranslationContext translationContext , ErrorReporter errorReporter , TranslateExprNodeVisitor exprTranslator ) { // ------ Generate the expression for the original data to pass ------ Expression dataToPass ; if ( callNode . isPassingAllData ( ) ) { dataToPass = JsRuntime . OPT_DATA ; } else if ( callNode . isPassingData ( ) ) { dataToPass = exprTranslator . exec ( callNode . getDataExpr ( ) ) ; } else if ( callNode . numChildren ( ) == 0 ) { // If we're passing neither children nor indirect data, we can immediately return null. return LITERAL_NULL ; } else { dataToPass = LITERAL_NULL ; } Map < String , Expression > paramDefaults = getDefaultParams ( callNode , translationContext ) ; // ------ Case 1: No additional params ------ if ( callNode . numChildren ( ) == 0 ) { if ( ! paramDefaults . isEmpty ( ) ) { dataToPass = SOY_ASSIGN_DEFAULTS . call ( dataToPass , Expression . objectLiteral ( paramDefaults ) ) ; } // Ignore inconsistencies between Closure Compiler & Soy type systems (eg, proto nullability). return dataToPass . castAs ( "?" ) ; } // ------ Build an object literal containing the additional params ------ 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 { // This is a param with content that cannot be represented as JS expressions, so we assume // that code has been generated to define the temporary variable 'param<n>'. value = id ( "param" + cpcn . getId ( ) ) ; } value = maybeWrapContent ( translationContext . codeGenerator ( ) , cpcn , value ) ; } params . put ( child . getKey ( ) . identifier ( ) , value ) ; } Expression paramsExp = Expression . objectLiteral ( params ) ; // ------ Cases 2 and 3: Additional params with and without original data to pass ------ if ( callNode . isPassingData ( ) ) { Expression allData = SOY_ASSIGN_DEFAULTS . call ( paramsExp , dataToPass ) ; // No need to cast; assignDefaults already returns {?}. return allData ; } else { // Ignore inconsistencies between Closure Compiler & Soy type systems (eg, proto nullability). return paramsExp . castAs ( "?" ) ; } } | Generates the JS expression for the object to pass in a given call . | 702 | 15 |
30,683 | protected Expression maybeWrapContent ( CodeChunk . Generator generator , CallParamContentNode node , Expression content ) { if ( node . getContentKind ( ) == null ) { return content ; } // Use the internal blocks wrapper, to maintain falsiness of empty string 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 . | 81 | 41 |
30,684 | @ Nullable 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 . | 174 | 16 |
30,685 | public String findTypeWithMatchingNamespace ( String prefix ) { prefix = prefix + "." ; // This must be sorted so that errors are deterministic, or we'll break integration tests. 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 . | 75 | 20 |
30,686 | 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 . | 100 | 9 |
30,687 | 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 . | 66 | 19 |
30,688 | public static SoyMsgRawTextPart of ( String rawText ) { int utf8Length = Utf8 . encodedLength ( rawText ) ; // Determine whether UTF8 or UTF16 uses less memory, and choose between one of the two internal // implementations. char[] is preferred if the sizes are equal because it is faster to turn // back into a String. In a realistic application with 1 million messages in memory, using // UTF-8 saves about 35M, and dynamicaly switching encodings saves another 10M. // IMPORTANT! This choice is deterministic, so that for any particular input string the choice // of implementation class is the same. This ensures operations like equals() and hashCode() // do not have to decode the contents. 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 . | 216 | 14 |
30,689 | public boolean isPure ( ) { if ( soyFunction instanceof BuiltinFunction ) { return ( ( BuiltinFunction ) soyFunction ) . isPure ( ) ; } return soyFunction . getClass ( ) . isAnnotationPresent ( SoyPureFunction . class ) ; } | Whether or not this function is pure . | 57 | 8 |
30,690 | 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 . | 132 | 12 |
30,691 | 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 . | 67 | 39 |
30,692 | @ Nullable 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 . | 56 | 15 |
30,693 | 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 . | 50 | 17 |
30,694 | public static boolean equal ( SoyValue operand0 , SoyValue operand1 ) { // Treat the case where either is a string specially. // TODO(gboyer): This should probably handle SanitizedContent == SanitizedContent, even though // Javascript doesn't handle that case properly. http://b/21461181 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 . | 163 | 14 |
30,695 | 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 . | 72 | 15 |
30,696 | public GoogRequire merge ( GoogRequire other ) { checkArgument ( other . symbol ( ) . equals ( symbol ( ) ) ) ; if ( other . equals ( this ) ) { return this ; } // if symbols are equal and the references are, then they must differ only by requireType or not // prefer the non requireType symbol 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 . | 216 | 16 |
30,697 | 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 . | 64 | 28 |
30,698 | 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 . | 132 | 19 |
30,699 | 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 . | 197 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.