Extend the inferred model #679
-
I need to manipulate the inferred model before code generation. My grammar looks like this:
Consequently, the model generated by Langium is:
I need to manipulate the generated model and add it a new instructions before code generation. I need a new instruction named Synchronize :
Then, I can create an object implementing Synchronize but I can not add it to Job.instructions because it does not match the Instruction type. Is it possible to generate an interface for Instruction with If and Return extending it ? In this case, I can also extend it in Synchronize and add it to Job.instructions ? Or is there a way solution to do this ? Thanks for your answer. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Hey @lelandaisb, you can declare types inside of your grammar to fine tune how the type inference generates the final types. This feature is still work in progress, but it has already been released in Langium 0.4. There might be some errors, which prevent you from doing this, but I believe you could accomplish your goals like this: interface Synchronize {
...
}
type InstructionType = If | Return | ... | Synchronize;
interface Job {
name: string
instructions: InstructionType[]
}
...
Instruction returns InstructionType: If | Return | ...
If: 'if' '(' condition=Expression ')' then=Instruction (=>'else' else=Instruction)?;
Return: 'return' expression=Expression;
...
Job returns Job: name=ID ':' instructions+=Instruction*; |
Beta Was this translation helpful? Give feedback.
-
Hey @msujew, Thanks a lot for your quick answer. I can't do that with a type declaration ? |
Beta Was this translation helpful? Give feedback.
-
@lelandaisb As mentioned, the declared types still have a few issues. Seems like this is one of them. Anyway, I believe your only other option until we get to refactoring that feature (it is on our roadmap) is to go behind the back of the TypeScript type checker and do something like: job.instructions.push({...} as unknown as Instruction); On another note, creating synthetic nodes isn't really recommended, as it usually leads to problems like these. Is there a way for you to generate that information on the fly while running your generator? |
Beta Was this translation helpful? Give feedback.
-
Thanks for your answer. |
Beta Was this translation helpful? Give feedback.
Thanks for your answer.
I can generate the Synchronize interface on the fly. My problem was to add the instruction to the list in a job. I will go behind the back of the TypeScript type checker like you suggest.
Thanks again.