Résultat du TP en C sur Forth
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

functions.c 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "functions.h"
  2. #include "definitions.h"
  3. #include "pileInt.h"
  4. #include <stdlib.h>
  5. #include <string.h>
  6. static struct PileInt callStack;
  7. struct FunctionsList {
  8. struct FunctionsList* next;
  9. char* functionName;
  10. programPointer instructionPointer;
  11. };
  12. void initFunctions() {
  13. initPileI(&callStack);
  14. }
  15. void prependFunction(struct State* state) {
  16. int functionNameLength;
  17. struct FunctionsList* aux = state->functions;
  18. state->functions = (struct FunctionsList*) malloc(sizeof(struct FunctionsList));
  19. state->functions->next = aux;
  20. ++(state->instructionPointer);
  21. functionNameLength = strlen(getCurrentToken(state)) + 1; // counting the '\0'
  22. state->functions->functionName = (char*)malloc(sizeof(char)*functionNameLength);
  23. strncpy(state->functions->functionName, getCurrentToken(state), functionNameLength);
  24. state->functions->instructionPointer = state->instructionPointer;
  25. state->mode = WAIT_FOR_SEMICOLON;
  26. }
  27. void endFunctions(struct FunctionsList** pfunctions) {
  28. struct FunctionsList* functions = *pfunctions;
  29. struct FunctionsList* aux;
  30. while (functions != NULL) {
  31. aux = functions;
  32. functions = functions->next;
  33. free(aux->functionName);
  34. free(aux);
  35. }
  36. *pfunctions = NULL;
  37. }
  38. int tryCallFunctions(char* func, struct State* state) {
  39. struct FunctionsList* aux = state->functions;
  40. while (aux != NULL) {
  41. if (!strcmp(aux->functionName, func)) {
  42. pushPileI(&callStack, state->instructionPointer);
  43. state->instructionPointer = aux->instructionPointer;
  44. return 1;
  45. }
  46. aux = aux->next;
  47. }
  48. return 0;
  49. }
  50. void returnFromFunction(struct State* state) {
  51. state->instructionPointer = topPileI(&callStack);
  52. popPileI(&callStack);
  53. }
  54. void colonCmd(struct State* state) {
  55. if (state->mode == EXECUTE) {
  56. prependFunction(state);
  57. }
  58. }
  59. void semicolonCmd(struct State* state) {
  60. if (state->mode == WAIT_FOR_SEMICOLON) {
  61. state->mode = EXECUTE;
  62. } else if (state->mode == EXECUTE) {
  63. returnFromFunction(state);
  64. }
  65. }