fork of hey-api/openapi-ts because I need some additional things
at feat/skip-token 82 lines 2.1 kB view raw
1import type { AnalysisContext } from '@hey-api/codegen-core'; 2 3import { py } from '../../ts-python'; 4import type { MaybePyDsl } from '../base'; 5import { PyDsl } from '../base'; 6import type { DoExpr } from '../mixins/do'; 7import { DoMixin } from '../mixins/do'; 8import { BlockPyDsl } from './block'; 9 10export type IfCondition = string | MaybePyDsl<py.Expression>; 11 12const Mixed = DoMixin(PyDsl<py.IfStatement>); 13 14export class IfPyDsl extends Mixed { 15 readonly '~dsl' = 'IfPyDsl'; 16 17 protected _condition?: IfCondition; 18 protected _else?: Array<DoExpr>; 19 20 constructor(condition?: IfCondition) { 21 super(); 22 if (condition) this.condition(condition); 23 } 24 25 override analyze(ctx: AnalysisContext): void { 26 super.analyze(ctx); 27 ctx.analyze(this._condition); 28 if (this._else) { 29 ctx.pushScope(); 30 try { 31 for (const stmt of this._else) { 32 ctx.analyze(stmt); 33 } 34 } finally { 35 ctx.popScope(); 36 } 37 } 38 } 39 40 /** Returns true when all required builder calls are present. */ 41 get isValid(): boolean { 42 return this.missingRequiredCalls().length === 0; 43 } 44 45 condition(condition: IfCondition): this { 46 this._condition = condition; 47 return this; 48 } 49 50 otherwise(...items: Array<DoExpr>): this { 51 this._else = items; 52 return this; 53 } 54 55 override toAst() { 56 this.$validate(); 57 58 const thenStatements = this.$do(); 59 const elseStatements = this._else ? new BlockPyDsl(...this._else).$do() : undefined; 60 61 return py.factory.createIfStatement( 62 this.$node(this._condition!), 63 [...thenStatements], 64 elseStatements ? [...elseStatements] : undefined, 65 ); 66 } 67 68 $validate(): asserts this is this & { 69 _condition: IfCondition; 70 } { 71 const missing = this.missingRequiredCalls(); 72 if (missing.length === 0) return; 73 throw new Error(`If statement missing ${missing.join(' and ')}`); 74 } 75 76 private missingRequiredCalls(): ReadonlyArray<string> { 77 const missing: Array<string> = []; 78 if (!this._condition) missing.push('.condition()'); 79 if (this._do.length === 0) missing.push('.do()'); 80 return missing; 81 } 82}