GLSLDecoder.js 22 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. import { Program, FunctionDeclaration, Switch, For, AccessorElements, Ternary, Varying, DynamicElement, StaticElement, FunctionParameter, Unary, Conditional, VariableDeclaration, Operator, Number, String, FunctionCall, Return, Accessor, Uniform, Discard, SwitchCase, Continue, Break, While, Comment } from './AST.js';
  2. const unaryOperators = [
  3. '+', '-', '~', '!', '++', '--'
  4. ];
  5. const arithmeticOperators = [
  6. '*', '/', '%', '+', '-', '<<', '>>'
  7. ];
  8. const precedenceOperators = [
  9. '*', '/', '%',
  10. '-', '+',
  11. '<<', '>>',
  12. '<', '>', '<=', '>=',
  13. '==', '!=',
  14. '&',
  15. '^',
  16. '|',
  17. '&&',
  18. '^^',
  19. '||',
  20. '?',
  21. '=',
  22. '+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '<<=', '>>=',
  23. ','
  24. ].reverse();
  25. const associativityRightToLeft = [
  26. '=',
  27. '+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '<<=', '>>=',
  28. ',',
  29. '?',
  30. ':'
  31. ];
  32. const glslToTSL = {
  33. inversesqrt: 'inverseSqrt'
  34. };
  35. const samplers = [ 'sampler1D', 'sampler2D', 'sampler2DArray', 'sampler2DShadow', 'sampler2DArrayShadow', 'isampler2D', 'isampler2DArray', 'usampler2D', 'usampler2DArray' ];
  36. const samplersCube = [ 'samplerCube', 'samplerCubeShadow', 'usamplerCube', 'isamplerCube' ];
  37. const samplers3D = [ 'sampler3D', 'isampler3D', 'usampler3D' ];
  38. const spaceRegExp = /^((\t| )\n*)+/;
  39. const lineRegExp = /^\n+/;
  40. const commentRegExp = /^\/\*[\s\S]*?\*\//;
  41. const inlineCommentRegExp = /^\/\/.*?(?=\n|$)/;
  42. const numberRegExp = /^((0x\w+)|(\.?\d+\.?\d*((e-?\d+)|\w)?))/;
  43. const stringDoubleRegExp = /^(\"((?:[^"\\]|\\.)*)\")/;
  44. const stringSingleRegExp = /^(\'((?:[^'\\]|\\.)*)\')/;
  45. const literalRegExp = /^[A-Za-z](\w|\.)*/;
  46. const operatorsRegExp = new RegExp( '^(\\' + [
  47. '<<=', '>>=', '++', '--', '<<', '>>', '+=', '-=', '*=', '/=', '%=', '&=', '^^', '^=', '|=',
  48. '<=', '>=', '==', '!=', '&&', '||',
  49. '(', ')', '[', ']', '{', '}',
  50. '.', ',', ';', '!', '=', '~', '*', '/', '%', '+', '-', '<', '>', '&', '^', '|', '?', ':', '#'
  51. ].join( '$' ).split( '' ).join( '\\' ).replace( /\\\$/g, '|' ) + ')' );
  52. function getFunctionName( str ) {
  53. return glslToTSL[ str ] || str;
  54. }
  55. function getGroupDelta( str ) {
  56. if ( str === '(' || str === '[' || str === '{' ) return 1;
  57. if ( str === ')' || str === ']' || str === '}' ) return - 1;
  58. return 0;
  59. }
  60. class Token {
  61. constructor( tokenizer, type, str, pos ) {
  62. this.tokenizer = tokenizer;
  63. this.type = type;
  64. this.str = str;
  65. this.pos = pos;
  66. this.isTag = false;
  67. this.tags = null;
  68. }
  69. get endPos() {
  70. return this.pos + this.str.length;
  71. }
  72. get isNumber() {
  73. return this.type === Token.NUMBER;
  74. }
  75. get isString() {
  76. return this.type === Token.STRING;
  77. }
  78. get isLiteral() {
  79. return this.type === Token.LITERAL;
  80. }
  81. get isOperator() {
  82. return this.type === Token.OPERATOR;
  83. }
  84. }
  85. Token.LINE = 'line';
  86. Token.COMMENT = 'comment';
  87. Token.NUMBER = 'number';
  88. Token.STRING = 'string';
  89. Token.LITERAL = 'literal';
  90. Token.OPERATOR = 'operator';
  91. const TokenParserList = [
  92. { type: Token.LINE, regexp: lineRegExp, isTag: true },
  93. { type: Token.COMMENT, regexp: commentRegExp, isTag: true },
  94. { type: Token.COMMENT, regexp: inlineCommentRegExp, isTag: true },
  95. { type: Token.NUMBER, regexp: numberRegExp },
  96. { type: Token.STRING, regexp: stringDoubleRegExp, group: 2 },
  97. { type: Token.STRING, regexp: stringSingleRegExp, group: 2 },
  98. { type: Token.LITERAL, regexp: literalRegExp },
  99. { type: Token.OPERATOR, regexp: operatorsRegExp }
  100. ];
  101. class Tokenizer {
  102. constructor( source ) {
  103. this.source = source;
  104. this.position = 0;
  105. this.tokens = [];
  106. }
  107. tokenize() {
  108. let token = this.readToken();
  109. while ( token ) {
  110. this.tokens.push( token );
  111. token = this.readToken();
  112. }
  113. return this;
  114. }
  115. skip( ...params ) {
  116. let remainingCode = this.source.substr( this.position );
  117. let i = params.length;
  118. while ( i -- ) {
  119. const skip = params[ i ].exec( remainingCode );
  120. const skipLength = skip ? skip[ 0 ].length : 0;
  121. if ( skipLength > 0 ) {
  122. this.position += skipLength;
  123. remainingCode = this.source.substr( this.position );
  124. // re-skip, new remainingCode is generated
  125. // maybe exist previous regexp non detected
  126. i = params.length;
  127. }
  128. }
  129. return remainingCode;
  130. }
  131. nextToken() {
  132. const remainingCode = this.skip( spaceRegExp );
  133. for ( var i = 0; i < TokenParserList.length; i ++ ) {
  134. const parser = TokenParserList[ i ];
  135. const result = parser.regexp.exec( remainingCode );
  136. if ( result ) {
  137. const token = new Token( this, parser.type, result[ parser.group || 0 ], this.position );
  138. token.isTag = parser.isTag;
  139. this.position += result[ 0 ].length;
  140. return token;
  141. }
  142. }
  143. }
  144. readToken() {
  145. let token = this.nextToken();
  146. if ( token && token.isTag ) {
  147. const tags = [];
  148. while ( token.isTag ) {
  149. tags.push( token );
  150. token = this.nextToken();
  151. if ( ! token ) return;
  152. }
  153. token.tags = tags;
  154. }
  155. return token;
  156. }
  157. }
  158. const isType = ( str ) => /void|bool|float|u?int|mat[234]|mat[234]x[234]|(u|i|b)?vec[234]/.test( str );
  159. class GLSLDecoder {
  160. constructor() {
  161. this.index = 0;
  162. this.tokenizer = null;
  163. this.keywords = [];
  164. this.addPolyfill( 'gl_FragCoord', 'vec3 gl_FragCoord = vec3( screenCoordinate.x, screenCoordinate.y.oneMinus(), screenCoordinate.z );' );
  165. }
  166. addPolyfill( name, polyfill ) {
  167. this.keywords.push( { name, polyfill } );
  168. return this;
  169. }
  170. get tokens() {
  171. return this.tokenizer.tokens;
  172. }
  173. readToken() {
  174. return this.tokens[ this.index ++ ];
  175. }
  176. getToken( offset = 0 ) {
  177. return this.tokens[ this.index + offset ];
  178. }
  179. getTokensUntil( str, tokens, offset = 0 ) {
  180. const output = [];
  181. let groupIndex = 0;
  182. for ( let i = offset; i < tokens.length; i ++ ) {
  183. const token = tokens[ i ];
  184. groupIndex += getGroupDelta( token.str );
  185. output.push( token );
  186. if ( groupIndex === 0 && token.str === str ) {
  187. break;
  188. }
  189. }
  190. return output;
  191. }
  192. readTokensUntil( str ) {
  193. const tokens = this.getTokensUntil( str, this.tokens, this.index );
  194. this.index += tokens.length;
  195. return tokens;
  196. }
  197. parseExpressionFromTokens( tokens ) {
  198. if ( tokens.length === 0 ) return null;
  199. const firstToken = tokens[ 0 ];
  200. const lastToken = tokens[ tokens.length - 1 ];
  201. // precedence operators
  202. let groupIndex = 0;
  203. for ( const operator of precedenceOperators ) {
  204. const parseToken = ( i, inverse = false ) => {
  205. const token = tokens[ i ];
  206. groupIndex += getGroupDelta( token.str );
  207. if ( ! token.isOperator || i === 0 || i === tokens.length - 1 ) return;
  208. // important for negate operator after arithmetic operator: a * -1, a * -( b )
  209. if ( inverse && arithmeticOperators.includes( tokens[ i - 1 ].str ) ) {
  210. return;
  211. }
  212. if ( groupIndex === 0 && token.str === operator ) {
  213. if ( operator === '?' ) {
  214. const conditionTokens = tokens.slice( 0, i );
  215. const leftTokens = this.getTokensUntil( ':', tokens, i + 1 ).slice( 0, - 1 );
  216. const rightTokens = tokens.slice( i + leftTokens.length + 2 );
  217. const condition = this.parseExpressionFromTokens( conditionTokens );
  218. const left = this.parseExpressionFromTokens( leftTokens );
  219. const right = this.parseExpressionFromTokens( rightTokens );
  220. return new Ternary( condition, left, right );
  221. } else {
  222. const left = this.parseExpressionFromTokens( tokens.slice( 0, i ) );
  223. const right = this.parseExpressionFromTokens( tokens.slice( i + 1, tokens.length ) );
  224. return new Operator( operator, left, right );
  225. }
  226. }
  227. if ( inverse ) {
  228. if ( groupIndex > 0 ) {
  229. return this.parseExpressionFromTokens( tokens.slice( i ) );
  230. }
  231. } else {
  232. if ( groupIndex < 0 ) {
  233. return this.parseExpressionFromTokens( tokens.slice( 0, i ) );
  234. }
  235. }
  236. };
  237. if ( associativityRightToLeft.includes( operator ) ) {
  238. for ( let i = 0; i < tokens.length; i ++ ) {
  239. const result = parseToken( i );
  240. if ( result ) return result;
  241. }
  242. } else {
  243. for ( let i = tokens.length - 1; i >= 0; i -- ) {
  244. const result = parseToken( i, true );
  245. if ( result ) return result;
  246. }
  247. }
  248. }
  249. // unary operators (before)
  250. if ( firstToken.isOperator ) {
  251. for ( const operator of unaryOperators ) {
  252. if ( firstToken.str === operator ) {
  253. const right = this.parseExpressionFromTokens( tokens.slice( 1 ) );
  254. return new Unary( operator, right );
  255. }
  256. }
  257. }
  258. // unary operators (after)
  259. if ( lastToken.isOperator ) {
  260. for ( const operator of unaryOperators ) {
  261. if ( lastToken.str === operator ) {
  262. const left = this.parseExpressionFromTokens( tokens.slice( 0, tokens.length - 1 ) );
  263. return new Unary( operator, left, true );
  264. }
  265. }
  266. }
  267. // groups
  268. if ( firstToken.str === '(' ) {
  269. const leftTokens = this.getTokensUntil( ')', tokens );
  270. const left = this.parseExpressionFromTokens( leftTokens.slice( 1, leftTokens.length - 1 ) );
  271. const operator = tokens[ leftTokens.length ];
  272. if ( operator ) {
  273. const rightTokens = tokens.slice( leftTokens.length + 1 );
  274. const right = this.parseExpressionFromTokens( rightTokens );
  275. return new Operator( operator.str, left, right );
  276. }
  277. return left;
  278. }
  279. // primitives and accessors
  280. if ( firstToken.isNumber ) {
  281. let type;
  282. const isHex = /^(0x)/.test( firstToken.str );
  283. if ( isHex ) type = 'int';
  284. else if ( /u$|U$/.test( firstToken.str ) ) type = 'uint';
  285. else if ( /f|e|\./.test( firstToken.str ) ) type = 'float';
  286. else type = 'int';
  287. let str = firstToken.str.replace( /u|U|i$/, '' );
  288. if ( isHex === false ) {
  289. str = str.replace( /f$/, '' );
  290. }
  291. return new Number( str, type );
  292. } else if ( firstToken.isString ) {
  293. return new String( firstToken.str );
  294. } else if ( firstToken.isLiteral ) {
  295. if ( firstToken.str === 'return' ) {
  296. return new Return( this.parseExpressionFromTokens( tokens.slice( 1 ) ) );
  297. } else if ( firstToken.str === 'discard' ) {
  298. return new Discard();
  299. } else if ( firstToken.str === 'continue' ) {
  300. return new Continue();
  301. } else if ( firstToken.str === 'break' ) {
  302. return new Break();
  303. }
  304. const secondToken = tokens[ 1 ];
  305. if ( secondToken ) {
  306. if ( secondToken.str === '(' ) {
  307. // function call
  308. const internalTokens = this.getTokensUntil( ')', tokens, 1 ).slice( 1, - 1 );
  309. const paramsTokens = this.parseFunctionParametersFromTokens( internalTokens );
  310. const functionCall = new FunctionCall( getFunctionName( firstToken.str ), paramsTokens );
  311. const accessTokens = tokens.slice( 3 + internalTokens.length );
  312. if ( accessTokens.length > 0 ) {
  313. const elements = this.parseAccessorElementsFromTokens( accessTokens );
  314. return new AccessorElements( functionCall, elements );
  315. }
  316. return functionCall;
  317. } else if ( secondToken.str === '[' ) {
  318. // array accessor
  319. const elements = this.parseAccessorElementsFromTokens( tokens.slice( 1 ) );
  320. return new AccessorElements( new Accessor( firstToken.str ), elements );
  321. }
  322. }
  323. return new Accessor( firstToken.str );
  324. }
  325. }
  326. parseAccessorElementsFromTokens( tokens ) {
  327. const elements = [];
  328. let currentTokens = tokens;
  329. while ( currentTokens.length > 0 ) {
  330. const token = currentTokens[ 0 ];
  331. if ( token.str === '[' ) {
  332. const accessorTokens = this.getTokensUntil( ']', currentTokens );
  333. const element = this.parseExpressionFromTokens( accessorTokens.slice( 1, accessorTokens.length - 1 ) );
  334. currentTokens = currentTokens.slice( accessorTokens.length );
  335. elements.push( new DynamicElement( element ) );
  336. } else if ( token.str === '.' ) {
  337. const accessorTokens = currentTokens.slice( 1, 2 );
  338. const element = this.parseExpressionFromTokens( accessorTokens );
  339. currentTokens = currentTokens.slice( 2 );
  340. elements.push( new StaticElement( element ) );
  341. } else {
  342. console.error( 'Unknown accessor expression', token );
  343. break;
  344. }
  345. }
  346. return elements;
  347. }
  348. parseFunctionParametersFromTokens( tokens ) {
  349. if ( tokens.length === 0 ) return [];
  350. const expression = this.parseExpressionFromTokens( tokens );
  351. const params = [];
  352. let current = expression;
  353. while ( current.type === ',' ) {
  354. params.push( current.left );
  355. current = current.right;
  356. }
  357. params.push( current );
  358. return params;
  359. }
  360. parseExpression() {
  361. const tokens = this.readTokensUntil( ';' );
  362. const exp = this.parseExpressionFromTokens( tokens.slice( 0, tokens.length - 1 ) );
  363. return exp;
  364. }
  365. parseFunctionParams( tokens ) {
  366. const params = [];
  367. for ( let i = 0; i < tokens.length; i ++ ) {
  368. const immutable = tokens[ i ].str === 'const';
  369. if ( immutable ) i ++;
  370. let qualifier = tokens[ i ].str;
  371. if ( /^(in|out|inout)$/.test( qualifier ) ) {
  372. i ++;
  373. } else {
  374. qualifier = null;
  375. }
  376. const type = tokens[ i ++ ].str;
  377. const name = tokens[ i ++ ].str;
  378. params.push( new FunctionParameter( type, name, qualifier, immutable ) );
  379. if ( tokens[ i ] && tokens[ i ].str !== ',' ) throw new Error( 'Expected ","' );
  380. }
  381. return params;
  382. }
  383. parseFunction() {
  384. const type = this.readToken().str;
  385. const name = this.readToken().str;
  386. const paramsTokens = this.readTokensUntil( ')' );
  387. const params = this.parseFunctionParams( paramsTokens.slice( 1, paramsTokens.length - 1 ) );
  388. const body = this.parseBlock();
  389. const func = new FunctionDeclaration( type, name, params, body );
  390. return func;
  391. }
  392. parseVariablesFromToken( tokens, type ) {
  393. let index = 0;
  394. const immutable = tokens[ 0 ].str === 'const';
  395. if ( immutable ) index ++;
  396. type = type || tokens[ index ++ ].str;
  397. const name = tokens[ index ++ ].str;
  398. const token = tokens[ index ];
  399. let init = null;
  400. let next = null;
  401. if ( token ) {
  402. const initTokens = this.getTokensUntil( ',', tokens, index );
  403. if ( initTokens[ 0 ].str === '=' ) {
  404. const expressionTokens = initTokens.slice( 1 );
  405. if ( expressionTokens[ expressionTokens.length - 1 ].str === ',' ) expressionTokens.pop();
  406. init = this.parseExpressionFromTokens( expressionTokens );
  407. }
  408. const nextTokens = tokens.slice( initTokens.length + ( index - 1 ) );
  409. if ( nextTokens[ 0 ] && nextTokens[ 0 ].str === ',' ) {
  410. next = this.parseVariablesFromToken( nextTokens.slice( 1 ), type );
  411. }
  412. }
  413. const variable = new VariableDeclaration( type, name, init, next, immutable );
  414. return variable;
  415. }
  416. parseVariables() {
  417. const tokens = this.readTokensUntil( ';' );
  418. return this.parseVariablesFromToken( tokens.slice( 0, tokens.length - 1 ) );
  419. }
  420. parseUniform() {
  421. const tokens = this.readTokensUntil( ';' );
  422. let type = tokens[ 1 ].str;
  423. const name = tokens[ 2 ].str;
  424. // GLSL to TSL types
  425. if ( samplers.includes( type ) ) type = 'texture';
  426. else if ( samplersCube.includes( type ) ) type = 'cubeTexture';
  427. else if ( samplers3D.includes( type ) ) type = 'texture3D';
  428. return new Uniform( type, name );
  429. }
  430. parseVarying() {
  431. const tokens = this.readTokensUntil( ';' );
  432. const type = tokens[ 1 ].str;
  433. const name = tokens[ 2 ].str;
  434. return new Varying( type, name );
  435. }
  436. parseReturn() {
  437. this.readToken(); // skip 'return'
  438. const expression = this.parseExpression();
  439. return new Return( expression );
  440. }
  441. parseWhile() {
  442. this.readToken(); // skip 'while'
  443. const conditionTokens = this.readTokensUntil( ')' ).slice( 1, - 1 );
  444. const condition = this.parseExpressionFromTokens( conditionTokens );
  445. let body;
  446. if ( this.getToken().str === '{' ) {
  447. body = this.parseBlock();
  448. } else {
  449. body = [ this.parseExpression() ];
  450. }
  451. const statement = new While( condition, body );
  452. return statement;
  453. }
  454. parseFor() {
  455. this.readToken(); // skip 'for'
  456. const forTokens = this.readTokensUntil( ')' ).slice( 1, - 1 );
  457. const initializationTokens = this.getTokensUntil( ';', forTokens, 0 ).slice( 0, - 1 );
  458. const conditionTokens = this.getTokensUntil( ';', forTokens, initializationTokens.length + 1 ).slice( 0, - 1 );
  459. const afterthoughtTokens = forTokens.slice( initializationTokens.length + conditionTokens.length + 2 );
  460. let initialization;
  461. if ( initializationTokens[ 0 ] && isType( initializationTokens[ 0 ].str ) ) {
  462. initialization = this.parseVariablesFromToken( initializationTokens );
  463. } else {
  464. initialization = this.parseExpressionFromTokens( initializationTokens );
  465. }
  466. const condition = this.parseExpressionFromTokens( conditionTokens );
  467. const afterthought = this.parseExpressionFromTokens( afterthoughtTokens );
  468. let body;
  469. if ( this.getToken().str === '{' ) {
  470. body = this.parseBlock();
  471. } else {
  472. body = [ this.parseExpression() ];
  473. }
  474. const statement = new For( initialization, condition, afterthought, body );
  475. return statement;
  476. }
  477. parseSwitch() {
  478. this.readToken(); // Skip 'switch'
  479. const switchDeterminantTokens = this.readTokensUntil( ')' );
  480. // Parse expresison between parentheses. Index 1: char after '('. Index -1: char before ')'
  481. const discriminant = this.parseExpressionFromTokens( switchDeterminantTokens.slice( 1, - 1 ) );
  482. // Validate curly braces
  483. if ( this.getToken().str !== '{' ) {
  484. throw new Error( 'Expected \'{\' after switch(...) ' );
  485. }
  486. this.readToken(); // Skip '{'
  487. const cases = this.parseSwitchCases();
  488. const switchStatement = new Switch( discriminant, cases );
  489. return switchStatement;
  490. }
  491. parseSwitchCases() {
  492. const cases = [];
  493. let token = this.getToken();
  494. let conditions = null;
  495. const isCase = ( token ) => token.str === 'case' || token.str === 'default';
  496. while ( isCase( token ) ) {
  497. this.readToken(); // Skip 'case' or 'default'
  498. if ( token.str === 'case' ) {
  499. const caseTokens = this.readTokensUntil( ':' );
  500. const caseStatement = this.parseExpressionFromTokens( caseTokens.slice( 0, - 1 ) );
  501. conditions = conditions || [];
  502. conditions.push( caseStatement );
  503. } else {
  504. this.readTokensUntil( ':' ); // Skip 'default:'
  505. conditions = null;
  506. }
  507. token = this.getToken();
  508. if ( isCase( token ) ) {
  509. // If the next token is another case/default, continue parsing
  510. continue;
  511. }
  512. cases.push( new SwitchCase( this.parseBlock(), conditions ) );
  513. token = this.getToken();
  514. conditions = null;
  515. }
  516. return cases;
  517. }
  518. parseIf() {
  519. const parseIfExpression = () => {
  520. this.readToken(); // skip 'if'
  521. const condTokens = this.readTokensUntil( ')' );
  522. return this.parseExpressionFromTokens( condTokens.slice( 1, condTokens.length - 1 ) );
  523. };
  524. const parseIfBlock = () => {
  525. let body;
  526. if ( this.getToken().str === '{' ) {
  527. body = this.parseBlock();
  528. } else {
  529. body = [ this.parseExpression() ];
  530. }
  531. return body;
  532. };
  533. //
  534. // Parse the first if statement
  535. const conditional = new Conditional( parseIfExpression(), parseIfBlock() );
  536. //
  537. let current = conditional;
  538. while ( this.getToken() && this.getToken().str === 'else' ) {
  539. this.readToken(); // skip 'else'
  540. // Assign the current if/else statement as the previous within the chain of conditionals
  541. const previous = current;
  542. let expression = null;
  543. // If an 'else if' statement, parse the conditional within the if
  544. if ( this.getToken().str === 'if' ) {
  545. // Current conditional now equal to next conditional in the chain
  546. expression = parseIfExpression();
  547. }
  548. current = new Conditional( expression, parseIfBlock() );
  549. current.parent = previous;
  550. // n - 1 conditional's else statement assigned to new if/else statement
  551. previous.elseConditional = current;
  552. }
  553. return conditional;
  554. }
  555. parseBlock() {
  556. const body = [];
  557. const firstToken = this.getToken();
  558. if ( firstToken.str === '{' ) {
  559. this.readToken(); // skip '{'
  560. }
  561. let groupIndex = 0;
  562. while ( this.index < this.tokens.length ) {
  563. const token = this.getToken();
  564. let statement = null;
  565. groupIndex += getGroupDelta( token.str );
  566. if ( groupIndex === 0 && ( token.str === 'case' || token.str === 'default' ) ) {
  567. return body; // switch case or default statement, return body
  568. } else if ( groupIndex < 0 ) {
  569. this.readToken(); // skip '}'
  570. return body;
  571. }
  572. //
  573. if ( token.tags ) {
  574. let lastStatement = null;
  575. for ( const tag of token.tags ) {
  576. if ( tag.type === Token.COMMENT ) {
  577. const str = tag.str.replace( /\t/g, '' );
  578. if ( ! lastStatement || lastStatement.isComment !== true ) {
  579. lastStatement = new Comment( str );
  580. body.push( lastStatement );
  581. } else {
  582. lastStatement.comment += '\n' + str;
  583. }
  584. }
  585. }
  586. }
  587. if ( token.isLiteral || token.isOperator ) {
  588. if ( token.str === 'const' ) {
  589. statement = this.parseVariables();
  590. } else if ( token.str === 'uniform' ) {
  591. statement = this.parseUniform();
  592. } else if ( token.str === 'varying' ) {
  593. statement = this.parseVarying();
  594. } else if ( isType( token.str ) ) {
  595. if ( this.getToken( 2 ).str === '(' ) {
  596. statement = this.parseFunction();
  597. } else {
  598. statement = this.parseVariables();
  599. }
  600. } else if ( token.str === 'return' ) {
  601. statement = this.parseReturn();
  602. } else if ( token.str === 'if' ) {
  603. statement = this.parseIf();
  604. } else if ( token.str === 'for' ) {
  605. statement = this.parseFor();
  606. } else if ( token.str === 'while' ) {
  607. statement = this.parseWhile();
  608. } else if ( token.str === 'switch' ) {
  609. statement = this.parseSwitch();
  610. } else {
  611. statement = this.parseExpression();
  612. }
  613. }
  614. if ( statement ) {
  615. body.push( statement );
  616. } else {
  617. this.index ++;
  618. }
  619. }
  620. return body;
  621. }
  622. parse( source ) {
  623. let polyfill = '';
  624. for ( const keyword of this.keywords ) {
  625. if ( new RegExp( `(^|\\b)${ keyword.name }($|\\b)`, 'gm' ).test( source ) ) {
  626. polyfill += keyword.polyfill + '\n';
  627. }
  628. }
  629. if ( polyfill ) {
  630. polyfill = '// Polyfills\n\n' + polyfill + '\n';
  631. }
  632. this.index = 0;
  633. this.tokenizer = new Tokenizer( polyfill + source ).tokenize();
  634. const body = this.parseBlock();
  635. const program = new Program( body );
  636. return program;
  637. }
  638. }
  639. export default GLSLDecoder;
粤ICP备19079148号