idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
30,500 | static SoyNodeCompiler create ( CompiledTemplateRegistry registry , InnerClasses innerClasses , FieldRef stateField , Expression thisVar , AppendableExpression appendableVar , TemplateVariableManager variables , TemplateParameterLookup parameterLookup , ErrorReporter reporter , SoyTypeRegistry typeRegistry ) { DetachState detachState = new DetachState ( variables , thisVar , stateField ) ; ExpressionCompiler expressionCompiler = ExpressionCompiler . create ( detachState , parameterLookup , variables , reporter , typeRegistry ) ; ExpressionToSoyValueProviderCompiler soyValueProviderCompiler = ExpressionToSoyValueProviderCompiler . create ( variables , expressionCompiler , parameterLookup ) ; return new SoyNodeCompiler ( thisVar , registry , detachState , variables , parameterLookup , appendableVar , expressionCompiler , soyValueProviderCompiler , new LazyClosureCompiler ( registry , innerClasses , parameterLookup , variables , soyValueProviderCompiler , reporter , typeRegistry ) ) ; } | Creates a SoyNodeCompiler | 220 | 7 |
30,501 | private Expression computeRangeValue ( SyntheticVarName varName , Optional < ExprNode > expression , int defaultValue , Scope scope , final ImmutableList . Builder < Statement > initStatements ) { if ( ! expression . isPresent ( ) ) { return constant ( defaultValue ) ; } else if ( expression . get ( ) instanceof IntegerNode && ( ( IntegerNode ) expression . get ( ) ) . isInt ( ) ) { int value = Ints . checkedCast ( ( ( IntegerNode ) expression . get ( ) ) . getValue ( ) ) ; return constant ( value ) ; } else { Label startDetachPoint = new Label ( ) ; // Note: If the value of rangeArgs.start() is above 32 bits, Ints.checkedCast() will fail at // runtime with IllegalArgumentException. Expression startExpression = MethodRef . INTS_CHECKED_CAST . invoke ( exprCompiler . compile ( expression . get ( ) , startDetachPoint ) . unboxAsLong ( ) ) ; if ( ! startExpression . isCheap ( ) ) { // bounce it into a local variable Variable startVar = scope . createSynthetic ( varName , startExpression , STORE ) ; initStatements . add ( startVar . initializer ( ) . labelStart ( startDetachPoint ) ) ; startExpression = startVar . local ( ) ; } return startExpression ; } } | Computes a single range argument . | 303 | 7 |
30,502 | private static boolean shouldCheckBuffer ( PrintNode node ) { if ( ! ( node . getExpr ( ) . getRoot ( ) instanceof FunctionNode ) ) { return true ; } FunctionNode fn = ( FunctionNode ) node . getExpr ( ) . getRoot ( ) ; if ( ! ( fn . getSoyFunction ( ) instanceof BuiltinFunction ) ) { return true ; } BuiltinFunction bfn = ( BuiltinFunction ) fn . getSoyFunction ( ) ; if ( bfn != BuiltinFunction . XID && bfn != BuiltinFunction . CSS ) { return true ; } return false ; } | Returns true if the print expression should check the rendering buffer and generate a detach . | 134 | 16 |
30,503 | private void validateVeLogNode ( VeLogNode node ) { if ( node . getVeDataExpression ( ) . getRoot ( ) . getType ( ) . getKind ( ) != Kind . VE_DATA ) { reporter . report ( node . getVeDataExpression ( ) . getSourceLocation ( ) , INVALID_VE , node . getVeDataExpression ( ) . getRoot ( ) . getType ( ) ) ; } if ( node . getLogonlyExpression ( ) != null ) { // check to see if it is in a msg node. logonly is disallowed in msg nodes because we don't // have an implementation strategy. if ( isInMsgNode ( node ) ) { reporter . report ( node . getLogonlyExpression ( ) . getSourceLocation ( ) , LOGONLY_DISALLOWED_IN_MSG ) ; } SoyType type = node . getLogonlyExpression ( ) . getType ( ) ; if ( type . getKind ( ) != Kind . BOOL ) { reporter . report ( node . getLogonlyExpression ( ) . getSourceLocation ( ) , WRONG_TYPE , BoolType . getInstance ( ) , type ) ; } } } | Type checks the VE and logonly expressions . | 262 | 10 |
30,504 | public static UniqueNameGenerator forLocalVariables ( ) { UniqueNameGenerator generator = new UniqueNameGenerator ( DANGEROUS_CHARACTERS , "$$" ) ; generator . reserve ( JsSrcUtils . JS_LITERALS ) ; generator . reserve ( JsSrcUtils . JS_RESERVED_WORDS ) ; return generator ; } | Returns a name generator suitable for generating local variable names . | 84 | 11 |
30,505 | public synchronized void put ( String fileName , VersionedFile versionedFile ) { cache . put ( fileName , versionedFile . copy ( ) ) ; } | Stores a cached version of the AST . | 34 | 9 |
30,506 | public synchronized VersionedFile get ( String fileName , Version version ) { VersionedFile entry = cache . get ( fileName ) ; if ( entry != null ) { if ( entry . version ( ) . equals ( version ) ) { // Make a defensive copy since the caller might run further passes on it. return entry . copy ( ) ; } else { // Aggressively purge to save memory. cache . remove ( fileName ) ; } } return null ; } | Retrieves a cached version of this file supplier AST if any . | 97 | 14 |
30,507 | public static boolean isSanitizedContentField ( FieldDescriptor fieldDescriptor ) { return fieldDescriptor . getType ( ) == Type . MESSAGE && SAFE_PROTO_TYPES . contains ( fieldDescriptor . getMessageType ( ) . getFullName ( ) ) ; } | Returns true if fieldDescriptor holds a sanitized proto type . | 68 | 14 |
30,508 | public static boolean isSanitizedContentMap ( FieldDescriptor fieldDescriptor ) { if ( ! fieldDescriptor . isMapField ( ) ) { return false ; } Descriptor valueDesc = getMapValueMessageType ( fieldDescriptor ) ; if ( valueDesc == null ) { return false ; } return SAFE_PROTO_TYPES . contains ( valueDesc . getFullName ( ) ) ; } | Returns true if fieldDescriptor holds a map where the values are a sanitized proto type . | 92 | 20 |
30,509 | @ Nullable public static Descriptor getMapValueMessageType ( FieldDescriptor mapField ) { FieldDescriptor valueDesc = mapField . getMessageType ( ) . findFieldByName ( "value" ) ; if ( valueDesc . getType ( ) == FieldDescriptor . Type . MESSAGE ) { return valueDesc . getMessageType ( ) ; } else { return null ; } } | Returns the descriptor representing the type of the value of the map field . Returns null if the map value isn t a message . | 89 | 25 |
30,510 | public static String getJsExtensionImport ( FieldDescriptor desc ) { Descriptor scope = desc . getExtensionScope ( ) ; if ( scope != null ) { while ( scope . getContainingType ( ) != null ) { scope = scope . getContainingType ( ) ; } return calculateQualifiedJsName ( scope ) ; } return getJsPackage ( desc . getFile ( ) ) + "." + computeJsExtensionName ( desc ) ; } | Returns the JS name of the import for the given extension suitable for goog . require . | 100 | 18 |
30,511 | private static String computeJsExtensionName ( FieldDescriptor field ) { String name = CaseFormat . LOWER_UNDERSCORE . to ( CaseFormat . LOWER_CAMEL , field . getName ( ) ) ; return field . isRepeated ( ) ? name + "List" : name ; } | Performs camelcase translation . | 69 | 6 |
30,512 | private static String getJsPackage ( FileDescriptor file ) { String protoPackage = file . getPackage ( ) ; if ( ! protoPackage . isEmpty ( ) ) { return "proto." + protoPackage ; } return "proto" ; } | Returns the expected javascript package for protos based on the . proto file . | 54 | 15 |
30,513 | public static boolean hasJsType ( FieldDescriptor fieldDescriptor ) { if ( ! JS_TYPEABLE_FIELDS . contains ( fieldDescriptor . getType ( ) ) ) { return false ; } if ( fieldDescriptor . getOptions ( ) . hasJstype ( ) ) { return true ; } return false ; } | Returns true if this field has a valid jstype annotation . | 75 | 13 |
30,514 | public static boolean isUnsigned ( FieldDescriptor descriptor ) { switch ( descriptor . getType ( ) ) { case FIXED32 : case FIXED64 : case UINT32 : case UINT64 : return true ; default : return false ; } } | Returns true if this field is an unsigned integer . | 54 | 10 |
30,515 | static boolean shouldCheckFieldPresenceToEmulateJspbNullability ( FieldDescriptor desc ) { boolean hasBrokenSemantics = false ; if ( desc . hasDefaultValue ( ) || desc . isRepeated ( ) ) { return false ; } else if ( desc . getFile ( ) . getSyntax ( ) == Syntax . PROTO3 || ! hasBrokenSemantics ) { // in proto3 or proto2 with non-broken semantics we only need to check for presence for // message typed fields. return desc . getJavaType ( ) == JavaType . MESSAGE ; } else { return true ; } } | Returns whether or not we should check for presence to emulate jspb nullability semantics in server side soy . | 136 | 22 |
30,516 | @ Override public boolean shouldUseSameVarNameAs ( MsgSubstUnitNode other ) { return ( other instanceof MsgPlaceholderNode ) && this . initialNodeKind == ( ( MsgPlaceholderNode ) other ) . initialNodeKind && this . samenessKey . equals ( ( ( MsgPlaceholderNode ) other ) . samenessKey ) ; } | Returns whether this node and the given other node are the same such that they should be represented by the same placeholder . | 79 | 23 |
30,517 | @ VisibleForTesting static String icuEscape ( String rawText ) { Matcher matcher = ICU_SYNTAX_CHAR_NEEDING_ESCAPE_PATTERN . matcher ( rawText ) ; if ( ! matcher . find ( ) ) { return rawText ; } StringBuffer escapedTextSb = new StringBuffer ( ) ; do { String repl = ICU_SYNTAX_CHAR_ESCAPE_MAP . get ( matcher . group ( ) ) ; matcher . appendReplacement ( escapedTextSb , repl ) ; } while ( matcher . find ( ) ) ; matcher . appendTail ( escapedTextSb ) ; return escapedTextSb . toString ( ) ; } | Escapes ICU syntax characters in raw text . | 162 | 10 |
30,518 | @ SuppressWarnings ( "unchecked" ) // The constructor guarantees the type of ImmutableList. private SoyMsg resurrectMsg ( long id , ImmutableList < SoyMsgPart > parts ) { return SoyMsg . builder ( ) . setId ( id ) . setLocaleString ( localeString ) . setIsPlrselMsg ( MsgPartUtils . hasPlrselPart ( parts ) ) . setParts ( parts ) . build ( ) ; } | Brings a message back to life from only its ID and parts . | 100 | 14 |
30,519 | public Boolean isPossibleHeaderVar ( ) { if ( defn == null ) { throw new NullPointerException ( getSourceLocation ( ) . toString ( ) ) ; } return defn . kind ( ) == VarDefn . Kind . PARAM || defn . kind ( ) == VarDefn . Kind . STATE || defn . kind ( ) == VarDefn . Kind . UNDECLARED ; } | Returns whether this might be header variable reference . A header variable is declared in Soy with the | 90 | 18 |
30,520 | @ Nullable public SoyNode firstChildThatMatches ( Predicate < SoyNode > condition ) { int firstChildIndex = 0 ; while ( firstChildIndex < numChildren ( ) && ! condition . test ( getChild ( firstChildIndex ) ) ) { firstChildIndex ++ ; } if ( firstChildIndex < numChildren ( ) ) { return getChild ( firstChildIndex ) ; } return null ; } | Returns the template s first child node that matches the given condition . | 86 | 13 |
30,521 | @ Nullable public SoyNode lastChildThatMatches ( Predicate < SoyNode > condition ) { int lastChildIndex = numChildren ( ) - 1 ; while ( lastChildIndex >= 0 && ! condition . test ( getChild ( lastChildIndex ) ) ) { lastChildIndex -- ; } if ( lastChildIndex >= 0 ) { return getChild ( lastChildIndex ) ; } return null ; } | Returns the template s last child node that matches the given condition . | 85 | 13 |
30,522 | @ SuppressWarnings ( "unused" ) // called in SoyFileParser.jj public static final String calculateFullCalleeName ( Identifier ident , SoyFileHeaderInfo header , ErrorReporter errorReporter ) { String name = ident . identifier ( ) ; switch ( ident . type ( ) ) { case DOT_IDENT : // Case 1: Source callee name is partial. return header . getNamespace ( ) + name ; case DOTTED_IDENT : // Case 2: Source callee name is a proper dotted ident, which might start with an alias. return header . resolveAlias ( name ) ; case SINGLE_IDENT : // Case 3: Source callee name is a single ident (not dotted). if ( header . hasAlias ( name ) ) { // Case 3a: This callee collides with a namespace alias, which likely means the alias // incorrectly references a template. errorReporter . report ( ident . location ( ) , CALL_COLLIDES_WITH_NAMESPACE_ALIAS , name ) ; } else { // Case 3b: The callee name needs a namespace. errorReporter . report ( ident . location ( ) , MISSING_CALLEE_NAMESPACE , name ) ; } return name ; } throw new AssertionError ( ident . type ( ) ) ; } | Given a template call and file header info return the expanded callee name if possible . | 287 | 17 |
30,523 | @ SuppressWarnings ( "unused" ) // called in SoyFileParser.jj public static String unescapeString ( String s , ErrorReporter errorReporter , SourceLocation loc ) { StringBuilder sb = new StringBuilder ( s . length ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; ) { char c = s . charAt ( i ) ; if ( c == ' ' ) { i = doUnescape ( s , i + 1 , sb , errorReporter , loc ) ; } else { sb . append ( c ) ; i ++ ; } } return sb . toString ( ) ; } | Unescapes a Soy string according to JavaScript rules . | 143 | 12 |
30,524 | private static int doUnescape ( String s , int i , StringBuilder sb , ErrorReporter errorReporter , SourceLocation loc ) { checkArgument ( i < s . length ( ) , "Found escape sequence at the end of a string." ) ; char c = s . charAt ( i ++ ) ; switch ( c ) { case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : case ' ' : case ' ' : case ' ' : sb . append ( c ) ; break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : -- i ; // backup to first octal digit int nOctalDigits = 1 ; int digitLimit = c < ' ' ? 3 : 2 ; while ( nOctalDigits < digitLimit && i + nOctalDigits < s . length ( ) && isOctal ( s . charAt ( i + nOctalDigits ) ) ) { ++ nOctalDigits ; } sb . append ( ( char ) Integer . parseInt ( s . substring ( i , i + nOctalDigits ) , 8 ) ) ; i += nOctalDigits ; break ; case ' ' : case ' ' : String hexCode ; int nHexDigits = ( c == ' ' ? 4 : 2 ) ; try { hexCode = s . substring ( i , i + nHexDigits ) ; } catch ( IndexOutOfBoundsException ioobe ) { errorReporter . report ( loc . offsetStartCol ( i + 1 ) , INVALID_UNICODE_SEQUENCE , s . substring ( i ) ) ; return i + nHexDigits ; } int unicodeValue ; try { unicodeValue = Integer . parseInt ( hexCode , 16 ) ; } catch ( NumberFormatException nfe ) { errorReporter . report ( loc . offsetStartCol ( i + 1 ) , INVALID_UNICODE_SEQUENCE , hexCode ) ; return i + nHexDigits ; } sb . append ( ( char ) unicodeValue ) ; i += nHexDigits ; break ; default : errorReporter . report ( loc . offsetStartCol ( i ) , UNKNOWN_ESCAPE_CODE , c ) ; return i ; } return i ; } | Looks for an escape code starting at index i of s and appends it to sb . | 582 | 19 |
30,525 | static String unescapeCommandAttributeValue ( String s , QuoteStyle quoteStyle ) { // NOTE: we don't just use String.replace since it internally allocates/compiles a regular // expression. Instead we have a handrolled loop. int index = s . indexOf ( quoteStyle == QuoteStyle . DOUBLE ? "\\\"" : "\\\'" ) ; if ( index == - 1 ) { return s ; } StringBuilder buf = new StringBuilder ( s . length ( ) ) ; buf . append ( s ) ; boolean nextIsQ = buf . charAt ( s . length ( ) - 1 ) == quoteStyle . getQuoteChar ( ) ; for ( int i = s . length ( ) - 2 ; i >= index ; i -- ) { char c = buf . charAt ( i ) ; if ( c == ' ' && nextIsQ ) { buf . deleteCharAt ( i ) ; } nextIsQ = c == quoteStyle . getQuoteChar ( ) ; } return buf . toString ( ) ; } | Unescapes backslash quote sequences in an attribute value to just the quote . | 219 | 18 |
30,526 | public void defineField ( ClassVisitor cv ) { cv . visitField ( accessFlags ( ) , name ( ) , type ( ) . getDescriptor ( ) , null /* no generic signature */ , null /* no initializer */ ) ; } | Defines the given field as member of the class . | 54 | 11 |
30,527 | public Expression accessor ( final Expression owner ) { checkState ( ! isStatic ( ) ) ; checkArgument ( owner . resultType ( ) . equals ( this . owner ( ) . type ( ) ) ) ; Features features = Features . of ( ) ; if ( owner . isCheap ( ) ) { features = features . plus ( Feature . CHEAP ) ; } if ( ! isNullable ( ) ) { features = features . plus ( Feature . NON_NULLABLE ) ; } return new Expression ( type ( ) , features ) { @ Override protected void doGen ( CodeBuilder mv ) { owner . gen ( mv ) ; mv . getField ( owner ( ) . type ( ) , FieldRef . this . name ( ) , resultType ( ) ) ; } } ; } | Returns an accessor that accesses this field on the given owner . | 170 | 14 |
30,528 | public Expression accessor ( ) { checkState ( isStatic ( ) ) ; Features features = Features . of ( Feature . CHEAP ) ; if ( ! isNullable ( ) ) { features = features . plus ( Feature . NON_NULLABLE ) ; } return new Expression ( type ( ) , features ) { @ Override protected void doGen ( CodeBuilder mv ) { accessStaticUnchecked ( mv ) ; } } ; } | Returns an expression that accesses this static field . | 93 | 10 |
30,529 | void accessStaticUnchecked ( CodeBuilder mv ) { checkState ( isStatic ( ) ) ; mv . getStatic ( owner ( ) . type ( ) , FieldRef . this . name ( ) , type ( ) ) ; } | Accesses a static field . | 50 | 6 |
30,530 | public void putUnchecked ( CodeBuilder adapter ) { checkState ( ! isStatic ( ) , "This field is static!" ) ; adapter . putField ( owner ( ) . type ( ) , name ( ) , type ( ) ) ; } | Adds code to place the top item of the stack into this field . | 51 | 14 |
30,531 | void compile ( ) { TypeInfo factoryType = innerClasses . registerInnerClass ( FACTORY_CLASS , FACTORY_ACCESS ) ; SoyClassWriter cw = SoyClassWriter . builder ( factoryType ) . implementing ( FACTORY_TYPE ) . setAccess ( FACTORY_ACCESS ) . sourceFileName ( templateNode . getSourceLocation ( ) . getFileName ( ) ) . build ( ) ; innerClasses . registerAsInnerClass ( cw , factoryType ) ; generateStaticInitializer ( cw ) ; defineDefaultConstructor ( cw , factoryType ) ; generateCreateMethod ( cw , factoryType ) ; cw . visitEnd ( ) ; innerClasses . add ( cw . toClassData ( ) ) ; } | Compiles the factory . | 167 | 5 |
30,532 | private int processNextToken ( RawTextNode node , final int offset , String text ) { // Find the transition whose pattern matches earliest in the raw text (and is applicable) int numCharsConsumed ; Context next ; int earliestStart = Integer . MAX_VALUE ; int earliestEnd = - 1 ; Transition earliestTransition = null ; Matcher earliestMatcher = null ; List < Transition > ts = TRANSITIONS . get ( context . state ) ; if ( ts == null ) { throw new NullPointerException ( "no transitions for state: " + context . state + " @" + node . substringLocation ( offset , offset + 1 ) ) ; } for ( Transition transition : ts ) { if ( transition . pattern != null ) { Matcher matcher = transition . pattern . matcher ( text ) ; // For each transition: // look for matches, if the match is later than the current earliest match, give up // otherwise if the match is applicable, store it. // NOTE: matcher.find() returns matches in sequential order. try { while ( matcher . find ( ) && matcher . start ( ) < earliestStart ) { int start = matcher . start ( ) ; int end = matcher . end ( ) ; if ( transition . isApplicableTo ( context , matcher ) ) { earliestStart = start ; earliestEnd = end ; earliestTransition = transition ; earliestMatcher = matcher ; break ; } } } catch ( StackOverflowError soe ) { // catch and annotate with the pattern. throw new RuntimeException ( String . format ( "StackOverflow while trying to match: '%s' in context %s starting @ %s" , transition . pattern , context , node . substringLocation ( offset , offset + 1 ) ) , soe ) ; } } else if ( transition . literal != null ) { int start = 0 ; int index ; String needle = transition . literal ; while ( ( index = text . indexOf ( needle , start ) ) != - 1 && index < earliestStart ) { if ( transition . isApplicableTo ( context , null ) ) { earliestStart = index ; earliestEnd = index + needle . length ( ) ; earliestTransition = transition ; earliestMatcher = null ; break ; } } } else { if ( text . length ( ) < earliestStart && transition . isApplicableTo ( context , null ) ) { earliestStart = text . length ( ) ; earliestEnd = text . length ( ) ; earliestTransition = transition ; earliestMatcher = null ; } } } if ( earliestTransition != null ) { int transitionOffset = offset ; // the earliest start might be at the end for null transitions. if ( earliestStart < text . length ( ) ) { transitionOffset += earliestStart ; } next = earliestTransition . computeNextContext ( node , transitionOffset , context , earliestMatcher ) ; numCharsConsumed = earliestEnd ; } else { throw SoyAutoescapeException . createWithNode ( "Error determining next state when encountering \"" + text + "\" in " + context , // calculate a raw text node that points at the beginning of the string that couldn't // bet matched. node . substring ( Integer . MAX_VALUE /* bogus id */ , offset ) ) ; } if ( numCharsConsumed == 0 && next . state == context . state ) { throw new IllegalStateException ( "Infinite loop at `" + text + "` / " + context ) ; } this . context = next ; return numCharsConsumed ; } | Consume a portion of text and compute the next context . Output is stored in member variables . | 750 | 19 |
30,533 | public static Expression fromExpr ( JsExpr expr , Iterable < GoogRequire > requires ) { return Leaf . create ( expr , /* isCheap= */ false , requires ) ; } | Creates a new code chunk from the given expression . The expression s precedence is preserved . | 43 | 18 |
30,534 | public static Expression regexLiteral ( String contents ) { int firstSlash = contents . indexOf ( ' ' ) ; int lastSlash = contents . lastIndexOf ( ' ' ) ; checkArgument ( firstSlash < lastSlash && firstSlash != - 1 , "expected regex to start with a '/' and have a second '/' near the end, got %s" , contents ) ; return Leaf . create ( contents , /* isCheap= */ false ) ; } | Creates a code chunk representing a JavaScript regular expression literal . | 104 | 12 |
30,535 | public static Expression number ( long value ) { Preconditions . checkArgument ( IntegerNode . isInRange ( value ) , "Number is outside JS safe integer range: %s" , value ) ; return Leaf . create ( Long . toString ( value ) , /* isCheap= */ true ) ; } | Creates a code chunk representing a JavaScript number literal . | 66 | 11 |
30,536 | public static Expression function ( JsDoc parameters , Statement body ) { return FunctionDeclaration . create ( parameters , body ) ; } | Creates a code chunk representing an anonymous function literal . | 27 | 11 |
30,537 | public static Expression arrowFunction ( JsDoc parameters , Statement body ) { return FunctionDeclaration . createArrowFunction ( parameters , body ) ; } | Creates a code chunk representing an arrow function . | 31 | 10 |
30,538 | public static Expression operation ( Operator op , List < Expression > operands ) { Preconditions . checkArgument ( operands . size ( ) == op . getNumOperands ( ) ) ; Preconditions . checkArgument ( op != Operator . AND && op != Operator . OR && op != Operator . CONDITIONAL ) ; switch ( op . getNumOperands ( ) ) { case 1 : return PrefixUnaryOperation . create ( op , operands . get ( 0 ) ) ; case 2 : return BinaryOperation . create ( op , operands . get ( 0 ) , operands . get ( 1 ) ) ; default : throw new AssertionError ( ) ; } } | Creates a code chunk representing the given Soy operator applied to the given operands . | 147 | 17 |
30,539 | public static Expression arrayLiteral ( Iterable < ? extends Expression > elements ) { return ArrayLiteral . create ( ImmutableList . copyOf ( elements ) ) ; } | Creates a code chunk representing a javascript array literal . | 38 | 11 |
30,540 | public final Expression withInitialStatements ( Iterable < ? extends Statement > initialStatements ) { // If there are no new initial statements, return the current chunk. if ( Iterables . isEmpty ( initialStatements ) ) { return this ; } // Otherwise, return a code chunk that includes all of the dependent code. return Composite . create ( ImmutableList . copyOf ( initialStatements ) , this ) ; } | Returns a chunk whose output expression is the same as this chunk s but which includes the given initial statements . | 88 | 21 |
30,541 | public TagKind getTagKind ( ) { if ( htmlTagNode instanceof HtmlOpenTagNode ) { HtmlOpenTagNode openTagNode = ( HtmlOpenTagNode ) htmlTagNode ; if ( openTagNode . isSelfClosing ( ) || openTagNode . getTagName ( ) . isDefinitelyVoid ( ) ) { return TagKind . VOID_TAG ; } return TagKind . OPEN_TAG ; } else { return TagKind . CLOSE_TAG ; } } | Returns the tag kind . | 107 | 5 |
30,542 | public static SoyType of ( Collection < SoyType > members ) { // sort and flatten the set of types ImmutableSortedSet . Builder < SoyType > builder = ImmutableSortedSet . orderedBy ( MEMBER_ORDER ) ; for ( SoyType type : members ) { // simplify unions containing these types if ( type . getKind ( ) == Kind . UNKNOWN || type . getKind ( ) == Kind . ERROR || type . getKind ( ) == Kind . ANY ) { return type ; } if ( type . getKind ( ) == Kind . UNION ) { builder . addAll ( ( ( UnionType ) type ) . members ) ; } else { builder . add ( type ) ; } } ImmutableSet < SoyType > flattenedMembers = builder . build ( ) ; if ( flattenedMembers . size ( ) == 1 ) { return Iterables . getOnlyElement ( flattenedMembers ) ; } return new UnionType ( flattenedMembers ) ; } | Create a union from a collection of types . | 202 | 9 |
30,543 | public boolean isNullable ( ) { return members . stream ( ) . anyMatch ( t -> t . getKind ( ) == SoyType . Kind . NULL ) ; } | Returns true if the union includes the null type . | 36 | 10 |
30,544 | public SoyType removeNullability ( ) { if ( isNullable ( ) ) { return of ( members . stream ( ) . filter ( t -> t . getKind ( ) != SoyType . Kind . NULL ) . collect ( Collectors . toList ( ) ) ) ; } return this ; } | Returns a Soy type that is equivalent to this one but with null removed . | 63 | 15 |
30,545 | public void addChild ( N child ) { checkNotNull ( child ) ; tryRemoveFromOldParent ( child ) ; children . add ( child ) ; child . setParent ( master ) ; } | Adds the given child . | 41 | 5 |
30,546 | public void removeChild ( int index ) { N child = children . remove ( index ) ; child . setParent ( null ) ; } | Removes the child at the given index . | 28 | 9 |
30,547 | public void replaceChild ( int index , N newChild ) { checkNotNull ( newChild ) ; tryRemoveFromOldParent ( newChild ) ; N oldChild = children . set ( index , newChild ) ; oldChild . setParent ( null ) ; newChild . setParent ( master ) ; } | Replaces the child at the given index with the given new child . | 64 | 14 |
30,548 | public void clearChildren ( ) { for ( int i = 0 ; i < children . size ( ) ; i ++ ) { children . get ( i ) . setParent ( null ) ; } children . clear ( ) ; } | Clears the list of children . | 47 | 7 |
30,549 | @ SuppressWarnings ( "unchecked" ) public void addChildren ( List < ? extends N > children ) { // NOTE: if the input list comes from another node, this could cause // ConcurrentModificationExceptions as nodes are moved from one parent to another. To avoid // this we make a copy of the input list. for ( Node child : children . toArray ( new Node [ 0 ] ) ) { addChild ( ( N ) child ) ; } } | Adds the given children . | 100 | 5 |
30,550 | public void appendSourceStringForChildren ( StringBuilder sb ) { for ( N child : children ) { sb . append ( child . toSourceString ( ) ) ; } } | Appends the source strings for all the children to the given StringBuilder . | 38 | 15 |
30,551 | public T setId ( int id ) { Preconditions . checkState ( this . id == null ) ; this . id = id ; return ( T ) this ; } | Sets the id for the node to be built . | 36 | 11 |
30,552 | public T setSoyDoc ( String soyDoc , SourceLocation soyDocLocation ) { Preconditions . checkState ( this . soyDoc == null ) ; Preconditions . checkState ( cmdText != null ) ; int paramOffset = soyDoc . indexOf ( "@param" ) ; if ( paramOffset != - 1 ) { errorReporter . report ( new RawTextNode ( - 1 , soyDoc , soyDocLocation ) . substringLocation ( paramOffset , paramOffset + "@param" . length ( ) ) , SOYDOC_PARAM ) ; } this . soyDoc = soyDoc ; Preconditions . checkArgument ( soyDoc . startsWith ( "/**" ) && soyDoc . endsWith ( "*/" ) ) ; this . soyDocDesc = cleanSoyDocHelper ( soyDoc ) ; return ( T ) this ; } | Sets the SoyDoc for the node to be built . | 182 | 12 |
30,553 | public T addParams ( Iterable < ? extends TemplateParam > newParams ) { Set < String > seenParamKeys = new HashSet <> ( ) ; if ( this . params == null ) { this . params = ImmutableList . copyOf ( newParams ) ; } else { for ( TemplateParam oldParam : this . params ) { seenParamKeys . add ( oldParam . name ( ) ) ; } this . params = ImmutableList . < TemplateParam > builder ( ) . addAll ( this . params ) . addAll ( newParams ) . build ( ) ; } // Check new params. for ( TemplateParam param : newParams ) { if ( param . name ( ) . equals ( "ij" ) ) { errorReporter . report ( param . nameLocation ( ) , INVALID_PARAM_NAMED_IJ ) ; } if ( ! seenParamKeys . add ( param . name ( ) ) ) { errorReporter . report ( param . nameLocation ( ) , PARAM_ALREADY_DECLARED , param . name ( ) ) ; } } return ( T ) this ; } | This method is intended to be called at most once for header params . | 245 | 14 |
30,554 | public static < T extends Node > ImmutableList < T > getAllNodesOfType ( Node rootSoyNode , final Class < T > classObject ) { return getAllMatchingNodesOfType ( rootSoyNode , classObject , arg -> true ) ; } | Retrieves all nodes in a tree that are an instance of a particular class . | 59 | 17 |
30,555 | private static < T extends Node > ImmutableList < T > getAllMatchingNodesOfType ( Node rootSoyNode , final Class < T > classObject , final Predicate < T > filter ) { final ImmutableList . Builder < T > matchedNodesBuilder = ImmutableList . builder ( ) ; // optimization to avoid navigating into expr trees if we can't possibly match anything final boolean exploreExpressions = ExprNode . class . isAssignableFrom ( classObject ) ; visitAllNodes ( rootSoyNode , new NodeVisitor < Node , VisitDirective > ( ) { @ Override public VisitDirective exec ( Node node ) { if ( classObject . isInstance ( node ) ) { T typedNode = classObject . cast ( node ) ; if ( filter . test ( typedNode ) ) { matchedNodesBuilder . add ( typedNode ) ; } } if ( ! exploreExpressions && node instanceof ExprNode ) { return VisitDirective . SKIP_CHILDREN ; } return VisitDirective . CONTINUE ; } } ) ; return matchedNodesBuilder . build ( ) ; } | Retrieves all nodes in a tree that are an instance of a particular class and match the given predicate . | 241 | 22 |
30,556 | public static < R > void execOnAllV2Exprs ( SoyNode node , final AbstractNodeVisitor < ExprNode , R > exprNodeVisitor ) { visitAllNodes ( node , new NodeVisitor < Node , VisitDirective > ( ) { @ Override public VisitDirective exec ( Node node ) { if ( node instanceof ExprHolderNode ) { for ( ExprRootNode expr : ( ( ExprHolderNode ) node ) . getExprList ( ) ) { exprNodeVisitor . exec ( expr ) ; } } else if ( node instanceof ExprNode ) { return VisitDirective . SKIP_CHILDREN ; } return VisitDirective . CONTINUE ; } } ) ; } | Given a Soy node and a visitor for expression trees traverses the subtree of the node and executes the visitor on all expressions held by nodes in the subtree . | 160 | 33 |
30,557 | public static boolean checkCloseTagClosesOptional ( TagName closeTag , TagName optionalOpenTag ) { // TODO(b/120994894): Replace this with checkArgument() when HtmlTagEntry can be replaced. if ( ! optionalOpenTag . isStatic ( ) || ! optionalOpenTag . isDefinitelyOptional ( ) ) { return false ; } if ( ! closeTag . isStatic ( ) ) { return true ; } String openTagName = optionalOpenTag . getStaticTagNameAsLowerCase ( ) ; String closeTagName = closeTag . getStaticTagNameAsLowerCase ( ) ; checkArgument ( ! openTagName . equals ( closeTagName ) ) ; if ( "p" . equals ( openTagName ) ) { return ! PTAG_CLOSE_EXCEPTIONS . contains ( closeTagName ) ; } return OPTIONAL_TAG_CLOSE_TAG_RULES . containsEntry ( openTagName , closeTagName ) ; } | Checks if the an open tag can be auto - closed by a following close tag which does not have the same tag name as the open tag . | 209 | 30 |
30,558 | public static boolean checkOpenTagClosesOptional ( TagName openTag , TagName optionalOpenTag ) { checkArgument ( optionalOpenTag . isDefinitelyOptional ( ) , "Open tag is not optional." ) ; if ( ! ( openTag . isStatic ( ) && optionalOpenTag . isStatic ( ) ) ) { return false ; } String optionalTagName = optionalOpenTag . getStaticTagNameAsLowerCase ( ) ; String openTagName = openTag . getStaticTagNameAsLowerCase ( ) ; return OPTIONAL_TAG_OPEN_CLOSE_RULES . containsEntry ( optionalTagName , openTagName ) ; } | Checks if the given open tag can implicitly close the given optional tag . | 139 | 15 |
30,559 | public SwitchBuilder addCase ( Expression caseLabel , Statement body ) { clauses . add ( new Switch . CaseClause ( ImmutableList . of ( caseLabel ) , body ) ) ; return this ; } | Adds a case clause to this switch statement . | 43 | 9 |
30,560 | public ExprNode valueAsExpr ( ErrorReporter reporter ) { checkState ( value == null ) ; if ( valueExprList . size ( ) > 1 ) { reporter . report ( valueExprList . get ( 1 ) . getSourceLocation ( ) , EXPECTED_A_SINGLE_EXPRESSION , key . identifier ( ) ) ; // Return the first expr to avoid an NPE in CallNode ctor. return valueExprList . get ( 0 ) ; } return Iterables . getOnlyElement ( valueExprList ) ; } | Returns the value as an expression . Only call on an expression attribute . | 121 | 14 |
30,561 | public static List < String > genNoncollidingBaseNamesForExprs ( List < ExprNode > exprNodes , String fallbackBaseName , ErrorReporter errorReporter ) { int numExprs = exprNodes . size ( ) ; // --- Compute candidate base names for each expression. --- List < List < String > > candidateBaseNameLists = Lists . newArrayListWithCapacity ( numExprs ) ; for ( ExprNode exprRoot : exprNodes ) { candidateBaseNameLists . add ( genCandidateBaseNamesForExpr ( exprRoot ) ) ; } // --- Build a multiset of collision strings (if key has > 1 values, then it's a collision). --- // Note: We could combine this loop with the previous loop, but it's more readable this way. Multimap < String , ExprNode > collisionStrToLongestCandidatesMultimap = HashMultimap . create ( ) ; for ( int i = 0 ; i < numExprs ; i ++ ) { ExprNode exprRoot = exprNodes . get ( i ) ; List < String > candidateBaseNameList = candidateBaseNameLists . get ( i ) ; if ( candidateBaseNameList . isEmpty ( ) ) { continue ; } String longestCandidate = candidateBaseNameList . get ( candidateBaseNameList . size ( ) - 1 ) ; // Add longest candidate as a collision string. collisionStrToLongestCandidatesMultimap . put ( longestCandidate , exprRoot ) ; // Add all suffixes that begin after an underscore char as collision strings. for ( int j = 0 , n = longestCandidate . length ( ) ; j < n ; j ++ ) { if ( longestCandidate . charAt ( j ) == ' ' ) { collisionStrToLongestCandidatesMultimap . put ( longestCandidate . substring ( j + 1 ) , exprRoot ) ; } } } // --- Find the shortest noncolliding candidate base name for each expression. --- List < String > noncollidingBaseNames = Lists . newArrayListWithCapacity ( numExprs ) ; OUTER : for ( int i = 0 ; i < numExprs ; i ++ ) { List < String > candidateBaseNameList = candidateBaseNameLists . get ( i ) ; if ( ! candidateBaseNameList . isEmpty ( ) ) { // Has candidates: Use the shortest candidate that doesn't collide. for ( String candidateBaseName : candidateBaseNameList ) { if ( collisionStrToLongestCandidatesMultimap . get ( candidateBaseName ) . size ( ) == 1 ) { // Found candidate with 1 value in multimap, which means no collision. noncollidingBaseNames . add ( candidateBaseName ) ; continue OUTER ; } } // Did not find any candidate with no collision. ExprNode exprRoot = exprNodes . get ( i ) ; String longestCandidate = candidateBaseNameList . get ( candidateBaseNameList . size ( ) - 1 ) ; ExprNode collidingExprRoot = null ; for ( ExprNode er : collisionStrToLongestCandidatesMultimap . get ( longestCandidate ) ) { if ( er != exprRoot ) { collidingExprRoot = er ; break ; } } errorReporter . report ( collidingExprRoot . getSourceLocation ( ) , COLLIDING_EXPRESSIONS , exprRoot . toSourceString ( ) , collidingExprRoot . toSourceString ( ) ) ; return noncollidingBaseNames ; } else { // No candidates: Use fallback. noncollidingBaseNames . add ( fallbackBaseName ) ; } } return noncollidingBaseNames ; } | Generates base names for all the expressions in a list where for each expression we use the shortest candidate base name that does not collide with any of the candidate base names generated from other expressions in the list . Two candidate base names are considered to collide if they are identical or if one is a suffix of the other beginning after an underscore character . | 798 | 68 |
30,562 | @ CheckReturnValue public Expression build ( CodeChunk . Generator codeGenerator ) { ImmutableList < IfThenPair < Expression >> pairs = conditions . build ( ) ; Expression ternary = tryCreateTernary ( pairs ) ; if ( ternary != null ) { return ternary ; } // Otherwise we need to introduce a temporary and assign to it in each branch VariableDeclaration decl = codeGenerator . declarationBuilder ( ) . build ( ) ; Expression var = decl . ref ( ) ; ConditionalBuilder builder = null ; for ( IfThenPair < Expression > oldCondition : pairs ) { Expression newConsequent = var . assign ( oldCondition . consequent ) ; if ( builder == null ) { builder = ifStatement ( oldCondition . predicate , newConsequent . asStatement ( ) ) ; } else { builder . addElseIf ( oldCondition . predicate , newConsequent . asStatement ( ) ) ; } } if ( trailingElse != null ) { builder . setElse ( var . assign ( trailingElse ) . asStatement ( ) ) ; } return var . withInitialStatements ( ImmutableList . of ( decl , builder . build ( ) ) ) ; } | Finishes building this conditional . | 255 | 6 |
30,563 | void addBasic ( Token token ) { if ( basicStart == - 1 ) { basicStart = buffer . length ( ) ; basicStartOfWhitespace = - 1 ; basicHasNewline = false ; } switch ( token . kind ) { case SoyFileParserConstants . TOKEN_WS : if ( token . image . indexOf ( ' ' ) != - 1 || token . image . indexOf ( ' ' ) != - 1 ) { basicHasNewline = true ; } if ( basicStartOfWhitespace == - 1 && whitespaceMode == WhitespaceMode . JOIN ) { basicStartOfWhitespace = buffer . length ( ) ; endLineAtStartOfWhitespace = offsets . endLine ( ) ; endColumnAtStartOfWhitespace = offsets . endColumn ( ) ; } break ; case SoyFileParserConstants . TOKEN_NOT_WS : maybeCollapseWhitespace ( token . image ) ; break ; default : throw new AssertionError ( SoyFileParserConstants . tokenImage [ token . kind ] + " is not a basic text token" ) ; } append ( token , token . image ) ; } | Append a basic token . Basic tokens are text literals . | 246 | 13 |
30,564 | private void append ( Token token , String content ) { if ( content . isEmpty ( ) ) { throw new IllegalStateException ( String . format ( "shouldn't append empty content: %s @ %s" , SoyFileParserConstants . tokenImage [ token . kind ] , Tokens . createSrcLoc ( fileName , token ) ) ) ; } // add a new offset if: // - this is the first token // - the previous token introduced a discontinuity (due to a special token, or whitespace // joining) // - this token doesn't directly abut the previous token (this happens when there is a comment) boolean addOffset = false ; if ( offsets . isEmpty ( ) ) { addOffset = true ; } else if ( discontinuityReason != Reason . NONE ) { addOffset = true ; } else { // are the two tokens not adjacent? We don't actually record comments in the AST or token // stream so this is kind of a guess, but all known cases are due to comments. if ( offsets . endLine ( ) == token . beginLine ) { if ( offsets . endColumn ( ) + 1 != token . beginColumn ) { addOffset = true ; discontinuityReason = Reason . COMMENT ; } } else if ( offsets . endLine ( ) + 1 == token . beginLine && token . beginColumn != 1 ) { addOffset = true ; discontinuityReason = Reason . COMMENT ; } } if ( addOffset ) { offsets . add ( buffer . length ( ) , token . beginLine , token . beginColumn , discontinuityReason ) ; discontinuityReason = Reason . NONE ; } offsets . setEndLocation ( token . endLine , token . endColumn ) ; buffer . append ( content ) ; } | updates the location with the given tokens location . | 369 | 10 |
30,565 | public static String javaClassNameFromSoyTemplateName ( String soyTemplate ) { checkArgument ( BaseUtils . isDottedIdentifier ( soyTemplate ) , "%s is not a valid template name." , soyTemplate ) ; return CLASS_PREFIX + soyTemplate ; } | Translate a user controlled Soy name to a form that is safe to encode in a java class method or field name . | 60 | 24 |
30,566 | public static String javaFileName ( String soyNamespace , String fileName ) { checkArgument ( BaseUtils . isDottedIdentifier ( soyNamespace ) , "%s is not a valid soy namspace name." , soyNamespace ) ; return ( CLASS_PREFIX + soyNamespace ) . replace ( ' ' , ' ' ) + ' ' + fileName ; } | Given the soy namespace and file name returns the path where the corresponding resource should be stored . | 83 | 18 |
30,567 | public static void rewriteStackTrace ( Throwable throwable ) { StackTraceElement [ ] stack = throwable . getStackTrace ( ) ; for ( int i = 0 ; i < stack . length ; i ++ ) { StackTraceElement curr = stack [ i ] ; if ( curr . getClassName ( ) . startsWith ( CLASS_PREFIX ) ) { stack [ i ] = new StackTraceElement ( soyTemplateNameFromJavaClassName ( curr . getClassName ( ) ) , // TODO(lukes): remove the method name? only if it == 'render'? curr . getMethodName ( ) , curr . getFileName ( ) , curr . getLineNumber ( ) ) ; } } throwable . setStackTrace ( stack ) ; } | Rewrites the given stack trace by replacing all references to generated jbcsrc types with the original template names . | 173 | 23 |
30,568 | private static String translateVar ( SoyToJsVariableMappings variableMappings , Matcher matcher ) { Preconditions . checkArgument ( matcher . matches ( ) ) ; String firstPart = matcher . group ( 1 ) ; StringBuilder exprTextSb = new StringBuilder ( ) ; // ------ Translate the first key, which may be a variable or a data key ------ String translation = getLocalVarTranslation ( firstPart , variableMappings ) ; if ( translation != null ) { // Case 1: In-scope local var. exprTextSb . append ( translation ) ; } else { // Case 2: Data reference. exprTextSb . append ( "opt_data." ) . append ( firstPart ) ; } return exprTextSb . toString ( ) ; } | Helper function to translate a variable or data reference . | 167 | 10 |
30,569 | public String typeExprForRecordMember ( boolean isOptional ) { if ( typeExpressions . size ( ) > 1 || isOptional ) { // needs parens return "(" + typeExpr ( ) + ( isOptional && ! typeExpressions . contains ( "undefined" ) ? "|undefined" : "" ) + ")" ; } return typeExpr ( ) ; } | Returns a type expression for a record member . In some cases this requires additional parens . | 83 | 19 |
30,570 | public static DictImpl forProviderMap ( Map < String , ? extends SoyValueProvider > providerMap , RuntimeMapTypeTracker . Type mapType ) { return new DictImpl ( providerMap , mapType ) ; } | Creates a SoyDict implementation for a particular underlying provider map . | 46 | 14 |
30,571 | private StackTraceElement [ ] concatWithJavaStackTrace ( StackTraceElement [ ] javaStackTrace ) { if ( soyStackTrace . isEmpty ( ) ) { return javaStackTrace ; } StackTraceElement [ ] finalStackTrace = new StackTraceElement [ soyStackTrace . size ( ) + javaStackTrace . length ] ; soyStackTrace . toArray ( finalStackTrace ) ; System . arraycopy ( javaStackTrace , 0 , finalStackTrace , soyStackTrace . size ( ) , javaStackTrace . length ) ; return finalStackTrace ; } | Prepend the soy stack trace to the given standard java stack trace . | 136 | 14 |
30,572 | public void put ( Object ... data ) { // TODO: Perhaps change to only convert varargs to Map, and do put(Map) elsewhere. if ( data . length % 2 != 0 ) { throw new SoyDataException ( "Varargs to put(...) must have an even number of arguments (key-value pairs)." ) ; } for ( int i = 0 ; i < data . length ; i += 2 ) { try { put ( ( String ) data [ i ] , SoyData . createFromExistingData ( data [ i + 1 ] ) ) ; } catch ( ClassCastException cce ) { throw new SoyDataException ( "Attempting to add a mapping containing a non-string key (key type " + data [ i ] . getClass ( ) . getName ( ) + ")." ) ; } } } | Convenience function to put multiple mappings in one call . | 175 | 13 |
30,573 | public void remove ( String keyStr ) { List < String > keys = split ( keyStr , ' ' ) ; int numKeys = keys . size ( ) ; CollectionData collectionData = this ; for ( int i = 0 ; i <= numKeys - 2 ; ++ i ) { SoyData soyData = collectionData . getSingle ( keys . get ( i ) ) ; if ( ! ( soyData instanceof CollectionData ) ) { return ; } collectionData = ( CollectionData ) soyData ; } collectionData . removeSingle ( keys . get ( numKeys - 1 ) ) ; } | Removes the data at the specified key string . | 123 | 10 |
30,574 | private static List < String > split ( String str , char delim ) { List < String > result = Lists . newArrayList ( ) ; int currPartStart = 0 ; while ( true ) { int currPartEnd = str . indexOf ( delim , currPartStart ) ; if ( currPartEnd == - 1 ) { result . add ( str . substring ( currPartStart ) ) ; break ; } else { result . add ( str . substring ( currPartStart , currPartEnd ) ) ; currPartStart = currPartEnd + 1 ; } } return result ; } | Splits a string into tokens at the specified delimiter . | 132 | 12 |
30,575 | public static boolean isNumericPrimitive ( SoyType type ) { SoyType . Kind kind = type . getKind ( ) ; if ( NUMERIC_PRIMITIVES . contains ( kind ) ) { return true ; } return type . isAssignableFrom ( NUMBER_TYPE ) || NUMBER_TYPE . isAssignableFrom ( type ) ; } | Returns true if the input type is a numeric primitive type such as int float proto enum and number . | 78 | 20 |
30,576 | public static SoyType tryRemoveNull ( SoyType soyType ) { if ( soyType == NullType . getInstance ( ) ) { return NullType . getInstance ( ) ; } return removeNull ( soyType ) ; } | If the type is nullable makes it non - nullable . | 47 | 13 |
30,577 | public static SoyType computeLowestCommonType ( SoyTypeRegistry typeRegistry , SoyType t0 , SoyType t1 ) { if ( t0 == ErrorType . getInstance ( ) || t1 == ErrorType . getInstance ( ) ) { return ErrorType . getInstance ( ) ; } if ( t0 . isAssignableFrom ( t1 ) ) { return t0 ; } else if ( t1 . isAssignableFrom ( t0 ) ) { return t1 ; } else { // Create a union. This preserves the most information. return typeRegistry . getOrCreateUnionType ( t0 , t1 ) ; } } | Compute the most specific type that is assignable from both t0 and t1 . | 140 | 18 |
30,578 | public static SoyType computeLowestCommonType ( SoyTypeRegistry typeRegistry , Collection < SoyType > types ) { SoyType result = null ; for ( SoyType type : types ) { result = ( result == null ) ? type : computeLowestCommonType ( typeRegistry , result , type ) ; } return result ; } | Compute the most specific type that is assignable from all types within a collection . | 71 | 17 |
30,579 | public static Optional < SoyType > computeLowestCommonTypeArithmetic ( SoyType t0 , SoyType t1 ) { // If either of the types is an error type, return the error type if ( t0 . getKind ( ) == Kind . ERROR || t1 . getKind ( ) == Kind . ERROR ) { return Optional . of ( ErrorType . getInstance ( ) ) ; } // If either of the types isn't numeric or unknown, then this isn't valid for an arithmetic // operation. if ( ! isNumericOrUnknown ( t0 ) || ! isNumericOrUnknown ( t1 ) ) { return Optional . absent ( ) ; } // Note: everything is assignable to unknown and itself. So the first two conditions take care // of all cases but a mix of float and int. if ( t0 . isAssignableFrom ( t1 ) ) { return Optional . of ( t0 ) ; } else if ( t1 . isAssignableFrom ( t0 ) ) { return Optional . of ( t1 ) ; } else { // If we get here then we know that we have a mix of float and int. In this case arithmetic // ops always 'upgrade' to float. So just return that. return Optional . of ( FloatType . getInstance ( ) ) ; } } | Compute the most specific type that is assignable from both t0 and t1 taking into account arithmetic promotions - that is converting int to float if needed . | 278 | 32 |
30,580 | Statement detachForCall ( final Expression callRender ) { checkArgument ( callRender . resultType ( ) . equals ( RENDER_RESULT_TYPE ) ) ; final Label reattachRender = new Label ( ) ; final SaveRestoreState saveRestoreState = variables . saveRestoreState ( ) ; // We pass NULL statement for the restore logic since we handle that ourselves below int state = addState ( reattachRender , Statement . NULL_STATEMENT ) ; final Statement saveState = stateField . putInstanceField ( thisExpr , BytecodeUtils . constant ( state ) ) ; return new Statement ( ) { @ Override protected void doGen ( CodeBuilder adapter ) { // Legend: RR = RenderResult, Z = boolean callRender . gen ( adapter ) ; // Stack: RR adapter . dup ( ) ; // Stack: RR, RR MethodRef . RENDER_RESULT_IS_DONE . invokeUnchecked ( adapter ) ; // Stack: RR, Z // if isDone goto Done Label end = new Label ( ) ; adapter . ifZCmp ( Opcodes . IFNE , end ) ; // Stack: RR saveRestoreState . save ( ) . gen ( adapter ) ; saveState . gen ( adapter ) ; adapter . returnValue ( ) ; adapter . mark ( reattachRender ) ; callRender . gen ( adapter ) ; // Stack: RR adapter . dup ( ) ; // Stack: RR, RR MethodRef . RENDER_RESULT_IS_DONE . invokeUnchecked ( adapter ) ; // Stack: RR, Z // if isDone goto restore Label restore = new Label ( ) ; adapter . ifZCmp ( Opcodes . IFNE , restore ) ; // Stack: RR // no need to save or restore anything adapter . returnValue ( ) ; adapter . mark ( restore ) ; // Stack: RR saveRestoreState . restore ( ) . gen ( adapter ) ; adapter . mark ( end ) ; // Stack: RR adapter . pop ( ) ; // Stack: } } ; } | Generate detach logic for calls . | 430 | 7 |
30,581 | Statement generateReattachTable ( ) { final Expression readField = stateField . accessor ( thisExpr ) ; final Statement defaultCase = Statement . throwExpression ( MethodRef . RUNTIME_UNEXPECTED_STATE_ERROR . invoke ( readField ) ) ; return new Statement ( ) { @ Override protected void doGen ( final CodeBuilder adapter ) { int [ ] keys = new int [ reattaches . size ( ) ] ; for ( int i = 0 ; i < keys . length ; i ++ ) { keys [ i ] = i ; } readField . gen ( adapter ) ; // Generate a switch table. Note, while it might be preferable to just 'goto state', Java // doesn't allow computable gotos (probably because it makes verification impossible). So // instead we emulate that with a jump table. And anyway we still need to execute 'restore' // logic to repopulate the local variable tables, so the 'case' statements are a natural // place for that logic to live. adapter . tableSwitch ( keys , new TableSwitchGenerator ( ) { @ Override public void generateCase ( int key , Label end ) { if ( key == 0 ) { // State 0 is special, it means initial state, so we just jump to the very end adapter . goTo ( end ) ; return ; } ReattachState reattachState = reattaches . get ( key ) ; // restore and jump! reattachState . restoreStatement ( ) . gen ( adapter ) ; adapter . goTo ( reattachState . reattachPoint ( ) ) ; } @ Override public void generateDefault ( ) { defaultCase . gen ( adapter ) ; } } , // Use tableswitch instead of lookupswitch. TableSwitch is appropriate because our case // labels are sequential integers in the range [0, N). This means that switch is O(1) // and // there are no 'holes' meaning that it is compact in the bytecode. true ) ; } } ; } | Returns a statement that generates the reattach jump table . | 420 | 11 |
30,582 | private int addState ( Label reattachPoint , Statement restore ) { ReattachState create = ReattachState . create ( reattachPoint , restore ) ; reattaches . add ( create ) ; int state = reattaches . size ( ) - 1 ; // the index of the ReattachState in the list return state ; } | Add a new state item and return the state . | 69 | 10 |
30,583 | private boolean shouldProtect ( Expression operand , OperandPosition operandPosition ) { if ( operand instanceof Operation ) { Operation operation = ( Operation ) operand ; return operation . precedence ( ) < this . precedence ( ) || ( operation . precedence ( ) == this . precedence ( ) && operandPosition . shouldParenthesize ( operation . associativity ( ) ) ) ; } else if ( operand instanceof Leaf ) { // JsExprs have precedence info, but not associativity. So at least check the precedence. JsExpr expr = ( ( Leaf ) operand ) . value ( ) ; return expr . getPrecedence ( ) < this . precedence ( ) ; } else { return false ; } } | An operand needs to be protected with parens if | 154 | 12 |
30,584 | public static SimplifyVisitor create ( IdGenerator idGenerator , ImmutableList < SoyFileNode > sourceFiles ) { return new SimplifyVisitor ( idGenerator , sourceFiles , new SimplifyExprVisitor ( ) , new PreevalVisitorFactory ( ) ) ; } | Creates a new simplify visitor . | 63 | 7 |
30,585 | @ VisibleForTesting static String buildMsgContentStrForMsgIdComputation ( ImmutableList < SoyMsgPart > msgParts , boolean doUseBracedPhs ) { msgParts = IcuSyntaxUtils . convertMsgPartsToEmbeddedIcuSyntax ( msgParts ) ; StringBuilder msgStrSb = new StringBuilder ( ) ; for ( SoyMsgPart msgPart : msgParts ) { if ( msgPart instanceof SoyMsgRawTextPart ) { msgStrSb . append ( ( ( SoyMsgRawTextPart ) msgPart ) . getRawText ( ) ) ; } else if ( msgPart instanceof SoyMsgPlaceholderPart ) { if ( doUseBracedPhs ) { msgStrSb . append ( ' ' ) ; } msgStrSb . append ( ( ( SoyMsgPlaceholderPart ) msgPart ) . getPlaceholderName ( ) ) ; if ( doUseBracedPhs ) { msgStrSb . append ( ' ' ) ; } } else { throw new AssertionError ( "unexpected child: " + msgPart ) ; } } return msgStrSb . toString ( ) ; } | Private helper to build the canonical message content string that should be used for msg id computation . | 248 | 18 |
30,586 | private static String formatParseExceptionDetails ( String errorToken , List < String > expectedTokens ) { // quotes/normalize the expected tokens before rendering, just in case after normalization some // can be deduplicated. ImmutableSet . Builder < String > normalizedTokensBuilder = ImmutableSet . builder ( ) ; for ( String t : expectedTokens ) { normalizedTokensBuilder . add ( maybeQuoteForParseError ( t ) ) ; } expectedTokens = normalizedTokensBuilder . build ( ) . asList ( ) ; StringBuilder details = new StringBuilder ( ) ; int numExpectedTokens = expectedTokens . size ( ) ; if ( numExpectedTokens != 0 ) { details . append ( ": expected " ) ; for ( int i = 0 ; i < numExpectedTokens ; i ++ ) { details . append ( expectedTokens . get ( i ) ) ; if ( i < numExpectedTokens - 2 ) { details . append ( ", " ) ; } if ( i == numExpectedTokens - 2 ) { if ( numExpectedTokens > 2 ) { details . append ( ' ' ) ; } details . append ( " or " ) ; } } } return String . format ( "parse error at '%s'%s" , escapeWhitespaceForErrorPrinting ( errorToken ) , details . toString ( ) ) ; } | A helper method for formatting javacc ParseExceptions . | 287 | 13 |
30,587 | private static void maybeMarkBadProtoAccess ( ExprNode expr , SoyValue value ) { if ( value instanceof SoyProtoValue ) { ( ( SoyProtoValue ) value ) . setAccessLocationKey ( expr . getSourceLocation ( ) ) ; } } | If the value is a proto then set the current access location since we are about to access it incorrectly . | 57 | 21 |
30,588 | private static boolean isNullOrUndefinedBase ( SoyValue base ) { return base == null || base instanceof NullData || base instanceof UndefinedData || base == NullSafetySentinel . INSTANCE ; } | Returns true if the base SoyValue of a data access chain is null or undefined . | 44 | 17 |
30,589 | @ Override protected void visitFieldAccessNode ( FieldAccessNode node ) { // simplify children first visitChildren ( node ) ; ExprNode baseExpr = node . getChild ( 0 ) ; if ( baseExpr instanceof RecordLiteralNode ) { RecordLiteralNode recordLiteral = ( RecordLiteralNode ) baseExpr ; for ( int i = 0 ; i < recordLiteral . numChildren ( ) ; i ++ ) { if ( recordLiteral . getKey ( i ) . identifier ( ) . equals ( node . getFieldName ( ) ) ) { node . getParent ( ) . replaceChild ( node , recordLiteral . getChild ( i ) ) ; return ; } } // replace with null? this should have been a compiler error. } else if ( baseExpr instanceof ProtoInitNode ) { ProtoInitNode protoInit = ( ProtoInitNode ) baseExpr ; int fieldIndex = - 1 ; for ( int i = 0 ; i < protoInit . getParamNames ( ) . size ( ) ; i ++ ) { if ( protoInit . getParamNames ( ) . get ( i ) . identifier ( ) . equals ( node . getFieldName ( ) ) ) { fieldIndex = i ; break ; } } if ( fieldIndex != - 1 ) { node . getParent ( ) . replaceChild ( node , protoInit . getChild ( fieldIndex ) ) ; } else { // here we could replace with a default value or null, but for now, do nothing, rather than // implement proto default field semantics. } } } | this code since it desugars into a record literal . | 338 | 12 |
30,590 | private void attemptPreeval ( ExprNode node ) { // Note that we need to catch RenderException because preevaluation may fail, e.g. when // (a) the expression uses a bidi function that needs bidiGlobalDir to be in scope, but the // apiCallScope is not currently active, // (b) the expression uses an external function (Soy V1 syntax), // (c) other cases I haven't thought up. SoyValue preevalResult ; try { preevalResult = preevalVisitor . exec ( node ) ; } catch ( RenderException e ) { return ; // failed to preevaluate } PrimitiveNode newNode = InternalValueUtils . convertPrimitiveDataToExpr ( ( PrimitiveData ) preevalResult , node . getSourceLocation ( ) ) ; if ( newNode != null ) { node . getParent ( ) . replaceChild ( node , newNode ) ; } } | Attempts to preevaluate a node . If successful the node is replaced with a new constant node in the tree . If unsuccessful the tree is not changed . | 198 | 31 |
30,591 | static SoyValue getConstantOrNull ( ExprNode expr ) { switch ( expr . getKind ( ) ) { case NULL_NODE : return NullData . INSTANCE ; case BOOLEAN_NODE : return BooleanData . forValue ( ( ( BooleanNode ) expr ) . getValue ( ) ) ; case INTEGER_NODE : return IntegerData . forValue ( ( ( IntegerNode ) expr ) . getValue ( ) ) ; case FLOAT_NODE : return FloatData . forValue ( ( ( FloatNode ) expr ) . getValue ( ) ) ; case STRING_NODE : return StringData . forValue ( ( ( StringNode ) expr ) . getValue ( ) ) ; case GLOBAL_NODE : GlobalNode global = ( GlobalNode ) expr ; if ( global . isResolved ( ) ) { return getConstantOrNull ( global . getValue ( ) ) ; } return null ; default : return null ; } } | Returns the value of the given expression if it s constant else returns null . | 209 | 15 |
30,592 | public static < T > T visitField ( FieldDescriptor fieldDescriptor , FieldVisitor < T > visitor ) { // NOTE: map fields are technically repeated, so check isMap first. if ( fieldDescriptor . isMapField ( ) ) { List < FieldDescriptor > mapFields = fieldDescriptor . getMessageType ( ) . getFields ( ) ; checkState ( mapFields . size ( ) == 2 , "proto representation of map fields changed" ) ; FieldDescriptor keyField = mapFields . get ( 0 ) ; FieldDescriptor valueField = mapFields . get ( 1 ) ; return visitor . visitMap ( fieldDescriptor , getScalarType ( keyField , visitor ) , getScalarType ( valueField , visitor ) ) ; } else if ( fieldDescriptor . isRepeated ( ) ) { return visitor . visitRepeated ( getScalarType ( fieldDescriptor , visitor ) ) ; } else { return getScalarType ( fieldDescriptor , visitor ) ; } } | Applies the visitor to the given field . | 234 | 9 |
30,593 | static JbcSrcJavaValue error ( Expression expr , JbcSrcValueErrorReporter reporter ) { return new JbcSrcJavaValue ( expr , /* method= */ null , /* allowedType= */ null , /* constantNull= */ false , /* error= */ true , reporter ) ; } | Constructs a JbcSrcJavaValue that represents an error . | 64 | 14 |
30,594 | static JbcSrcJavaValue of ( Expression expr , JbcSrcValueErrorReporter reporter ) { if ( expr instanceof SoyExpression ) { return new JbcSrcJavaValue ( expr , /* method= */ null , /* allowedType= */ ( ( SoyExpression ) expr ) . soyType ( ) , /* constantNull= */ false , /* error= */ false , reporter ) ; } return new JbcSrcJavaValue ( expr , /* method= */ null , /* allowedType= */ null , /* constantNull= */ false , /* error= */ false , reporter ) ; } | Constructs a JbcSrcJavaValue based on the Expression . | 127 | 14 |
30,595 | static JbcSrcJavaValue of ( Expression expr , Method method , JbcSrcValueErrorReporter reporter ) { checkNotNull ( method ) ; if ( expr instanceof SoyExpression ) { return new JbcSrcJavaValue ( expr , method , /* allowedType= */ ( ( SoyExpression ) expr ) . soyType ( ) , /* constantNull= */ false , /* error= */ false , reporter ) ; } return new JbcSrcJavaValue ( expr , method , /* allowedType= */ null , /* constantNull= */ false , /* error= */ false , reporter ) ; } | Constructs a JbcSrcJavaValue based on the Expression . The method is used to display helpful error messages to the user if necessary . It is not invoked . | 129 | 34 |
30,596 | static JbcSrcJavaValue of ( SoyExpression expr , SoyType allowedType , JbcSrcValueErrorReporter reporter ) { return new JbcSrcJavaValue ( expr , /* method= */ null , checkNotNull ( allowedType ) , /* constantNull= */ false , /* error= */ false , reporter ) ; } | Constructs a JbcSrcJavaValue based on the Expression with the given SoyType as allowed types . The SoyType is expected to be based on the function signature so can be broader than the soy type of the expression itself . The expression is expected to be assignable to the type . | 72 | 59 |
30,597 | public static Class < ? > classFromAsmType ( Type type ) { Optional < Class < ? > > maybeClass = objectTypeToClassCache . getUnchecked ( type ) ; if ( ! maybeClass . isPresent ( ) ) { throw new IllegalArgumentException ( "Could not load: " + type ) ; } return maybeClass . get ( ) ; } | Returns the runtime class represented by the given type . | 78 | 10 |
30,598 | public static Expression numericConversion ( final Expression expr , final Type to ) { if ( to . equals ( expr . resultType ( ) ) ) { return expr ; } if ( ! isNumericPrimitive ( to ) || ! isNumericPrimitive ( expr . resultType ( ) ) ) { throw new IllegalArgumentException ( "Cannot convert from " + expr . resultType ( ) + " to " + to ) ; } return new Expression ( to , expr . features ( ) ) { @ Override protected void doGen ( CodeBuilder adapter ) { expr . gen ( adapter ) ; adapter . cast ( expr . resultType ( ) , to ) ; } } ; } | Returns an expression that does a numeric conversion cast from the given expression to the given type . | 143 | 18 |
30,599 | public static Expression compare ( final int comparisonOpcode , final Expression left , final Expression right ) { checkArgument ( left . resultType ( ) . equals ( right . resultType ( ) ) , "left and right must have matching types, found %s and %s" , left . resultType ( ) , right . resultType ( ) ) ; checkIntComparisonOpcode ( left . resultType ( ) , comparisonOpcode ) ; Features features = Expression . areAllCheap ( left , right ) ? Features . of ( Feature . CHEAP ) : Features . of ( ) ; return new Expression ( Type . BOOLEAN_TYPE , features ) { @ Override protected void doGen ( CodeBuilder mv ) { left . gen ( mv ) ; right . gen ( mv ) ; Label ifTrue = mv . newLabel ( ) ; Label end = mv . newLabel ( ) ; mv . ifCmp ( left . resultType ( ) , comparisonOpcode , ifTrue ) ; mv . pushBoolean ( false ) ; mv . goTo ( end ) ; mv . mark ( ifTrue ) ; mv . pushBoolean ( true ) ; mv . mark ( end ) ; } } ; } | Compares the two primitive valued expressions using the provided comparison operation . | 265 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.