GLSLDecoder.js 22 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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. import { isType } from './TranspilerUtils.js';
  3. const unaryOperators = [
  4. '+', '-', '~', '!', '++', '--'
  5. ];
  6. const arithmeticOperators = [
  7. '*', '/', '%', '+', '-', '<<', '>>'
  8. ];
  9. const precedenceOperators = [
  10. [ ',' ],
  11. [ '=', '+=', '-=', '*=', '/=', '%=', '^=', '&=', '|=', '<<=', '>>=' ],
  12. [ '?' ],
  13. [ '||' ],
  14. [ '^^' ],
  15. [ '&&' ],
  16. [ '|' ],
  17. [ '^' ],
  18. [ '&' ],
  19. [ '==', '!=' ],
  20. [ '<', '>', '<=', '>=' ],
  21. [ '<<', '>>' ],
  22. [ '+', '-' ],
  23. [ '*', '/', '%' ]
  24. ];
  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. class GLSLDecoder {
  159. constructor() {
  160. this.index = 0;
  161. this.tokenizer = null;
  162. this.keywords = [];
  163. this.addPolyfill( 'gl_FragCoord', 'vec3 gl_FragCoord = vec3( screenCoordinate.x, screenCoordinate.y.oneMinus(), screenCoordinate.z );' );
  164. }
  165. addPolyfill( name, polyfill ) {
  166. this.keywords.push( { name, polyfill } );
  167. return this;
  168. }
  169. get tokens() {
  170. return this.tokenizer.tokens;
  171. }
  172. readToken() {
  173. return this.tokens[ this.index ++ ];
  174. }
  175. getToken( offset = 0 ) {
  176. return this.tokens[ this.index + offset ];
  177. }
  178. getTokensUntil( str, tokens, offset = 0 ) {
  179. const output = [];
  180. let groupIndex = 0;
  181. for ( let i = offset; i < tokens.length; i ++ ) {
  182. const token = tokens[ i ];
  183. groupIndex += getGroupDelta( token.str );
  184. output.push( token );
  185. if ( groupIndex === 0 && token.str === str ) {
  186. break;
  187. }
  188. }
  189. return output;
  190. }
  191. readTokensUntil( str ) {
  192. const tokens = this.getTokensUntil( str, this.tokens, this.index );
  193. this.index += tokens.length;
  194. return tokens;
  195. }
  196. parseExpressionFromTokens( tokens ) {
  197. if ( tokens.length === 0 ) return null;
  198. const firstToken = tokens[ 0 ];
  199. const lastToken = tokens[ tokens.length - 1 ];
  200. // precedence operators
  201. let groupIndex = 0;
  202. for ( const operators of precedenceOperators ) {
  203. const parseToken = ( i, inverse = false ) => {
  204. const token = tokens[ i ];
  205. groupIndex += getGroupDelta( token.str );
  206. if ( ! token.isOperator || i === 0 || i === tokens.length - 1 ) return;
  207. // important for negate operator after arithmetic operator: a * -1, a * -( b )
  208. if ( inverse && arithmeticOperators.includes( tokens[ i - 1 ].str ) ) {
  209. return;
  210. }
  211. if ( groupIndex === 0 && operators.includes( token.str ) ) {
  212. const operator = token.str;
  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. const isRightAssociative = operators.some( op => associativityRightToLeft.includes( op ) );
  238. if ( isRightAssociative ) {
  239. for ( let i = 0; i < tokens.length; i ++ ) {
  240. const result = parseToken( i );
  241. if ( result ) return result;
  242. }
  243. } else {
  244. for ( let i = tokens.length - 1; i >= 0; i -- ) {
  245. const result = parseToken( i, true );
  246. if ( result ) return result;
  247. }
  248. }
  249. }
  250. // unary operators (before)
  251. if ( firstToken.isOperator ) {
  252. for ( const operator of unaryOperators ) {
  253. if ( firstToken.str === operator ) {
  254. const right = this.parseExpressionFromTokens( tokens.slice( 1 ) );
  255. return new Unary( operator, right );
  256. }
  257. }
  258. }
  259. // unary operators (after)
  260. if ( lastToken.isOperator ) {
  261. for ( const operator of unaryOperators ) {
  262. if ( lastToken.str === operator ) {
  263. const left = this.parseExpressionFromTokens( tokens.slice( 0, tokens.length - 1 ) );
  264. return new Unary( operator, left, true );
  265. }
  266. }
  267. }
  268. // groups
  269. if ( firstToken.str === '(' ) {
  270. const leftTokens = this.getTokensUntil( ')', tokens );
  271. const left = this.parseExpressionFromTokens( leftTokens.slice( 1, leftTokens.length - 1 ) );
  272. const operator = tokens[ leftTokens.length ];
  273. if ( operator ) {
  274. const rightTokens = tokens.slice( leftTokens.length + 1 );
  275. const right = this.parseExpressionFromTokens( rightTokens );
  276. return new Operator( operator.str, left, right );
  277. }
  278. return left;
  279. }
  280. // primitives and accessors
  281. if ( firstToken.isNumber ) {
  282. let type;
  283. const isHex = /^(0x)/.test( firstToken.str );
  284. if ( isHex ) type = 'int';
  285. else if ( /u$|U$/.test( firstToken.str ) ) type = 'uint';
  286. else if ( /f|e|\./.test( firstToken.str ) ) type = 'float';
  287. else type = 'int';
  288. let str = firstToken.str.replace( /u|U|i$/, '' );
  289. if ( isHex === false ) {
  290. str = str.replace( /f$/, '' );
  291. }
  292. return new Number( str, type );
  293. } else if ( firstToken.isString ) {
  294. return new String( firstToken.str );
  295. } else if ( firstToken.isLiteral ) {
  296. if ( firstToken.str === 'return' ) {
  297. return new Return( this.parseExpressionFromTokens( tokens.slice( 1 ) ) );
  298. } else if ( firstToken.str === 'discard' ) {
  299. return new Discard();
  300. } else if ( firstToken.str === 'continue' ) {
  301. return new Continue();
  302. } else if ( firstToken.str === 'break' ) {
  303. return new Break();
  304. }
  305. const secondToken = tokens[ 1 ];
  306. if ( secondToken ) {
  307. if ( secondToken.str === '(' ) {
  308. // function call
  309. const internalTokens = this.getTokensUntil( ')', tokens, 1 ).slice( 1, - 1 );
  310. const paramsTokens = this.parseFunctionParametersFromTokens( internalTokens );
  311. const functionCall = new FunctionCall( getFunctionName( firstToken.str ), paramsTokens );
  312. const accessTokens = tokens.slice( 3 + internalTokens.length );
  313. if ( accessTokens.length > 0 ) {
  314. const elements = this.parseAccessorElementsFromTokens( accessTokens );
  315. return new AccessorElements( functionCall, elements );
  316. }
  317. return functionCall;
  318. } else if ( secondToken.str === '[' ) {
  319. // array accessor
  320. const elements = this.parseAccessorElementsFromTokens( tokens.slice( 1 ) );
  321. return new AccessorElements( new Accessor( firstToken.str ), elements );
  322. }
  323. }
  324. return new Accessor( firstToken.str );
  325. }
  326. }
  327. parseAccessorElementsFromTokens( tokens ) {
  328. const elements = [];
  329. let currentTokens = tokens;
  330. while ( currentTokens.length > 0 ) {
  331. const token = currentTokens[ 0 ];
  332. if ( token.str === '[' ) {
  333. const accessorTokens = this.getTokensUntil( ']', currentTokens );
  334. const element = this.parseExpressionFromTokens( accessorTokens.slice( 1, accessorTokens.length - 1 ) );
  335. currentTokens = currentTokens.slice( accessorTokens.length );
  336. elements.push( new DynamicElement( element ) );
  337. } else if ( token.str === '.' ) {
  338. const accessorTokens = currentTokens.slice( 1, 2 );
  339. const element = this.parseExpressionFromTokens( accessorTokens );
  340. currentTokens = currentTokens.slice( 2 );
  341. elements.push( new StaticElement( element ) );
  342. } else {
  343. console.error( 'Unknown accessor expression', token );
  344. break;
  345. }
  346. }
  347. return elements;
  348. }
  349. parseFunctionParametersFromTokens( tokens ) {
  350. if ( tokens.length === 0 ) return [];
  351. const expression = this.parseExpressionFromTokens( tokens );
  352. const params = [];
  353. let current = expression;
  354. while ( current.type === ',' ) {
  355. params.push( current.left );
  356. current = current.right;
  357. }
  358. params.push( current );
  359. return params;
  360. }
  361. parseExpression() {
  362. const tokens = this.readTokensUntil( ';' );
  363. const exp = this.parseExpressionFromTokens( tokens.slice( 0, tokens.length - 1 ) );
  364. return exp;
  365. }
  366. parseFunctionParams( tokens ) {
  367. const params = [];
  368. for ( let i = 0; i < tokens.length; i ++ ) {
  369. const immutable = tokens[ i ].str === 'const';
  370. if ( immutable ) i ++;
  371. let qualifier = tokens[ i ].str;
  372. if ( /^(in|out|inout)$/.test( qualifier ) ) {
  373. i ++;
  374. } else {
  375. qualifier = null;
  376. }
  377. const type = tokens[ i ++ ].str;
  378. const name = tokens[ i ++ ].str;
  379. params.push( new FunctionParameter( type, name, qualifier, immutable ) );
  380. if ( tokens[ i ] && tokens[ i ].str !== ',' ) throw new Error( 'Expected ","' );
  381. }
  382. return params;
  383. }
  384. parseFunction() {
  385. const type = this.readToken().str;
  386. const name = this.readToken().str;
  387. const paramsTokens = this.readTokensUntil( ')' );
  388. const params = this.parseFunctionParams( paramsTokens.slice( 1, paramsTokens.length - 1 ) );
  389. const body = this.parseBlock();
  390. const func = new FunctionDeclaration( type, name, params, body );
  391. return func;
  392. }
  393. parseVariablesFromToken( tokens, type ) {
  394. let index = 0;
  395. const immutable = tokens[ 0 ].str === 'const';
  396. if ( immutable ) index ++;
  397. type = type || tokens[ index ++ ].str;
  398. const name = tokens[ index ++ ].str;
  399. const token = tokens[ index ];
  400. let init = null;
  401. let next = null;
  402. if ( token ) {
  403. const initTokens = this.getTokensUntil( ',', tokens, index );
  404. if ( initTokens[ 0 ].str === '=' ) {
  405. const expressionTokens = initTokens.slice( 1 );
  406. if ( expressionTokens[ expressionTokens.length - 1 ].str === ',' ) expressionTokens.pop();
  407. init = this.parseExpressionFromTokens( expressionTokens );
  408. }
  409. const nextTokens = tokens.slice( initTokens.length + ( index - 1 ) );
  410. if ( nextTokens[ 0 ] && nextTokens[ 0 ].str === ',' ) {
  411. next = this.parseVariablesFromToken( nextTokens.slice( 1 ), type );
  412. }
  413. }
  414. const variable = new VariableDeclaration( type, name, init, next, immutable );
  415. return variable;
  416. }
  417. parseVariables() {
  418. const tokens = this.readTokensUntil( ';' );
  419. return this.parseVariablesFromToken( tokens.slice( 0, tokens.length - 1 ) );
  420. }
  421. parseUniform() {
  422. const tokens = this.readTokensUntil( ';' );
  423. let type = tokens[ 1 ].str;
  424. const name = tokens[ 2 ].str;
  425. // GLSL to TSL types
  426. if ( samplers.includes( type ) ) type = 'texture';
  427. else if ( samplersCube.includes( type ) ) type = 'cubeTexture';
  428. else if ( samplers3D.includes( type ) ) type = 'texture3D';
  429. return new Uniform( type, name );
  430. }
  431. parseVarying() {
  432. const tokens = this.readTokensUntil( ';' );
  433. const type = tokens[ 1 ].str;
  434. const name = tokens[ 2 ].str;
  435. return new Varying( type, name );
  436. }
  437. parseReturn() {
  438. this.readToken(); // skip 'return'
  439. const expression = this.parseExpression();
  440. return new Return( expression );
  441. }
  442. parseWhile() {
  443. this.readToken(); // skip 'while'
  444. const conditionTokens = this.readTokensUntil( ')' ).slice( 1, - 1 );
  445. const condition = this.parseExpressionFromTokens( conditionTokens );
  446. let body;
  447. if ( this.getToken().str === '{' ) {
  448. body = this.parseBlock();
  449. } else {
  450. body = [ this.parseExpression() ];
  451. }
  452. const statement = new While( condition, body );
  453. return statement;
  454. }
  455. parseFor() {
  456. this.readToken(); // skip 'for'
  457. const forTokens = this.readTokensUntil( ')' ).slice( 1, - 1 );
  458. const initializationTokens = this.getTokensUntil( ';', forTokens, 0 ).slice( 0, - 1 );
  459. const conditionTokens = this.getTokensUntil( ';', forTokens, initializationTokens.length + 1 ).slice( 0, - 1 );
  460. const afterthoughtTokens = forTokens.slice( initializationTokens.length + conditionTokens.length + 2 );
  461. let initialization;
  462. if ( initializationTokens[ 0 ] && isType( initializationTokens[ 0 ].str ) ) {
  463. initialization = this.parseVariablesFromToken( initializationTokens );
  464. } else {
  465. initialization = this.parseExpressionFromTokens( initializationTokens );
  466. }
  467. const condition = this.parseExpressionFromTokens( conditionTokens );
  468. const afterthought = this.parseExpressionFromTokens( afterthoughtTokens );
  469. let body;
  470. if ( this.getToken().str === '{' ) {
  471. body = this.parseBlock();
  472. } else {
  473. body = [ this.parseExpression() ];
  474. }
  475. const statement = new For( initialization, condition, afterthought, body );
  476. return statement;
  477. }
  478. parseSwitch() {
  479. this.readToken(); // Skip 'switch'
  480. const switchDeterminantTokens = this.readTokensUntil( ')' );
  481. // Parse expression between parentheses. Index 1: char after '('. Index -1: char before ')'
  482. const discriminant = this.parseExpressionFromTokens( switchDeterminantTokens.slice( 1, - 1 ) );
  483. // Validate curly braces
  484. if ( this.getToken().str !== '{' ) {
  485. throw new Error( 'Expected \'{\' after switch(...) ' );
  486. }
  487. this.readToken(); // Skip '{'
  488. const cases = this.parseSwitchCases();
  489. const switchStatement = new Switch( discriminant, cases );
  490. return switchStatement;
  491. }
  492. parseSwitchCases() {
  493. const cases = [];
  494. let token = this.getToken();
  495. let conditions = null;
  496. const isCase = ( token ) => token.str === 'case' || token.str === 'default';
  497. while ( isCase( token ) ) {
  498. this.readToken(); // Skip 'case' or 'default'
  499. if ( token.str === 'case' ) {
  500. const caseTokens = this.readTokensUntil( ':' );
  501. const caseStatement = this.parseExpressionFromTokens( caseTokens.slice( 0, - 1 ) );
  502. conditions = conditions || [];
  503. conditions.push( caseStatement );
  504. } else {
  505. this.readTokensUntil( ':' ); // Skip 'default:'
  506. conditions = null;
  507. }
  508. token = this.getToken();
  509. if ( isCase( token ) ) {
  510. // If the next token is another case/default, continue parsing
  511. continue;
  512. }
  513. cases.push( new SwitchCase( this.parseBlock(), conditions ) );
  514. token = this.getToken();
  515. conditions = null;
  516. }
  517. return cases;
  518. }
  519. parseIf() {
  520. const parseIfExpression = () => {
  521. this.readToken(); // skip 'if'
  522. const condTokens = this.readTokensUntil( ')' );
  523. return this.parseExpressionFromTokens( condTokens.slice( 1, condTokens.length - 1 ) );
  524. };
  525. const parseIfBlock = () => {
  526. let body;
  527. if ( this.getToken().str === '{' ) {
  528. body = this.parseBlock();
  529. } else {
  530. body = [ this.parseExpression() ];
  531. }
  532. return body;
  533. };
  534. //
  535. // Parse the first if statement
  536. const conditional = new Conditional( parseIfExpression(), parseIfBlock() );
  537. //
  538. let current = conditional;
  539. while ( this.getToken() && this.getToken().str === 'else' ) {
  540. this.readToken(); // skip 'else'
  541. // Assign the current if/else statement as the previous within the chain of conditionals
  542. const previous = current;
  543. let expression = null;
  544. // If an 'else if' statement, parse the conditional within the if
  545. if ( this.getToken().str === 'if' ) {
  546. // Current conditional now equal to next conditional in the chain
  547. expression = parseIfExpression();
  548. }
  549. current = new Conditional( expression, parseIfBlock() );
  550. current.parent = previous;
  551. // n - 1 conditional's else statement assigned to new if/else statement
  552. previous.elseConditional = current;
  553. }
  554. return conditional;
  555. }
  556. parseBlock() {
  557. const body = [];
  558. const firstToken = this.getToken();
  559. if ( firstToken.str === '{' ) {
  560. this.readToken(); // skip '{'
  561. }
  562. let groupIndex = 0;
  563. while ( this.index < this.tokens.length ) {
  564. const token = this.getToken();
  565. let statement = null;
  566. groupIndex += getGroupDelta( token.str );
  567. if ( groupIndex === 0 && ( token.str === 'case' || token.str === 'default' ) ) {
  568. return body; // switch case or default statement, return body
  569. } else if ( groupIndex < 0 ) {
  570. this.readToken(); // skip '}'
  571. return body;
  572. }
  573. //
  574. if ( token.tags ) {
  575. let lastStatement = null;
  576. for ( const tag of token.tags ) {
  577. if ( tag.type === Token.COMMENT ) {
  578. const str = tag.str.replace( /\t/g, '' );
  579. if ( ! lastStatement || lastStatement.isComment !== true ) {
  580. lastStatement = new Comment( str );
  581. body.push( lastStatement );
  582. } else {
  583. lastStatement.comment += '\n' + str;
  584. }
  585. }
  586. }
  587. }
  588. if ( token.isLiteral || token.isOperator ) {
  589. if ( token.str === 'const' ) {
  590. statement = this.parseVariables();
  591. } else if ( token.str === 'uniform' ) {
  592. statement = this.parseUniform();
  593. } else if ( token.str === 'varying' ) {
  594. statement = this.parseVarying();
  595. } else if ( isType( token.str ) ) {
  596. if ( this.getToken( 2 ).str === '(' ) {
  597. statement = this.parseFunction();
  598. } else {
  599. statement = this.parseVariables();
  600. }
  601. } else if ( token.str === 'return' ) {
  602. statement = this.parseReturn();
  603. } else if ( token.str === 'if' ) {
  604. statement = this.parseIf();
  605. } else if ( token.str === 'for' ) {
  606. statement = this.parseFor();
  607. } else if ( token.str === 'while' ) {
  608. statement = this.parseWhile();
  609. } else if ( token.str === 'switch' ) {
  610. statement = this.parseSwitch();
  611. } else {
  612. statement = this.parseExpression();
  613. }
  614. }
  615. if ( statement ) {
  616. body.push( statement );
  617. } else {
  618. this.index ++;
  619. }
  620. }
  621. return body;
  622. }
  623. parse( source ) {
  624. let polyfill = '';
  625. for ( const keyword of this.keywords ) {
  626. if ( new RegExp( `(^|\\b)${ keyword.name }($|\\b)`, 'gm' ).test( source ) ) {
  627. polyfill += keyword.polyfill + '\n';
  628. }
  629. }
  630. if ( polyfill ) {
  631. polyfill = '// Polyfills\n\n' + polyfill + '\n';
  632. }
  633. this.index = 0;
  634. this.tokenizer = new Tokenizer( polyfill + source ).tokenize();
  635. const body = this.parseBlock();
  636. const program = new Program( body );
  637. return program;
  638. }
  639. }
  640. export default GLSLDecoder;
粤ICP备19079148号