idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
30,500
private static String embedCssIntoHtmlSlow ( String css , int nextReplacement , boolean searchForEndCData , boolean searchForEndTag ) { char [ ] buf = new char [ css . length ( ) + 16 ] ; int endOfPreviousReplacement = 0 ; int bufIndex = 0 ; do { int charsToCopy = nextReplacement - endOfPreviousReplacement ; buf = Chars . ensureCapacity ( buf , bufIndex + charsToCopy + 4 , 16 ) ; css . getChars ( endOfPreviousReplacement , nextReplacement , buf , bufIndex ) ; bufIndex += charsToCopy ; char c = css . charAt ( nextReplacement ) ; if ( c == ']' ) { buf [ bufIndex ++ ] = ']' ; buf [ bufIndex ++ ] = ']' ; buf [ bufIndex ++ ] = '\\' ; buf [ bufIndex ++ ] = '>' ; endOfPreviousReplacement = nextReplacement + 3 ; } else if ( c == '<' ) { buf [ bufIndex ++ ] = '<' ; buf [ bufIndex ++ ] = '\\' ; buf [ bufIndex ++ ] = '/' ; endOfPreviousReplacement = nextReplacement + 2 ; } else { throw new AssertionError ( ) ; } nextReplacement = - 1 ; if ( searchForEndTag ) { int indexOfEndTag = css . indexOf ( "</" , endOfPreviousReplacement ) ; if ( indexOfEndTag == - 1 ) { searchForEndTag = false ; } else { nextReplacement = indexOfEndTag ; } } if ( searchForEndCData ) { int indexOfEndCData = css . indexOf ( "]]>" , endOfPreviousReplacement ) ; if ( indexOfEndCData == - 1 ) { searchForEndCData = false ; } else { nextReplacement = nextReplacement == - 1 ? indexOfEndCData : Math . min ( nextReplacement , indexOfEndCData ) ; } } } while ( nextReplacement != - 1 ) ; int charsToCopy = css . length ( ) - endOfPreviousReplacement ; buf = Chars . ensureCapacity ( buf , bufIndex + charsToCopy , 16 ) ; css . getChars ( endOfPreviousReplacement , css . length ( ) , buf , bufIndex ) ; bufIndex += charsToCopy ; return new String ( buf , 0 , bufIndex ) ; }
Called when we know we need to make a replacement .
30,501
public ImmutableList < SoyMsgPart > getMsgParts ( long msgId ) { SoyMsg msg = getMsg ( msgId ) ; return msg == null ? ImmutableList . of ( ) : msg . getParts ( ) ; }
Returns the message parts or an empty array if there is no such message .
30,502
public static PyExpr concatPyExprs ( List < ? extends PyExpr > pyExprs ) { if ( pyExprs . isEmpty ( ) ) { return EMPTY_STRING ; } if ( pyExprs . size ( ) == 1 ) { return pyExprs . get ( 0 ) . toPyString ( ) ; } StringBuilder resultSb = new StringBuilder ( ) ; resultSb . append ( "[" ) ; boolean isFirst = true ; for ( PyExpr pyExpr : pyExprs ) { if ( isFirst ) { isFirst = false ; } else { resultSb . append ( ',' ) ; } resultSb . append ( pyExpr . toPyString ( ) . getText ( ) ) ; } resultSb . append ( "]" ) ; return new PyListExpr ( resultSb . toString ( ) , Integer . MAX_VALUE ) ; }
Builds one Python expression that computes the concatenation of the given Python expressions .
30,503
public static PyExpr maybeProtect ( PyExpr expr , int minSafePrecedence ) { if ( expr . getPrecedence ( ) >= minSafePrecedence ) { return expr ; } else { return new PyExpr ( "(" + expr . getText ( ) + ")" , Integer . MAX_VALUE ) ; } }
Wraps an expression with parenthesis if it s not above the minimum safe precedence .
30,504
public static PyExpr convertMapToOrderedDict ( Map < PyExpr , PyExpr > dict ) { List < String > values = new ArrayList < > ( ) ; for ( Map . Entry < PyExpr , PyExpr > entry : dict . entrySet ( ) ) { values . add ( "(" + entry . getKey ( ) . getText ( ) + ", " + entry . getValue ( ) . getText ( ) + ")" ) ; } Joiner joiner = Joiner . on ( ", " ) ; return new PyExpr ( "collections.OrderedDict([" + joiner . join ( values ) + "])" , Integer . MAX_VALUE ) ; }
Convert a java Map to valid PyExpr as dict .
30,505
public static String genExprWithNewToken ( Operator op , List < ? extends TargetExpr > operandExprs , String newToken ) { int opPrec = op . getPrecedence ( ) ; boolean isLeftAssociative = op . getAssociativity ( ) == Associativity . LEFT ; StringBuilder exprSb = new StringBuilder ( ) ; List < SyntaxElement > syntax = op . getSyntax ( ) ; for ( int i = 0 , n = syntax . size ( ) ; i < n ; i ++ ) { SyntaxElement syntaxEl = syntax . get ( i ) ; if ( syntaxEl instanceof Operand ) { int operandIndex = ( ( Operand ) syntaxEl ) . getIndex ( ) ; TargetExpr operandExpr = operandExprs . get ( operandIndex ) ; boolean needsProtection ; if ( i == ( isLeftAssociative ? 0 : n - 1 ) ) { needsProtection = operandExpr . getPrecedence ( ) < opPrec ; } else { needsProtection = operandExpr . getPrecedence ( ) <= opPrec ; } String subexpr = needsProtection ? "(" + operandExpr . getText ( ) + ")" : operandExpr . getText ( ) ; exprSb . append ( subexpr ) ; } else if ( syntaxEl instanceof Token ) { if ( newToken != null ) { exprSb . append ( newToken ) ; } else { exprSb . append ( ( ( Token ) syntaxEl ) . getValue ( ) ) ; } } else if ( syntaxEl instanceof Spacer ) { exprSb . append ( ' ' ) ; } else { throw new AssertionError ( ) ; } } return exprSb . toString ( ) ; }
Generates an expression for the given operator and operands assuming that the expression for the operator uses the same syntax format as the Soy operator with the exception that the of a different token . Associativity spacing and precedence are maintained from the original operator .
30,506
private static StaticAnalysisResult isListExpressionEmpty ( ForNode node ) { Optional < RangeArgs > rangeArgs = RangeArgs . createFromNode ( node ) ; if ( rangeArgs . isPresent ( ) ) { return isRangeExpressionEmpty ( rangeArgs . get ( ) ) ; } ExprNode expr = node . getExpr ( ) . getRoot ( ) ; if ( expr instanceof ListLiteralNode ) { return ( ( ListLiteralNode ) expr ) . numChildren ( ) > 0 ? StaticAnalysisResult . FALSE : StaticAnalysisResult . TRUE ; } return StaticAnalysisResult . UNKNOWN ; }
consider moving this to SoyTreeUtils or some similar place .
30,507
public SoyMsgBundle createFromFile ( File inputFile ) throws IOException { if ( ! inputFile . exists ( ) && FIRST_WORD_IS_EN_PATTERN . matcher ( inputFile . getName ( ) ) . matches ( ) ) { return SoyMsgBundle . EMPTY ; } try { String inputFileContent = Files . asCharSource ( inputFile , UTF_8 ) . read ( ) ; return msgPlugin . parseTranslatedMsgsFile ( inputFileContent ) ; } catch ( SoyMsgException sme ) { sme . setFileOrResourceName ( inputFile . toString ( ) ) ; throw sme ; } }
Reads a translated messages file and creates a SoyMsgBundle .
30,508
public SoyMsgBundle createFromResource ( URL inputResource ) throws IOException { try { String inputFileContent = Resources . asCharSource ( inputResource , UTF_8 ) . read ( ) ; return msgPlugin . parseTranslatedMsgsFile ( inputFileContent ) ; } catch ( SoyMsgException sme ) { sme . setFileOrResourceName ( inputResource . toString ( ) ) ; throw sme ; } }
Reads a translated messages resource and creates a SoyMsgBundle .
30,509
public HtmlCloseTagNode getCloseTagNode ( ) { if ( numChildren ( ) > 1 ) { return ( HtmlCloseTagNode ) getNodeAsHtmlTagNode ( getChild ( numChildren ( ) - 1 ) , false ) ; } return null ; }
Returns the close tag node if it exists .
30,510
public static Locale parseLocale ( String localeString ) { if ( localeString == null ) { return Locale . US ; } String [ ] groups = localeString . split ( "[-_]" ) ; switch ( groups . length ) { case 1 : return new Locale ( groups [ 0 ] ) ; case 2 : return new Locale ( groups [ 0 ] , Ascii . toUpperCase ( groups [ 1 ] ) ) ; case 3 : return new Locale ( groups [ 0 ] , Ascii . toUpperCase ( groups [ 1 ] ) , groups [ 2 ] ) ; default : throw new IllegalArgumentException ( "Malformed localeString: " + localeString ) ; } }
Given a string representing a Locale returns the Locale object for that string .
30,511
public < T > void updateRefs ( T oldObject , T newObject ) { checkNotNull ( oldObject ) ; checkNotNull ( newObject ) ; checkArgument ( ! ( newObject instanceof Listener ) ) ; Object previousMapping = mappings . put ( oldObject , newObject ) ; if ( previousMapping != null ) { if ( previousMapping instanceof Listener ) { @ SuppressWarnings ( "unchecked" ) Listener < T > listener = ( Listener < T > ) previousMapping ; listener . newVersion ( newObject ) ; } else { throw new IllegalStateException ( "found multiple remappings for " + oldObject ) ; } } }
Registers that the old object has been remapped to the new object .
30,512
public void checkAllListenersFired ( ) { for ( Map . Entry < Object , Object > entry : mappings . entrySet ( ) ) { if ( entry . getValue ( ) instanceof Listener ) { throw new IllegalStateException ( "Listener for " + entry . getKey ( ) + " never fired: " + entry . getValue ( ) ) ; } } }
Asserts that there are no pending listeners .
30,513
public static String unescapeHtml ( String s ) { int amp = s . indexOf ( '&' ) ; if ( amp < 0 ) { return s ; } int n = s . length ( ) ; StringBuilder sb = new StringBuilder ( n ) ; int pos = 0 ; do { int end = - 1 ; int entityLimit = Math . min ( n , amp + 12 ) ; for ( int i = amp + 1 ; i < entityLimit ; ++ i ) { if ( s . charAt ( i ) == ';' ) { end = i + 1 ; break ; } } int cp = - 1 ; if ( end == - 1 ) { cp = - 1 ; } else { if ( s . charAt ( amp + 1 ) == '#' ) { char ch = s . charAt ( amp + 2 ) ; try { if ( ch == 'x' || ch == 'X' ) { cp = Integer . parseInt ( s . substring ( amp + 3 , end - 1 ) , 16 ) ; } else { cp = Integer . parseInt ( s . substring ( amp + 2 , end - 1 ) , 10 ) ; } } catch ( NumberFormatException ex ) { cp = - 1 ; } } else { Integer cpI = HTML_ENTITY_TO_CODEPOINT . get ( s . substring ( amp , end ) ) ; cp = cpI != null ? cpI . intValue ( ) : - 1 ; } } if ( cp == - 1 ) { end = amp + 1 ; } else { sb . append ( s , pos , amp ) ; sb . appendCodePoint ( cp ) ; pos = end ; } amp = s . indexOf ( '&' , end ) ; } while ( amp >= 0 ) ; return sb . append ( s , pos , n ) . toString ( ) ; }
Replace all the occurrences of HTML entities with the appropriate code - points .
30,514
private List < String > genPySrc ( SoyFileSetNode soyTree , SoyPySrcOptions pySrcOptions , ImmutableMap < String , String > currentManifest , ErrorReporter errorReporter ) { BidiGlobalDir bidiGlobalDir = SoyBidiUtils . decodeBidiGlobalDirFromPyOptions ( pySrcOptions . getBidiIsRtlFn ( ) ) ; try ( SoyScopedData . InScope inScope = apiCallScope . enter ( null , bidiGlobalDir ) ) { return createVisitor ( pySrcOptions , inScope . getBidiGlobalDir ( ) , errorReporter , currentManifest ) . gen ( soyTree , errorReporter ) ; } }
Generates Python source code given a Soy parse tree and an options object .
30,515
public void genPyFiles ( SoyFileSetNode soyTree , SoyPySrcOptions pySrcOptions , String outputPathFormat , ErrorReporter errorReporter ) throws IOException { ImmutableList < SoyFileNode > srcsToCompile = ImmutableList . copyOf ( soyTree . getChildren ( ) ) ; List < String > soyNamespaces = getSoyNamespaces ( soyTree ) ; Multimap < String , Integer > outputs = MainEntryPointUtils . mapOutputsToSrcs ( null , outputPathFormat , srcsToCompile ) ; ImmutableMap < String , String > manifest = generateManifest ( soyNamespaces , outputs ) ; List < String > pyFileContents = genPySrc ( soyTree , pySrcOptions , manifest , errorReporter ) ; if ( srcsToCompile . size ( ) != pyFileContents . size ( ) ) { throw new AssertionError ( String . format ( "Expected to generate %d code chunk(s), got %d" , srcsToCompile . size ( ) , pyFileContents . size ( ) ) ) ; } for ( String outputFilePath : outputs . keySet ( ) ) { try ( Writer out = Files . newWriter ( new File ( outputFilePath ) , StandardCharsets . UTF_8 ) ) { for ( int inputFileIndex : outputs . get ( outputFilePath ) ) { out . write ( pyFileContents . get ( inputFileIndex ) ) ; } } } if ( pySrcOptions . namespaceManifestFile ( ) != null ) { try ( Writer out = Files . newWriter ( new File ( pySrcOptions . namespaceManifestFile ( ) ) , StandardCharsets . UTF_8 ) ) { Properties prop = new Properties ( ) ; for ( String namespace : manifest . keySet ( ) ) { prop . put ( namespace , manifest . get ( namespace ) ) ; } prop . store ( out , null ) ; } } }
Generates Python source files given a Soy parse tree an options object and information on where to put the output files .
30,516
private static ImmutableMap < String , String > generateManifest ( List < String > soyNamespaces , Multimap < String , Integer > outputs ) { ImmutableMap . Builder < String , String > manifest = new ImmutableMap . Builder < > ( ) ; for ( String outputFilePath : outputs . keySet ( ) ) { for ( int inputFileIndex : outputs . get ( outputFilePath ) ) { String pythonPath = outputFilePath . replace ( ".py" , "" ) . replace ( '/' , '.' ) ; manifest . put ( soyNamespaces . get ( inputFileIndex ) , pythonPath ) ; } } return manifest . build ( ) ; }
Generate the manifest file by finding the output file paths and converting them into a Python import format .
30,517
public void check ( SoyFileNode file , final ErrorReporter errorReporter ) { final List < Rule < ? > > rulesForFile = new ArrayList < > ( rules . size ( ) ) ; String filePath = file . getFilePath ( ) ; for ( RuleWithWhitelists rule : rules ) { if ( rule . shouldCheckConformanceFor ( filePath ) ) { rulesForFile . add ( rule . getRule ( ) ) ; } } if ( rulesForFile . isEmpty ( ) ) { return ; } SoyTreeUtils . visitAllNodes ( file , new NodeVisitor < Node , VisitDirective > ( ) { public VisitDirective exec ( Node node ) { for ( Rule < ? > rule : rulesForFile ) { rule . checkConformance ( node , errorReporter ) ; } return VisitDirective . CONTINUE ; } } ) ; }
Performs the overall check .
30,518
public static SoyType getTypeForContentKind ( SanitizedContentKind contentKind ) { switch ( contentKind ) { case ATTRIBUTES : return AttributesType . getInstance ( ) ; case CSS : return StyleType . getInstance ( ) ; case HTML : return HtmlType . getInstance ( ) ; case JS : return JsType . getInstance ( ) ; case URI : return UriType . getInstance ( ) ; case TRUSTED_RESOURCE_URI : return TrustedResourceUriType . getInstance ( ) ; case TEXT : return StringType . getInstance ( ) ; } throw new AssertionError ( contentKind ) ; }
Given a content kind return the corresponding soy type .
30,519
private static < T > T instantiateObject ( String flagName , String objectType , Class < T > clazz , PluginLoader loader , String instanceClassName ) { try { return loader . loadPlugin ( instanceClassName ) . asSubclass ( clazz ) . getConstructor ( ) . newInstance ( ) ; } catch ( ClassCastException cce ) { throw new CommandLineError ( String . format ( "%s \"%s\" is not a subclass of %s. Classes passed to %s should be %ss. " + "Did you pass it to the wrong flag?" , objectType , instanceClassName , clazz . getSimpleName ( ) , flagName , clazz . getSimpleName ( ) ) , cce ) ; } catch ( ReflectiveOperationException e ) { throw new CommandLineError ( String . format ( "Cannot instantiate %s \"%s\" registered with flag %s. Please make " + "sure that the %s exists and is on the compiler classpath and has a public " + "zero arguments constructor." , objectType , instanceClassName , flagName , objectType ) , e ) ; } catch ( ExceptionInInitializerError e ) { throw new CommandLineError ( String . format ( "Cannot instantiate %s \"%s\" registered with flag %s. An error was thrown while " + "loading the class. There is a bug in the implementation." , objectType , instanceClassName , flagName ) , e ) ; } catch ( SecurityException e ) { throw new CommandLineError ( String . format ( "Cannot instantiate %s \"%s\" registered with flag %s. A security manager is " + "preventing instantiation." , objectType , instanceClassName , flagName ) , e ) ; } }
Private helper for creating objects from flags .
30,520
public JsCodeBuilder addChunksToOutputVar ( List < ? extends Expression > codeChunks ) { if ( currOutputVarIsInited ) { Expression rhs = CodeChunkUtils . concatChunks ( codeChunks ) ; rhs . collectRequires ( requireCollector ) ; appendLine ( currOutputVar . plusEquals ( rhs ) . getCode ( ) ) ; } else { Expression rhs = CodeChunkUtils . concatChunksForceString ( codeChunks ) ; rhs . collectRequires ( requireCollector ) ; append ( VariableDeclaration . builder ( currOutputVar . singleExprOrName ( ) . getText ( ) ) . setRhs ( rhs ) . build ( ) ) ; setOutputVarInited ( ) ; } return this ; }
Appends one or more lines representing the concatenation of the values of the given code chunks saved to the current output variable .
30,521
private JsCodeBuilder changeIndentHelper ( int chg ) { int newIndentDepth = indent . length ( ) + chg * INDENT_SIZE ; Preconditions . checkState ( newIndentDepth >= 0 ) ; indent = Strings . repeat ( " " , newIndentDepth ) ; return this ; }
Helper for the various indent methods .
30,522
static SanitizedContent create ( String content , ContentKind kind ) { checkArgument ( kind != ContentKind . TEXT , "Use UnsanitizedString for SanitizedContent with a kind of TEXT" ) ; if ( Flags . stringIsNotSanitizedContent ( ) ) { return new SanitizedContent ( content , kind , kind . getDefaultDir ( ) ) ; } return SanitizedCompatString . create ( content , kind , kind . getDefaultDir ( ) ) ; }
Creates a SanitizedContent object with default direction .
30,523
public static StreamingEscaper create ( LoggingAdvisingAppendable delegate , CrossLanguageStringXform transform ) { if ( delegate instanceof StreamingEscaper ) { StreamingEscaper delegateAsStreamingEscaper = ( StreamingEscaper ) delegate ; if ( delegateAsStreamingEscaper . transform == transform ) { return delegateAsStreamingEscaper ; } } return new StreamingEscaper ( delegate , transform ) ; }
Creates a streaming escaper or returns the delegate if it is already escaping with the same settings .
30,524
public void onResolve ( ResolutionCallback callback ) { checkState ( this . resolveCallback == null , "callback has already been set." ) ; checkState ( this . value == null , "value is resolved." ) ; this . resolveCallback = checkNotNull ( callback ) ; }
Registers a callback that is invoked when this global is resolved to its actual value .
30,525
public static Statement assign ( Expression lhs , Expression rhs ) { return Assignment . create ( lhs , rhs , null ) ; }
Creates a code chunk that assigns value to a preexisting variable with the given name .
30,526
public static Statement assign ( Expression lhs , Expression rhs , JsDoc jsDoc ) { return Assignment . create ( lhs , rhs , jsDoc ) ; }
Creates a code chunk that assigns and prints jsDoc above the assignment .
30,527
public static Statement forLoop ( String localVar , Expression limit , Statement body ) { return For . create ( localVar , Expression . number ( 0 ) , limit , Expression . number ( 1 ) , body ) ; }
Creates a code chunk representing a for loop with default values for initial & increment .
30,528
public static Optional < CompiledTemplates > compile ( final TemplateRegistry registry , final SoyFileSetNode fileSet , boolean developmentMode , ErrorReporter reporter , ImmutableMap < String , SoyFileSupplier > filePathsToSuppliers , SoyTypeRegistry typeRegistry ) { final Stopwatch stopwatch = Stopwatch . createStarted ( ) ; ErrorReporter . Checkpoint checkpoint = reporter . checkpoint ( ) ; if ( reporter . errorsSince ( checkpoint ) ) { return Optional . absent ( ) ; } CompiledTemplateRegistry compilerRegistry = new CompiledTemplateRegistry ( registry ) ; if ( developmentMode ) { CompiledTemplates templates = new CompiledTemplates ( compilerRegistry . getDelegateTemplateNames ( ) , new CompilingClassLoader ( compilerRegistry , fileSet , filePathsToSuppliers , typeRegistry ) ) ; if ( reporter . errorsSince ( checkpoint ) ) { return Optional . absent ( ) ; } return Optional . of ( templates ) ; } List < ClassData > classes = compileTemplates ( compilerRegistry , fileSet , reporter , typeRegistry , new CompilerListener < List < ClassData > > ( ) { final List < ClassData > compiledClasses = new ArrayList < > ( ) ; int numBytes = 0 ; int numFields = 0 ; int numDetachStates = 0 ; public void onCompile ( ClassData clazz ) { numBytes += clazz . data ( ) . length ; numFields += clazz . numberOfFields ( ) ; numDetachStates += clazz . numberOfDetachStates ( ) ; compiledClasses . add ( clazz ) ; } public List < ClassData > getResult ( ) { logger . log ( Level . FINE , "Compilation took {0}\n" + " templates: {1}\n" + " classes: {2}\n" + " bytes: {3}\n" + " fields: {4}\n" + " detachStates: {5}" , new Object [ ] { stopwatch . toString ( ) , registry . getAllTemplates ( ) . size ( ) , compiledClasses . size ( ) , numBytes , numFields , numDetachStates } ) ; return compiledClasses ; } } ) ; if ( reporter . errorsSince ( checkpoint ) ) { return Optional . absent ( ) ; } CompiledTemplates templates = new CompiledTemplates ( compilerRegistry . getDelegateTemplateNames ( ) , new MemoryClassLoader ( classes ) ) ; stopwatch . reset ( ) . start ( ) ; templates . loadAll ( compilerRegistry . getTemplateNames ( ) ) ; logger . log ( Level . FINE , "Loaded all classes in {0}" , stopwatch ) ; return Optional . of ( templates ) ; }
Compiles all the templates in the given registry .
30,529
public void invokeUnchecked ( CodeBuilder cb ) { cb . visitMethodInsn ( opcode ( ) , owner ( ) . internalName ( ) , method ( ) . getName ( ) , method ( ) . getDescriptor ( ) , opcode ( ) == Opcodes . INVOKEINTERFACE ) ; }
Writes an invoke instruction for this method to the given adapter . Useful when the expression is not useful for representing operations . For example explicit dup operations are awkward in the Expression api .
30,530
protected static SoyData createFromExistingData ( Object obj ) { if ( obj instanceof SoyData ) { return ( SoyData ) obj ; } else if ( obj instanceof Map < ? , ? > ) { @ SuppressWarnings ( "unchecked" ) Map < String , ? > objCast = ( Map < String , ? > ) obj ; return new SoyMapData ( objCast ) ; } else if ( obj instanceof Iterable < ? > ) { return new SoyListData ( ( Iterable < ? > ) obj ) ; } else if ( obj instanceof Future < ? > ) { try { return createFromExistingData ( ( ( Future < ? > ) obj ) . get ( ) ) ; } catch ( InterruptedException e ) { throw new SoyDataException ( "Encountered InterruptedException when resolving Future object." , e ) ; } catch ( ExecutionException e ) { throw new SoyDataException ( "Encountered ExecutionException when resolving Future object." , e ) ; } } else { SoyValue soyValue = SoyValueConverter . INSTANCE . convert ( obj ) . resolve ( ) ; if ( soyValue instanceof SoyData ) { return ( SoyData ) soyValue ; } throw new SoyDataException ( "Attempting to convert unrecognized object to Soy data (object type " + obj . getClass ( ) . getName ( ) + ")." ) ; } }
Creates deprecated SoyData objects from standard Java data structures .
30,531
public static boolean hasPlrselPart ( List < SoyMsgPart > msgParts ) { for ( SoyMsgPart origMsgPart : msgParts ) { if ( origMsgPart instanceof SoyMsgPluralPart || origMsgPart instanceof SoyMsgSelectPart ) { return true ; } } return false ; }
Checks whether a given list of msg parts has any plural or select parts .
30,532
public void set ( int index , SoyData value ) { if ( index == list . size ( ) ) { list . add ( ensureValidValue ( value ) ) ; } else { list . set ( index , ensureValidValue ( value ) ) ; } }
Sets a data value at a given index .
30,533
public SoyData get ( int index ) { try { return list . get ( index ) ; } catch ( IndexOutOfBoundsException ioobe ) { return null ; } }
Gets the data value at a given index .
30,534
public static String getDidYouMeanMessage ( Iterable < String > allNames , String wrongName ) { String closestName = getClosest ( allNames , wrongName ) ; if ( closestName != null ) { return String . format ( " Did you mean '%s'?" , closestName ) ; } return "" ; }
Given a collection of strings and a name that isn t contained in it . Return a message that suggests one of the names .
30,535
private static int distance ( String s , String t , int maxDistance ) { int [ ] v0 = new int [ t . length ( ) + 1 ] ; int [ ] v1 = new int [ t . length ( ) + 1 ] ; for ( int i = 0 ; i < v0 . length ; i ++ ) { v0 [ i ] = i ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { v1 [ 0 ] = i + 1 ; int bestThisRow = v1 [ 0 ] ; char sChar = Ascii . toLowerCase ( s . charAt ( i ) ) ; for ( int j = 0 ; j < t . length ( ) ; j ++ ) { char tChar = Ascii . toLowerCase ( t . charAt ( j ) ) ; v1 [ j + 1 ] = Math . min ( v1 [ j ] + 1 , Math . min ( v0 [ j + 1 ] + 1 , v0 [ j ] + ( ( sChar == tChar ) ? 0 : 1 ) ) ) ; bestThisRow = Math . min ( bestThisRow , v1 [ j + 1 ] ) ; } if ( bestThisRow > maxDistance ) { return maxDistance + 1 ; } int [ ] tmp = v0 ; v0 = v1 ; v1 = tmp ; } return v0 [ t . length ( ) ] ; }
Performs a case insensitive Levenshtein edit distance based on the 2 rows implementation .
30,536
public static String formatErrors ( Iterable < SoyError > errors ) { int numErrors = 0 ; int numWarnings = 0 ; for ( SoyError error : errors ) { if ( error . isWarning ( ) ) { numWarnings ++ ; } else { numErrors ++ ; } } if ( numErrors + numWarnings == 0 ) { throw new IllegalArgumentException ( "cannot format 0 errors" ) ; } StringBuilder sb = new StringBuilder ( numErrors == 0 ? "warnings" : "errors" ) . append ( " during Soy compilation\n" ) ; Joiner . on ( '\n' ) . appendTo ( sb , errors ) ; if ( numErrors > 0 ) { formatNumber ( numErrors , "error" , sb ) ; } if ( numWarnings > 0 ) { if ( numErrors > 0 ) { sb . append ( ' ' ) ; } formatNumber ( numWarnings , "warning" , sb ) ; } return sb . append ( '\n' ) . toString ( ) ; }
Formats the errors in a standard way for displaying to a user .
30,537
public void prependKeyToDataPath ( String key ) { if ( dataPath == null ) { dataPath = key ; } else { dataPath = key + ( ( dataPath . charAt ( 0 ) == '[' ) ? "" : "." ) + dataPath ; } }
Prepends a key to the data path where this error occurred . E . g . if the dataPath was previously foo . goo and the key to prepend is boo then the new data path will be boo . foo . goo .
30,538
public Type type ( ) { int dotIndex = identifier ( ) . indexOf ( '.' ) ; if ( dotIndex == 0 ) { checkArgument ( BaseUtils . isIdentifierWithLeadingDot ( identifier ( ) ) ) ; return Type . DOT_IDENT ; } else { checkArgument ( BaseUtils . isDottedIdentifier ( identifier ( ) ) ) ; return dotIndex == - 1 ? Type . SINGLE_IDENT : Type . DOTTED_IDENT ; } }
This field is only rarely accessed memoize it .
30,539
public Identifier extractPartAfterLastDot ( ) { String part = BaseUtils . extractPartAfterLastDot ( identifier ( ) ) ; return Identifier . create ( part , location ( ) . offsetStartCol ( identifier ( ) . length ( ) - part . length ( ) ) ) ; }
Gets the part after the last dot in a dotted identifier . If there are no dots returns the whole identifier .
30,540
public static PrimitiveNode convertPrimitiveDataToExpr ( PrimitiveData primitiveData , SourceLocation location ) { if ( primitiveData instanceof StringData ) { return new StringNode ( primitiveData . stringValue ( ) , QuoteStyle . SINGLE , location ) ; } else if ( primitiveData instanceof BooleanData ) { return new BooleanNode ( primitiveData . booleanValue ( ) , location ) ; } else if ( primitiveData instanceof IntegerData ) { if ( ! IntegerNode . isInRange ( primitiveData . longValue ( ) ) ) { return null ; } else { return new IntegerNode ( primitiveData . longValue ( ) , location ) ; } } else if ( primitiveData instanceof FloatData ) { return new FloatNode ( primitiveData . floatValue ( ) , location ) ; } else if ( primitiveData instanceof NullData ) { return new NullNode ( location ) ; } else { throw new IllegalArgumentException ( ) ; } }
Converts a primitive data object into a primitive expression node .
30,541
public static PrimitiveData convertPrimitiveExprToData ( PrimitiveNode primitiveNode ) { if ( primitiveNode instanceof StringNode ) { return StringData . forValue ( ( ( StringNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof BooleanNode ) { return BooleanData . forValue ( ( ( BooleanNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof IntegerNode ) { return IntegerData . forValue ( ( ( IntegerNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof FloatNode ) { return FloatData . forValue ( ( ( FloatNode ) primitiveNode ) . getValue ( ) ) ; } else if ( primitiveNode instanceof NullNode ) { return NullData . INSTANCE ; } else { throw new IllegalArgumentException ( ) ; } }
Converts a primitive expression node into a primitive data object .
30,542
public static ImmutableMap < String , PrimitiveData > convertCompileTimeGlobalsMap ( Map < String , ? > compileTimeGlobalsMap ) { ImmutableMap . Builder < String , PrimitiveData > resultMapBuilder = ImmutableMap . builder ( ) ; for ( Map . Entry < String , ? > entry : compileTimeGlobalsMap . entrySet ( ) ) { Object valueObj = entry . getValue ( ) ; PrimitiveData value ; boolean isValidValue = true ; try { SoyValue value0 = SoyValueConverter . INSTANCE . convert ( valueObj ) . resolve ( ) ; if ( ! ( value0 instanceof PrimitiveData ) ) { isValidValue = false ; } value = ( PrimitiveData ) value0 ; } catch ( SoyDataException sde ) { isValidValue = false ; value = null ; } if ( ! isValidValue ) { throw new IllegalArgumentException ( "Compile-time globals map contains invalid value: " + valueObj + " for key: " + entry . getKey ( ) ) ; } resultMapBuilder . put ( entry . getKey ( ) , value ) ; } return resultMapBuilder . build ( ) ; }
Converts a compile - time globals map in user - provided format into one in the internal format .
30,543
boolean shouldCheckConformanceFor ( String filePath ) { for ( String whitelistedPath : getWhitelistedPaths ( ) ) { if ( filePath . contains ( whitelistedPath ) ) { return false ; } } ImmutableList < String > onlyApplyToPaths = getOnlyApplyToPaths ( ) ; if ( onlyApplyToPaths . isEmpty ( ) ) { return true ; } for ( String onlyApplyToPath : onlyApplyToPaths ) { if ( filePath . contains ( onlyApplyToPath ) ) { return true ; } } return false ; }
A file should be checked against a rule unless it contains one of the whitelisted paths .
30,544
private static boolean isEmpty ( MsgNode msg ) { for ( SoyNode child : msg . getChildren ( ) ) { if ( child instanceof RawTextNode && ( ( RawTextNode ) child ) . getRawText ( ) . isEmpty ( ) ) { continue ; } return false ; } return true ; }
If the only children are empty raw text nodes then the node is empty .
30,545
public void setEscapingDirectives ( SoyNode node , Context context , List < EscapingMode > escapingModes ) { Preconditions . checkArgument ( ( node instanceof PrintNode ) || ( node instanceof CallNode ) || ( node instanceof MsgFallbackGroupNode ) , "Escaping directives may only be set for {print}, {msg}, or {call} nodes" ) ; if ( escapingModes != null ) { nodeToEscapingModes . put ( node , ImmutableList . copyOf ( escapingModes ) ) ; } nodeToContext . put ( node , context ) ; }
Records inferred escaping modes so a directive can be later added to the Soy parse tree .
30,546
public ImmutableList < EscapingMode > getEscapingModesForNode ( SoyNode node ) { ImmutableList < EscapingMode > modes = nodeToEscapingModes . get ( node ) ; if ( modes == null ) { modes = ImmutableList . of ( ) ; } return modes ; }
The escaping modes for the print command with the given ID in the order in which they should be applied .
30,547
static SoyMsgBundle parseXliffTargetMsgs ( String xliffContent ) throws SAXException { SAXParserFactory saxParserFactory = SAXParserFactory . newInstance ( ) ; SAXParser saxParser ; try { saxParser = saxParserFactory . newSAXParser ( ) ; } catch ( ParserConfigurationException pce ) { throw new AssertionError ( "Could not get SAX parser for XML." ) ; } XliffSaxHandler xliffSaxHandler = new XliffSaxHandler ( ) ; try { saxParser . parse ( new InputSource ( new StringReader ( xliffContent ) ) , xliffSaxHandler ) ; } catch ( IOException e ) { throw new AssertionError ( "Should not fail in reading a string." ) ; } return new SoyMsgBundleImpl ( xliffSaxHandler . getTargetLocaleString ( ) , xliffSaxHandler . getMsgs ( ) ) ; }
Parses the content of a translated XLIFF file and creates a SoyMsgBundle .
30,548
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
30,549
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 ( ) ; Expression startExpression = MethodRef . INTS_CHECKED_CAST . invoke ( exprCompiler . compile ( expression . get ( ) , startDetachPoint ) . unboxAsLong ( ) ) ; if ( ! startExpression . isCheap ( ) ) { Variable startVar = scope . createSynthetic ( varName , startExpression , STORE ) ; initStatements . add ( startVar . initializer ( ) . labelStart ( startDetachPoint ) ) ; startExpression = startVar . local ( ) ; } return startExpression ; } }
Computes a single range argument .
30,550
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 .
30,551
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 ) { 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 .
30,552
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 .
30,553
public synchronized void put ( String fileName , VersionedFile versionedFile ) { cache . put ( fileName , versionedFile . copy ( ) ) ; }
Stores a cached version of the AST .
30,554
public synchronized VersionedFile get ( String fileName , Version version ) { VersionedFile entry = cache . get ( fileName ) ; if ( entry != null ) { if ( entry . version ( ) . equals ( version ) ) { return entry . copy ( ) ; } else { cache . remove ( fileName ) ; } } return null ; }
Retrieves a cached version of this file supplier AST if any .
30,555
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 .
30,556
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 .
30,557
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 .
30,558
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 .
30,559
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 .
30,560
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 .
30,561
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 .
30,562
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 .
30,563
static boolean shouldCheckFieldPresenceToEmulateJspbNullability ( FieldDescriptor desc ) { boolean hasBrokenSemantics = false ; if ( desc . hasDefaultValue ( ) || desc . isRepeated ( ) ) { return false ; } else if ( desc . getFile ( ) . getSyntax ( ) == Syntax . PROTO3 || ! hasBrokenSemantics ) { 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 .
30,564
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 .
30,565
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 .
30,566
@ SuppressWarnings ( "unchecked" ) 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 .
30,567
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
30,568
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 .
30,569
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 .
30,570
@ SuppressWarnings ( "unused" ) public static final String calculateFullCalleeName ( Identifier ident , SoyFileHeaderInfo header , ErrorReporter errorReporter ) { String name = ident . identifier ( ) ; switch ( ident . type ( ) ) { case DOT_IDENT : return header . getNamespace ( ) + name ; case DOTTED_IDENT : return header . resolveAlias ( name ) ; case SINGLE_IDENT : if ( header . hasAlias ( name ) ) { errorReporter . report ( ident . location ( ) , CALL_COLLIDES_WITH_NAMESPACE_ALIAS , name ) ; } else { 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 .
30,571
@ SuppressWarnings ( "unused" ) 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 .
30,572
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 'n' : sb . append ( '\n' ) ; break ; case 'r' : sb . append ( '\r' ) ; break ; case 't' : sb . append ( '\t' ) ; break ; case 'b' : sb . append ( '\b' ) ; break ; case 'f' : sb . append ( '\f' ) ; break ; case '\\' : case '\"' : case '\'' : case '>' : sb . append ( c ) ; break ; case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : -- i ; int nOctalDigits = 1 ; int digitLimit = c < '4' ? 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 'x' : case 'u' : String hexCode ; int nHexDigits = ( c == 'u' ? 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 .
30,573
static String unescapeCommandAttributeValue ( String s , QuoteStyle quoteStyle ) { 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 .
30,574
public void defineField ( ClassVisitor cv ) { cv . visitField ( accessFlags ( ) , name ( ) , type ( ) . getDescriptor ( ) , null , null ) ; }
Defines the given field as member of the class .
30,575
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 ) { 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 .
30,576
public Expression accessor ( ) { checkState ( isStatic ( ) ) ; Features features = Features . of ( Feature . CHEAP ) ; if ( ! isNullable ( ) ) { features = features . plus ( Feature . NON_NULLABLE ) ; } return new Expression ( type ( ) , features ) { protected void doGen ( CodeBuilder mv ) { accessStaticUnchecked ( mv ) ; } } ; }
Returns an expression that accesses this static field .
30,577
void accessStaticUnchecked ( CodeBuilder mv ) { checkState ( isStatic ( ) ) ; mv . getStatic ( owner ( ) . type ( ) , FieldRef . this . name ( ) , type ( ) ) ; }
Accesses a static field .
30,578
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 .
30,579
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 .
30,580
private int processNextToken ( RawTextNode node , final int offset , String text ) { 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 ) ; 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 ) { 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 ; 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 , node . substring ( Integer . MAX_VALUE , 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 .
30,581
private static UriPart getNextUriPart ( RawTextNode node , int offset , UriPart uriPart , char matchChar ) { switch ( uriPart ) { case MAYBE_SCHEME : case MAYBE_VARIABLE_SCHEME : if ( matchChar == ':' ) { if ( uriPart == UriPart . MAYBE_VARIABLE_SCHEME ) { throw SoyAutoescapeException . createWithNode ( "Soy can't safely process a URI that might start with a variable scheme. " + "For example, {$x}:{$y} could have an XSS if $x is 'javascript' and $y is " + "attacker-controlled. Either use a hard-coded scheme, or introduce " + "disambiguating characters (e.g. http://{$x}:{$y}, ./{$x}:{$y}, or " + "{$x}?foo=:{$y})" , node . substring ( Integer . MAX_VALUE , offset ) ) ; } else { return UriPart . AUTHORITY_OR_PATH ; } } if ( matchChar == '/' ) { return UriPart . AUTHORITY_OR_PATH ; } if ( ( matchChar == '=' || matchChar == '&' ) && uriPart == UriPart . MAYBE_VARIABLE_SCHEME ) { return UriPart . QUERY ; } case AUTHORITY_OR_PATH : case UNKNOWN_PRE_FRAGMENT : if ( matchChar == '?' ) { return UriPart . QUERY ; } case QUERY : case UNKNOWN : if ( matchChar == '#' ) { return UriPart . FRAGMENT ; } case FRAGMENT : return uriPart ; case DANGEROUS_SCHEME : return UriPart . DANGEROUS_SCHEME ; case TRUSTED_RESOURCE_URI_END : throw new AssertionError ( "impossible" ) ; case NONE : case START : } throw new AssertionError ( "Unanticipated URI part: " + uriPart ) ; }
Matching at the end is lowest possible precedence .
30,582
public static Expression fromExpr ( JsExpr expr , Iterable < GoogRequire > requires ) { return Leaf . create ( expr , false , requires ) ; }
Creates a new code chunk from the given expression . The expression s precedence is preserved .
30,583
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 , false ) ; }
Creates a code chunk representing a JavaScript regular expression literal .
30,584
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 ) , true ) ; }
Creates a code chunk representing a JavaScript number literal .
30,585
public static Expression function ( JsDoc parameters , Statement body ) { return FunctionDeclaration . create ( parameters , body ) ; }
Creates a code chunk representing an anonymous function literal .
30,586
public static Expression arrowFunction ( JsDoc parameters , Statement body ) { return FunctionDeclaration . createArrowFunction ( parameters , body ) ; }
Creates a code chunk representing an arrow function .
30,587
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 .
30,588
public static Expression arrayLiteral ( Iterable < ? extends Expression > elements ) { return ArrayLiteral . create ( ImmutableList . copyOf ( elements ) ) ; }
Creates a code chunk representing a javascript array literal .
30,589
public final Expression withInitialStatements ( Iterable < ? extends Statement > initialStatements ) { if ( Iterables . isEmpty ( initialStatements ) ) { return this ; } 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 .
30,590
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 .
30,591
public static SoyType of ( Collection < SoyType > members ) { ImmutableSortedSet . Builder < SoyType > builder = ImmutableSortedSet . orderedBy ( MEMBER_ORDER ) ; for ( SoyType type : members ) { 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 .
30,592
public boolean isNullable ( ) { return members . stream ( ) . anyMatch ( t -> t . getKind ( ) == SoyType . Kind . NULL ) ; }
Returns true if the union includes the null type .
30,593
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 .
30,594
public void addChild ( N child ) { checkNotNull ( child ) ; tryRemoveFromOldParent ( child ) ; children . add ( child ) ; child . setParent ( master ) ; }
Adds the given child .
30,595
public void removeChild ( int index ) { N child = children . remove ( index ) ; child . setParent ( null ) ; }
Removes the child at the given index .
30,596
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 .
30,597
public void clearChildren ( ) { for ( int i = 0 ; i < children . size ( ) ; i ++ ) { children . get ( i ) . setParent ( null ) ; } children . clear ( ) ; }
Clears the list of children .
30,598
@ SuppressWarnings ( "unchecked" ) public void addChildren ( List < ? extends N > children ) { for ( Node child : children . toArray ( new Node [ 0 ] ) ) { addChild ( ( N ) child ) ; } }
Adds the given children .
30,599
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 .